PayWeavePayWeaveBack to Home
Apps

Fastify Integration

The @payweave/fastify package leverages Fastify's hook system. Instead of positional middleware, you attach payweave.charge() using Fastify's preHandler route option, which runs before your handler on a per-route basis.

Installation

Terminal
npm install @payweave/fastify

Basic setup

TypeScript
import Fastify from 'fastify';
import { Payweave } from '@payweave/fastify';

const app = Fastify();
const payweave = new Payweave(
  process.env.PAYWEAVE_APP_ID!,
  process.env.PAYWEAVE_APP_SECRET!
);

app.get('/api/geocode', {
  preHandler: payweave.charge({
    price: '0.003',
    description: 'Geocoding API',
  }),
}, async (req, reply) => {
  return { lat: 37.77, lng: -122.42 };
});

app.listen({ port: 3000 });
The key difference from Express: pass payweave.charge() inside the route options object as preHandler, not as a positional argument.

Multiple preHandlers

Fastify supports an array of preHandler hooks. Combine PayWeave with your own validation or auth hooks:

TypeScript
app.post('/api/analyze', {
  preHandler: [
    validateApiKey,
    payweave.charge({
      price: '0.01',
      description: 'Analysis API',
    }),
  ],
}, async (req, reply) => {
  return { analysis: '...' };
});

Dynamic pricing

The price option accepts a function receiving the Fastify request:

TypeScript
app.post('/api/render', {
  preHandler: payweave.charge({
    price: (req) => {
      const size = req.body.width * req.body.height;
      return size > 1000000 ? '0.05' : '0.01';
    },
    description: 'Image rendering',
  }),
}, async (req, reply) => {
  return { imageUrl: '...' };
});

Accessing payment data

After payment verification, the receipt is available on the request via req.payweave:

TypeScript
app.get('/api/data', {
  preHandler: payweave.charge({ price: '0.001', description: 'Data API' }),
}, async (req, reply) => {
  const { txId, payer, amount } = req.payweave;
  return { data: '...', txId };
});
You can also register PayWeave as a Fastify plugin for app-wide configuration. Use app.register(payweave.plugin) to set defaults like description and metadata across all routes.