@mandate/middleware package lets you gate any API endpoint behind a Mandate payment check. When an agent sends a request without a valid payment proof, the middleware returns a 402 Payment Required response with a structured challenge. When the agent presents a valid proof, the middleware verifies it with the Mandate API and calls your handler — you get the agent ID, mandate ID, and transaction ID to use in your own logging or business logic.
Install the middleware
Hono
UserequireKyaPayment as route-level middleware:
Express
UserequireKyaPaymentExpress as route middleware:
Middleware options
BothrequireKyaPayment and requireKyaPaymentExpress accept the same KyaPaymentOptions object:
How the 402 response works
When a request arrives without anX-Payment-Proof header, the middleware returns 402 Payment Required with a JSON body and an X-Payment-Challenge header containing a base64url-encoded challenge:
scheme is kya-sandbox when you use a sandbox API key (ky_sand_...) and kya-usdc for production keys. The Mandate SDK reads this challenge and handles the full payment flow automatically — your seller-side code does not need to do anything else.
Verification flow
For every request that includes anX-Payment-Proof header, the middleware:
- Decodes the base64url proof from the header.
- Calls
POST /v1/payments/verifyon the Mandate API with the proof, your merchant domain, and the expected amount and currency. - If verification fails, returns
402with{ "error": "payment_verification_failed" }. - If verification succeeds, sets the agent context on the request and calls
next().
The middleware calls
POST /v1/payments/verify on every verified request. Each successful verification records a transaction and consumes the proof’s nonce — the same proof cannot be reused.
