# How to charge AI agents per API call with HTTP 402 (MPP and x402)

> How HTTP 402 agent payments work with MPP (Stripe Shared Payment Tokens) and x402, what breaks in production, and how to implement them in TypeScript.

- Published 2026-10-28, updated 2026-10-28
- URL: https://softreuse.com/guides/charge-ai-agents-http-402

**Short answer:** return `402 Payment Required` with a payment challenge, let the agent pay and retry with proof, verify the proof, run your handler once, and return the response with a receipt. Two protocols do this today: **MPP** (Stripe and Tempo; cards through Stripe Shared Payment Tokens, and stablecoins) and **x402** (Coinbase; mostly USDC through a facilitator). The protocol is the easy half. The hard half is what happens around the money: retries, duplicates, failures after the charge, and crashes.

## Why agents pay per request

An agent calling your API can't fill in a checkout page or sign up for a plan. It can pay a few cents for one call, if the API tells it how. HTTP has had a status code for this since the 1990s: `402 Payment Required`, still listed as "reserved for future use" in [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#name-402-payment-required). Agent payment protocols give it a format.

## The flow

1. The agent calls your endpoint without paying.
2. Your server answers `402` with the price and the ways it accepts payment.
3. The agent's wallet pays or authorises the payment and the agent **retries the same request** with proof.
4. Your server verifies the proof, takes the money, runs the handler and returns the result with a receipt.

## MPP and x402 compared

