Framework adapters and core logic for L402 payment-gated HTTP routes.
Supports:
- Express middleware
- Hono middleware
- Next.js route wrapper (
@zbdpay/agent-pay/next)
Want to run this immediately? See Examples (Fastest Way to Run).
- Node.js
>=22 - npm
npm install @zbdpay/agent-payimport express from "express";
import { createExpressPaymentMiddleware } from "@zbdpay/agent-pay";
const app = express();
app.get(
"/protected",
createExpressPaymentMiddleware({
amount: 21,
apiKey: process.env.ZBD_API_KEY,
}),
(_req, res) => {
res.json({ ok: true });
},
);import { Hono } from "hono";
import { createHonoPaymentMiddleware } from "@zbdpay/agent-pay";
const app = new Hono();
app.use(
"/protected",
createHonoPaymentMiddleware({
amount: 21,
apiKey: process.env.ZBD_API_KEY,
}),
);import { withPaymentRequired } from "@zbdpay/agent-pay/next";
export const GET = withPaymentRequired(
{
amount: 21,
apiKey: process.env.ZBD_API_KEY,
},
async () => Response.json({ ok: true }),
);amount: number or async resolver functioncurrency:"SAT" | "USD"(default"SAT")apiKey: optional, falls back toZBD_API_KEYtokenStorePath: optional, defaults to~/.zbd-wallet/server-tokens.json
ZBD_API_KEY: required unless passed via configZBD_API_BASE_URL: optional, defaulthttps://api.zbdpay.com
Use this local script path first to validate your environment before integrating middleware into your app.
examples/http-server.mjs: minimal Node HTTP server usingcreatePaymentMiddlewareFoundation
Run locally from this repo:
npm run build
ZBD_API_KEY=<your_api_key> npm run example:http-serverEnable verbose host-side debug logs:
ZBD_PAY_DEBUG=1 ZBD_API_KEY=<your_api_key> npm run example:http-serverIn a second terminal, consume the paid route with your local wallet CLI:
zbdw fetch "http://localhost:8787/protected" --max-sats 100When a request has no valid auth proof:
- Middleware creates a charge (
/v0/charges) - Returns
402with:- JSON body:
payment_required+ challenge fields WWW-Authenticateheader:L402 macaroon="...", invoice="..."
- JSON body:
When a request has auth proof:
- Parse
Authorization(L402orLSAT) - Verify signed macaroon payload
- Verify resource path, amount, expiry, payment hash
- Confirm charge settlement via ZBD API
- Allow or deny request
error.code may be:
configuration_errorpayment_requiredinvalid_credentialinvalid_payment_proofresource_mismatchamount_mismatchtoken_expiredpricing_errorinvoice_creation_failed
Main package:
createExpressPaymentMiddlewarecreateHonoPaymentMiddlewarecreatePaymentMiddlewareFoundationAgentPayErrorcreateConfigurationError- related TS types
Subpath export:
@zbdpay/agent-pay/next->withPaymentRequired
npm run build
npm run test
npm run lint
npm run typecheck
npm run smoke:adapters
npm run example:http-server
npm run release:dry-run- Middleware stores verified settled tokens in a local file token store by default.
- For production, set
tokenStorePathto durable storage if required by your deployment model.