x402 payments for Fastify
paygate ships a first-class Fastify plugin. Register it once with your merchant id, then gate routes either declaratively through route config or imperatively inside a handler.
Register the plugin
Both styles are supported; mix them freely per route.
import Fastify from "fastify"; import paygate from "paygate/fastify"; const app = Fastify(); await app.register(paygate, { merchantId: process.env.PAYGATE_MERCHANT_ID }); // Declarative: paywall from route config. app.get( "/api/data", { config: { paygate: { priceCents: 10 } } }, async (req, reply) => reply.send({ data: "premium" }), ); // Imperative: decide inside the handler. app.get("/api/premium", async (req, reply) => { const { paid } = await req.paygatePay({ priceCents: 25 }); if (!paid) return; // 402 challenge already sent reply.send({ data: "…" }); }); await app.listen({ port: 3000 });
Verification and settlement
The plugin performs the same verify-then-settle cycle as the Express middleware: challenge on missing payment, facilitator verification before the handler, settlement after success, receipt attached to `req.paygate`.
On the buyer side, any AI agent can pay your endpoint with `npx payagent pay <url>` or the payagent SDK — the 402 challenge your route now returns is the whole integration contract.
Scaffold a new seller
npx paygate init --framework fastify --wallet 0xYourAddress --price 10
Pricing guidance
- Integer cents only; 1 cent is the minimum price. Use dynamic `priceCents` functions to price by payload size or model depth rather than inventing tiers.
- Fastify's route-config style keeps prices visible next to the route definition — reviewers see the price where they see the handler.
FAQ
- Can I run paygate on only some routes?
- Yes. Routes without a `paygate` config entry (and without an imperative paygatePay call) are untouched — the plugin only intervenes where a price is declared.
- What happens on facilitator downtime?
- Verification failure returns 402 to the buyer rather than serving unpaid content — the middleware fails closed.
Is your service agent-ready?
Run the free readiness scan — it inspects your live endpoint's discoverability, machine-readable contracts, and payment support, then tells you the highest-impact fix.
