AI agents can now pay for API calls themselves: the server answers 402 Payment Required, the agent pays, and it retries with proof. Stripe co-authored one protocol for this (MPP, with Shared Payment Tokens from cards and wallets) and Coinbase another (x402, mostly stablecoins). Their SDKs give you the 402 and a verify call. What they leave to you is everything that happens around money: agents retry, connections drop after the charge, two copies of a request arrive at once, your handler fails after the card was charged, the process dies mid-request. Agent Payments is that production layer: one paywall for both protocols that charges exactly once, and a client that lets your own agents pay within a budget.
The failure cases it handles
| What happens | What the kit does |
|---|---|
| The agent paid, the response got lost, the agent retries with the same credential | The ledger replays the stored response: no second charge and no "already used" error |
| Two copies of the same paid request arrive together | A Postgres row lock lets exactly one charge; the other gets 409 and then the replay |
Your handler throws or returns 500 after the card was charged |
Refunded through Stripe automatically; over x402, payment is only settled after your handler succeeds |
| The server crashes between charging and responding | The charge is recorded before your handler runs; the retry delivers without charging again |
| A challenge from your $0.01 endpoint is used on your $5 endpoint, or with a different body | Refused: challenges are HMAC-bound to price, route, body digest and expiry, and pay once |
| You raised a price and an agent pays the old challenge | Refused with a fresh challenge at the new price |
An x402 payment says amount: 1 or names another payTo |
Refused before the facilitator is called; the facilitator only ever sees your terms |
| Stripe or the facilitator is down | 503 Retry-After; the same credential works afterwards, charged once (Stripe idempotency keys) |
| An x402 settlement is pending or its outcome is unknown | Response withheld, transaction recorded, row flagged in "needs attention" |
| Your agent gets into a loop on a paid API | createPayingFetch stops at the per-request and total budget, and only pays the origins you allow |
How it looks
const paywall = createPaywall({
store: new PostgresStore(pool),
mpp: { secret: process.env.MPP_SECRET!, methods: [stripeMethod({ secretKey, networkId: profileId })] },
x402: { facilitator: x402Facilitator({ url: facilitatorUrl }), accepts: [usdcOnBase] },
});
// app/api/generate/route.ts: two cents per call, any agent, either protocol
export const POST = paywall.protect({ price: { amount: "0.02", currency: "usd" } }, async (request, { payment }) => {
return Response.json(await generate(await request.json(), payment.key)); // runs once per payment
});
// and on the agent side
const paidFetch = createPayingFetch({ budget: { currency: "usd", maxPerRequest: "0.25", maxTotal: "5.00" }, mpp: { stripe: issueSpt } });
What's in the package
src/ ~1,700 lines of strict TypeScript, zero runtime dependencies
migrations/ one idempotent SQL file (the payment ledger, with revenue and "needs attention" queries)
tests/ 122 tests: both protocols end to end, concurrency, crash recovery, refunds, settlement failures,
the paying client and its budget, interop vectors from mppx and @x402/core, store contract (Memory + Postgres)
examples/ offline demo (npm run demo), Next.js setup, fixed and dynamic prices, ledger route, purge cron,
a paying agent, node:http server
docs/ ARCHITECTURE.md (binding, ledger, exactly-once case by case), SECURITY.md (threat model, checklist)
README.md CHANGELOG.md LICENSE.md
npm run demo runs a paid API and an agent with a $1 budget, with Stripe and the facilitator simulated: a 402 carrying both protocols, a two-cent call over x402, a 75-cent call over Stripe whose response is lost and replayed with one PaymentIntent, and a call the budget refuses.
Who it is for
Teams on Node and TypeScript who want to charge agents per call: AI APIs (generation, search, scraping, data) and anyone pricing an endpoint in cents where a checkout page makes no sense. And teams building agents that must pay for APIs without being able to overspend.
Who it is not for
- Selling to humans: a checkout page with Stripe Checkout is simpler and better understood by people.
- Subscriptions, MPP sessions or streaming payments: v1 is one charge per request. Prepaid credits can be built on
onPaid. - Holding keys or signing payments: wallet signing and Shared Payment Token issuance stay with your provider's SDK, behind the client's callbacks.
- Stripe accounts without Shared Payment Tokens: SPTs are a Stripe preview feature; without access, use the x402 side only.
- Making idempotent the rest of your API: for ordinary
POSTs, that's Idempotent Requests.
New to this? Read the guide: How to charge AI agents per API call with HTTP 402 (MPP and x402).
Read the full Agent Payments documentation (API, architecture, threat model) before you buy.
What you get
- One paywall answers 402 with both protocols: MPP (WWW-Authenticate: Payment, Stripe Shared Payment Tokens) and x402 v2 (PAYMENT-REQUIRED, via any facilitator)
- Charged exactly once per payment: a ledger row lock per credential, single-use tokens, and the paid response replayed to retries instead of a second charge
- Failure-safe: refunds over Stripe when your handler fails, x402 settled only after success, crash recovery that delivers without charging again
- MPP challenges HMAC-bound to price, route, request body and expiry, so a cheap or stale challenge can never pay for another request
- createPayingFetch for your agents: pays 402s within per-request and total budgets, allowed origins and a currency, and retries with the same credential
- Postgres ledger with provider references, revenue SQL and a 'needs attention' list; fixed or per-request prices with exact decimal conversion
- Wire format checked against the reference SDKs (mppx 0.15.0, @x402/core 2.28.0) with fixed interop vectors
- 122 automated tests (12 run against a real PostgreSQL), runnable offline demo, architecture and security docs, changelog
Will it work in my project?
- Node.js 20 or newer (tested on 20, 22, 24 and 26)
- PostgreSQL 12+ for the included store (any database via the PaymentStore interface)
- For MPP: a Stripe account with access to Shared Payment Tokens (a Stripe preview feature) and a Stripe profile
- For x402: an x402 v2 facilitator and a wallet address to receive stablecoins
- TypeScript 5+ recommended; zero runtime dependencies
What happens after you buy
- Pay on Stripe. You need a Softreuse account (free, email confirmation). Card details go to Stripe, never to us.
- Access is granted automatically as soon as Stripe confirms the payment, usually within seconds. Stripe emails the receipt.
- Download from your account at any time: the .zip, its SHA-256 checksum, and the full documentation. Links are generated on demand, so you can come back in a year.
- Unzip,
npm install,npm test,npm run demoto see it work before you touch your own code. - Updates: every v1.x release appears in the same place, free.
Not working as documented? Full refund within 14 days. Questions before buying: support@softreuse.com.
Security
The security design is documented in the package (docs/SECURITY.md) with a threat model. In short:
- Pay once, served once per request: a ledger row per payment credential with a Postgres primary-key lock; single-use tokens (unique index); replay only for the identical request. Tested with concurrent requests against a real database.
- Challenges can't be forged or moved: MPP challenges are HMAC-SHA256-bound (your ≥ 32-byte secret, constant-time check) to price, route, request body digest and expiry, the binding the IETF draft recommends and the reference SDK uses. x402 payloads must match your terms exactly, and the facilitator is only ever called with your requirements.
- No charge for failed work, no double charge: Stripe refunds on handler failure, x402 settles after success, charges are recorded before your handler runs, and Stripe calls are idempotent on challenge and token. The ledger fails closed when the database is unavailable.
- Agents can't overspend: the paying client enforces per-request and total budgets, a currency and allowed origins, ignores expired challenges, reserves budget atomically under concurrency, and never follows redirects with a payment attached.
- No secrets in logs: logs carry routes, amounts and statuses, never tokens, credentials or bodies. Tested.
- Injection: all SQL values are bound parameters with a validated table name; challenge descriptions are sanitised before going into headers.
- Supply chain: zero runtime dependencies;
npm audit --omit=devis clean. - Honest limits: it doesn't hold keys or sign payments, trusts the x402 facilitator you choose, doesn't authenticate users, and leaves pending or unknown settlements for you to resolve (they're flagged). Tax treatment of agent sales is yours to decide. These are documented along with a deployment checklist.
Versions & changelog
v1.0.0 · Oct 28, 2026
Initial release.
createPaywall: HTTP 402 for MPP (WWW-Authenticate: Payment, draft-ryan-httpauth-payment) and x402 v2 (PAYMENT-REQUIRED/PAYMENT-SIGNATURE/PAYMENT-RESPONSE) from one price, on one route; fixed or per-request prices with exact decimal conversion.- MPP challenges bound statelessly with HMAC-SHA256 (§5.1.2.1.1) to price, route, body digest (RFC 9530) and expiry; single-use; RFC 9457 problem details with the paymentauth.org problem types;
Payment-ReceiptwithCache-Control: private. - Exactly-once charging and delivery: ledger row lock per credential, single-use proofs, response replay to retries,
409for concurrent duplicates, crash recovery that never charges twice, fail-closed on ledger outage. - Failure handling: refund on handler failure (MPP), settle-after-success by default (x402),
settle: "before"option,settle_failedrecords for pending or unknown settlements,needsAttentionlisting. stripeMethod: MPPstripecharge intent (draft-stripe-charge) with Shared Payment Tokens, idempotent PaymentIntent creation and refunds, minimums and currencies.x402Facilitator: verify/settle client for any x402 v2 facilitator, with timeouts and outage detection.createPayingFetch: pays 402s (both protocols) within per-request and total budgets, allowed origins and a currency, retries with the same credential, never pays expired challenges or follows redirects with a payment.- Stores:
PostgresStoreandMemoryStorewith a contract test suite;toNodeHandlerfornode:http/Express. - 122 automated tests, including interop vectors from
mppx0.15.0 and@x402/core2.28.0 and a store contract suite run against a real PostgreSQL.
License
Softreuse Commercial License — Agent Payments
Version 1.0 · Copyright © Softreuse. All rights reserved.
"Softreuse" is the trading name of the seller identified in the Terms of Sale at https://softreuse.com/terms. Those Terms are the authoritative source for who the seller is and how to reach them.
This is the license that comes with your purchase of this package ("the Software"). Please read it; it is short on purpose.
1. What you may do
You (the individual or single company that purchased the Software, "Licensee") may, forever, for the versions covered by Section 4:
- use, copy and modify the source code in any number of projects that you or your company own or build for your own use, commercial or not;
- let your employees and contractors work with the source for those projects;
- ship products that contain or are built from the Software (including compiled or bundled) to your own users and customers;
- keep your modifications private.
2. What you may not do
- Redistribute, resell, sublicense, publish or share the Software's source code, in original or modified form, as a standalone product, template, boilerplate, starter kit, library, SaaS feature-for-feature clone, course material or marketplace listing.
- Publish the Software's source in a public repository or package registry. (Private repositories of your team are fine. Publishing an application that merely uses the Software is fine.)
- Share your download access or purchase with people outside your company.
- Remove copyright or license notices from the files.
If you are a consultancy building a product for a client, the client needs their own license unless the client is the owner of the resulting project and you transfer the project (not the Software as a standalone asset).
3. Ownership
Softreuse keeps ownership of the Software. You own everything you build with it.
4. Updates
Your purchase includes all releases of this product within the major version you bought (for example every 1.x release if you bought 1.0.0), delivered through your Softreuse account. A new major version (2.0.0) is a new paid release; versions you already have keep working under this license forever.
5. Warranty and liability
The Software is provided "as is", without warranty of any kind. Softreuse tests the Software and publishes known limitations, but you are responsible for evaluating it for your use, including security review of your own deployment. To the maximum extent permitted by law, Softreuse's total liability for any claim is limited to the amount you paid for the Software, and Softreuse is not liable for indirect or consequential damages (lost profits, lost data, business interruption).
6. Refunds
If the Software does not work as documented, tell us within 14 days of purchase and we will refund you in full. Refunded licenses end at the moment of refund.
7. Termination
This license ends automatically if you breach Section 2. Sections 3, 5 and 7 survive termination.
8. Contact
Questions
Why not just ask an AI to write this?
You can, and for many things you should. A model will write "return 402, check the header, call verify" in seconds, and the protocol SDKs do that part well. The hard part is what happens around the money: an agent retrying after a lost response, two copies of a paid request at once, a handler failing after the card was charged, a crash between charging and answering, a cheap challenge replayed on an expensive route, a payment token presented twice. This package comes with tests for each of those, run against a real PostgreSQL database, wire-format vectors from the reference SDKs (mppx and @x402/core), and a written threat model. You still review the code. You just start from something that has already been tested against the ways payments go wrong.
What exactly do I get after paying?
A .zip with the full TypeScript source, tests, runnable examples, SQL migration, architecture and security docs, a changelog and the licence. It's available in your Softreuse account the moment Stripe confirms payment, and you can download it again any time.
What does the licence allow?
Use it in unlimited projects you or your company own, commercial or not, and modify it freely. You can't resell or redistribute it as a standalone product or library. The full text is on the product page and inside the package.
Which versions does my purchase cover?
Every release of the major version you bought. Buy v1 and you get all v1.x updates (fixes and backwards-compatible features) for free. A future v2 with breaking changes would be a separate paid release; v1 stays yours either way.
Will it work with my stack?
It targets Node.js 20 or newer, TypeScript, and PostgreSQL for the included ledger, with zero runtime dependencies. It wraps any Web-standard Request/Response handler, so it works in Next.js route handlers, Hono, Remix, Bun and Deno, and in node:http or Express through the included adapter. For MPP you need a Stripe account with access to Shared Payment Tokens (a Stripe preview feature); for x402 you need an x402 v2 facilitator and a receiving wallet. You can use either protocol alone. It does not sign payments or hold keys, and it is not for subscriptions or streaming payments.
What if it doesn't work for me?
Email support@softreuse.com. If it doesn't work as documented and we can't fix it, you get a full refund within 14 days of purchase. No forms, no hoops.
Is checkout secure? Do you see my card?
Payment happens on Stripe's hosted checkout page. Your card details never touch Softreuse servers. Access is granted only after Stripe confirms the payment to us by a signed server-to-server message.
Do you charge VAT or sales tax?
Listed prices exclude VAT and sales tax. Where it applies, tax is calculated at checkout from your billing address and added to the price before you pay. If you buy as a business, you can enter your company name and VAT number at checkout. Stripe sends a receipt and an invoice for every purchase.
Related modules
- Reliable Webhooks: Receive webhooks without losing, duplicating or double-processing them.
- Idempotent Requests: Make POST endpoints safe to retry: no double charges, no duplicate orders.
- Outbound Webhooks: Send webhooks to your customers like Stripe does: signed, retried, logged and safe to point anywhere.