| | MPP (Machine Payments Protocol) | x402 (version 2) |
|---|---|---|
| Authors | Stripe and Tempo; IETF Internet-Draft [draft-ryan-httpauth-payment](https://datatracker.ietf.org/doc/html/draft-ryan-httpauth-payment-01) | Coinbase; [x402 specification](https://github.com/coinbase/x402/tree/main/specs) |
| Challenge | `WWW-Authenticate: Payment id=…, method=…, intent="charge", request=…` (one per method) | `PAYMENT-REQUIRED`: base64 JSON with an `accepts` list |
| Proof | `Authorization: Payment <base64url JSON>` echoing the challenge | `PAYMENT-SIGNATURE`: base64 JSON payload |
| Receipt | `Payment-Receipt` | `PAYMENT-RESPONSE` |
| Payment methods | Pluggable: Stripe Shared Payment Tokens (cards, wallets), stablecoins on Tempo, others | Schemes such as `exact` on EVM networks (USDC on Base) |
| Who verifies | Your server, with the method's provider (e.g. Stripe creates a PaymentIntent) | A facilitator: `POST /verify` and `POST /settle` |
| Smallest practical price | 0.50 USD for Stripe card payments (Stripe's documented minimum); 0.01 USDC for stablecoins on Stripe | Down to USDC's smallest unit (6 decimals), subject to your facilitator |

You don't have to choose. A server can send both in the same 402: one `WWW-Authenticate: Payment` challenge per MPP method and a `PAYMENT-REQUIRED` header for x402, and the agent pays with whichever it supports.

## What goes wrong in production

The SDK samples cover the happy path. Agents retry aggressively, and every one of these cases is about money:

- **The response is lost after the charge.** The agent retries with the same credential. If you charge again, it paid twice; if you answer "already used", it paid for nothing. Store the paid response and replay it to the same request.
- **Two copies arrive at once.** Without a lock, both verify and both charge. Use a database row per credential as the lock; let one through and answer the other `409`.
- **Your handler fails after the money moved.** Refund (cards), or with x402 verify first and **settle only after the handler succeeds**, so a failed call costs nothing.
- **The process crashes between charging and answering.** Record the charge before running the handler, so the retry delivers without charging again. Make your own side effects idempotent on the payment's id.
- **A cheap challenge pays for an expensive call.** An HMAC proves you issued a challenge, not what it was for. Bind the price, the route and a digest of the request body into it, and make it single-use.
- **One payment token is presented twice.** Keep the token id unique across all payments, not just per challenge.
- **The facilitator or Stripe times out.** Use idempotency keys (MPP's Stripe method uses `<challenge id>_<token>`) so a retry returns the original outcome. A settlement that may or may not have happened must be reconciled, not retried blindly.
- **Your own agent loops on a paid API.** Give it a per-request cap, a total budget and an allow-list of origins, and never pay an expired challenge.

## Implementing it in TypeScript

With the protocol SDKs alone ([mppx](https://mpp.dev) for MPP, [@x402/core](https://github.com/coinbase/x402) for x402) you get challenges and verification, and you build the ledger and failure handling around them. With [Agent Payments](https://softreuse.com/products/agent-payments), one paywall does both protocols and the production layer:

```ts
import { Pool } from "pg";
import { createPaywall, PostgresStore, stripeMethod, x402Facilitator } from "@softreuse/agent-payments";

const paywall = createPaywall({
  store: new PostgresStore(new Pool({ connectionString: process.env.DATABASE_URL })),
  mpp: {
    secret: process.env.MPP_SECRET!, // 32+ random bytes; signs challenges
    methods: [stripeMethod({ secretKey: process.env.STRIPE_SECRET_KEY!, networkId: process.env.STRIPE_PROFILE_ID! })],
  },
  x402: {
    facilitator: x402Facilitator({ url: process.env.X402_FACILITATOR_URL! }),
    accepts: [{ network: "eip155:8453", asset: process.env.USDC_ADDRESS!, payTo: process.env.PAY_TO!, decimals: 6, currency: "usd" }],
  },
});

// app/api/generate/route.ts: two cents per call
export const POST = paywall.protect({ price: { amount: "0.02", currency: "usd" } }, async (request, { payment }) => {
  const { prompt } = await request.json();
  return Response.json(await generate(prompt, { idempotencyKey: payment.key })); // runs once per payment
});
```

At two cents, only x402 is offered (below Stripe's card minimum); at 50 cents and above, agents can pay either way.

## The paying side

If your agent calls paid APIs, wrap its `fetch`:

```ts
import { createPayingFetch } from "@softreuse/agent-payments";

const paidFetch = createPayingFetch({
  budget: { currency: "usd", maxPerRequest: "0.25", maxTotal: "5.00" },
  allowedOrigins: ["https://api.example.com"],
  mpp: { stripe: async ({ request }) => ({ payload: { spt: await issueSharedPaymentToken(request) } }) },
});
```

It reads both protocols from the 402, picks the cheapest offer within the budget, pays once, and resends the **same** credential on a network error so the server replays instead of charging again.

## Checklist before going live

- Test with a Stripe sandbox (`npx @stripe/link-cli mpp pay <url>`) and on Base Sepolia (`eip155:84532`) before live mode.
- Validate input before the paywall, so a malformed request gets `400`, not a `402`.
- Charge only for successful responses, and decide what "successful" means for your API.
- Monitor payments that were taken but not delivered, and settlements in doubt.
- Decide how agent sales are taxed in your jurisdiction.

## Sources

- [RFC 9110 §15.5.3: 402 Payment Required](https://www.rfc-editor.org/rfc/rfc9110#name-402-payment-required)
- [draft-ryan-httpauth-payment: The "Payment" HTTP authentication scheme](https://datatracker.ietf.org/doc/html/draft-ryan-httpauth-payment-01) and [draft-stripe-charge](https://paymentauth.org/draft-stripe-charge-00)
- [Stripe: accept machine payments with MPP](https://docs.stripe.com/payments/machine/mpp)
- [x402 v2 specification and HTTP transport](https://github.com/coinbase/x402/tree/main/specs)

## Frequently asked questions

### What is HTTP 402 Payment Required?

A status code that HTTP reserved for payments decades ago (RFC 9110 still lists it as reserved for future use). Agent payment protocols now use it: the server answers 402 with what to pay, the client pays and retries the same request with proof of payment.

### What is the difference between MPP and x402?

MPP (Machine Payments Protocol, co-authored by Stripe and Tempo) is an HTTP authentication scheme: the challenge comes in WWW-Authenticate: Payment and the proof in Authorization: Payment, with pluggable methods such as Stripe Shared Payment Tokens for cards. x402 (from Coinbase) carries base64 JSON in PAYMENT-REQUIRED, PAYMENT-SIGNATURE and PAYMENT-RESPONSE headers and is used mostly for stablecoins such as USDC, verified and settled through a facilitator. A server can offer both in the same 402.

### Can I accept card payments from AI agents?

Yes, through MPP with Stripe Shared Payment Tokens: the agent's wallet issues a token scoped to the amount, and your server creates and confirms a Stripe PaymentIntent with it. Shared Payment Tokens are a Stripe preview feature and Stripe documents a 0.50 USD minimum for card payments this way; smaller amounts suit stablecoins.

### How do I avoid charging an agent twice when it retries?

Record each payment credential in a database row that acts as a lock, record the charge before running your handler, and store the paid response. A retry with the same credential then gets the stored response instead of a second charge, and a concurrent duplicate waits for the first.

### Do I need a crypto wallet to charge agents?

Not for MPP with Stripe: payments arrive in your Stripe balance like any card payment. For x402 you need a receiving address and a facilitator that verifies and settles the payment on chain.

### Is there a TypeScript library that handles both protocols?

The reference SDKs are mppx for MPP and @x402/core for x402. Softreuse's Agent Payments module puts both protocols behind one paywall with a Postgres ledger, exactly-once charging, refunds on failure and a budget-capped paying client, with zero runtime dependencies.
