Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Agentic payments:
x402 & AP2.
An agent that can browse and call tools eventually hits a paywall — an API that costs a cent a call, a dataset behind a charge, a compute job to rent. Stopping to ask a human defeats the point of autonomy; handing the agent your card defeats your bank balance. The answer is a machine-native checkout (x402) plus a signed mandate that says exactly how much this agent may spend, on what, before it can spend a cent. This handbook is how those rails work — and how to keep a looping agent from spending your month's budget in a minute.
The 402 revival: a checkout for machines
HTTP has always had a status code reserved for this: 402 Payment Required, dormant since the 1990s. x402 finally uses it. An agent requests a resource; the server replies 402 with payment terms (amount, address, token). The agent pays — typically a tiny stablecoin transfer — and retries the request carrying proof of payment. This time it gets 200 and the resource.
price + terms
proof attached
No checkout page, no human. Payment becomes just another part of the protocol — which is exactly what an autonomous agent needs. But a checkout an agent can drive is also a checkout a hijacked agent can drive. That's why x402 is only half the story; the other half is the authority the agent carries into it.
x402 on the wire: headers, facilitator, settle
Three roles take part: the resource server that wants payment, the client (your agent), and a facilitator, a service that verifies payments and settles them on the blockchain so the resource server doesn't have to run chain infrastructure. In version 2 of the x402 specification, the HTTP transport carries each step in a base64-encoded JSON header:
2. 402 Payment Required PAYMENT-REQUIRED: { x402Version: 2, accepts: [{ scheme: "exact", network, amount, asset, payTo, maxTimeoutSeconds }] }
3. GET /premium-data PAYMENT-SIGNATURE: { accepted: {…the option chosen…}, payload: { signature, authorization } }
4. server → facilitator: POST /verify (read-only), then runs the request, then POST /settle
5. 200 OK + data PAYMENT-RESPONSE: { success: true, transaction, network, payer }
Field and header names are from spec v2. Version 1 used different header names, so pin the version your SDK speaks.
Notice what the agent signs: an authorization to move a specific amount to a specific payTo address within a time window, not a blank cheque. The facilitator's /verify must not change any state; only /settle commits the payment. Failures come back as structured reasons (the spec lists codes such as insufficient_funds and settlement_pending, the latter a non-terminal state where a transaction was broadcast but not yet confirmed), so a client can tell "retry" from "stop". The spec leaves client-side budget management out of scope on purpose. That's the gap the next sections fill.
Mandates: OAuth scopes, but for money
You don't hand the agent your wallet — you hand it a mandate: a signed authorization that scopes what it may spend. Just as an OAuth token grants "read your email but not send," a payment mandate grants "spend up to $20 a transaction, $50 total, only at these merchants, until Friday." Protocols like AP2 standardize these mandates so any agent and any merchant can speak the same authorization language.
The agent acts freely inside the mandate and is refused outside it. Authority is delegated, bounded, and revocable — the model never holds unlimited spending power.
Don't trust the agent to spend wisely — bound what "spend" can even mean. The mandate turns "please don't overspend" (a hope) into "cannot overspend" (an invariant enforced by the payment layer).
AP2: mandates as signed, verifiable credentials
Google announced the Agent Payments Protocol on September 17, 2025, developed with more than 60 organizations, including Adyen and American Express. Its core idea is the mandate: a "tamper-proof, cryptographically-signed digital contract" that serves as verifiable proof of what the user instructed, signed with verifiable credentials. Two mandates carry the weight:
| Mandate | Captures | Used when |
|---|---|---|
| Intent Mandate | The user's request and its limits, for example "buy these concert tickets if they drop below a price" | The user isn't present at purchase time. The agent acts inside the signed scope. |
| Cart Mandate | The user's signed approval of the exact items and price | The user is present and approves a specific cart, which becomes an unchangeable record. |
AP2 distinguishes human-present purchases (the user approves the cart in real time) from human-not-present delegated tasks (the agent buys later under an Intent Mandate). The first needs one signature; the second is exactly the case this page's spend caps exist for. AP2 works as an extension of the A2A and MCP protocols, and Google also launched an A2A x402 extension for agent-based crypto payments, so the two protocols compose: AP2 says who authorized what, x402 moves the money.
Spend caps: enforce before you execute
The mandate is only as good as the check. Before every payment, the payment layer verifies three things against the mandate: is the amount within the per-transaction ceiling, does it keep cumulative spend under the total budget, and is the merchant in scope? All three must pass, or the payment is refused before any money moves.
This is least privilege applied to money: the agent's spending power is the narrowest set of payments that still lets it do its job. Everything else is denied by default.
Crucially, the check runs in the payment layer, not the prompt. You're not asking the model to respect a budget in its reasoning — you're making the budget a precondition it physically cannot bypass, the same way a sandbox enforces file access regardless of what code wants to do.
The runaway agent, contained
Here's the threat the caps exist for. A prompt-injected or looping agent decides to make a hundred payments — draining an account is exactly the kind of damage autonomy makes possible. With the mandate check in front of every payment, it can't. Cumulative spend climbs until the next payment would breach the cap, and then every further payment is refused; the loop spins but the money stops.
with mandate: next payment would exceed max_total → it and every further payment refused → damage bounded to the cap you chose
The runnable enforcer below makes this concrete: point a "runaway" agent at a $50 mandate, watch it try to spend $200, and watch it get stopped cold at the ceiling. The final spend is bounded by max_total no matter how many times it tries.
The protocol landscape
The protocols solve different layers, so they overlap less than the acronyms suggest.
| Protocol | Layer | Who and what |
|---|---|---|
| x402 | Settlement | HTTP 402 plus a facilitator that verifies and settles. Originated at Coinbase; the repository now lives under the x402 Foundation. |
| AP2 | Authorization | Google's mandates as verifiable credentials, extending A2A and MCP. |
| ACP (Agentic Commerce Protocol) | Checkout | An open standard for connecting buyers, their AI agents and businesses, maintained by OpenAI and Stripe and in beta. Its agents embed purchases "without being the merchant of record," and payment providers pass secure payment tokens between buyer and business. |
For an engineer the takeaway isn't which brand wins; it's that "my agent needs to pay for something" now has real answers at each layer, and each one needs the mandate discipline above bolted on. Check each spec's version before you build. ACP's repository, for instance, has published dated releases from September 2025 onward.
Reserve, retry, dispute: the engineering around the rails
Agents retry, and a retried payment is a second payment unless you design against it. Three patterns do the work.
Reserve, then capture. Before the agent starts a purchase, reserve the amount against the mandate's max_total and release it if the purchase fails. Otherwise ten parallel tool calls can each pass the cap check against the same remaining budget. This is the same atomic check-and-decrement you would use for inventory.
Idempotent retries. Derive one key per intended purchase, not per attempt. Stripe's API accepts an Idempotency-Key header on POST requests (up to 255 characters); for API v1 it saves the status and body of the first request and returns that saved response for retries with the same key, including 500 errors, and it errors if the retried parameters differ. Hold the same discipline on your side of any rail:
if ledger.has(key): return ledger.get(key)
hold = mandate.reserve(amount) # fails closed past max_total
result = rail.pay(amount, idempotency_key=key)
mandate.capture(hold) if result.ok else mandate.release(hold)
Practice the retry half in the Idempotency Key Handler challenge.
Disputes need evidence. When a charge is contested, the question is "did the user authorize this?" A signed Cart Mandate is that evidence, and a bare "the agent decided to" is not. Keep the mandate, the cart and the settlement record together, and log each refusal as well as each payment. For the full backend, see Design an Agent Payment Gateway.
Why it matters
Agentic payments are a genuinely new capability surface, and capability surfaces are where agents get dangerous. The good news is that this one has a clean control story: delegated, bounded, revocable authority checked before execution — the same least-privilege pattern that governs an agent's tool access and file system. If you're designing the backend, the mandate-verification and settlement flow is a system-design problem in its own right; see the payment system and digital wallet designs for the human-rails version this builds on.
The mental shift is the same one that made agents safe to give tools at all: never rely on the model to behave, bound what "behaving badly" can even cost. A mandate is a spending sandbox, and like every good sandbox, it works precisely because it doesn't trust the thing inside it.
The rails this builds on: Payment System and Digital Wallet. The least-privilege discipline: AI Security.
A mandate enforcer that stops a runaway agent
This is the whole safety model in a dozen lines. A signed mandate sets a per-transaction ceiling, a total budget, and allowed merchants; every payment must clear all three checks before it executes. Watch a legitimate payment go through, an over-limit one get refused, a wrong merchant get blocked — and a runaway agent that tries to spend $200 get stopped at $40 (a third $20 payment would breach the $50 budget) no matter how hard it loops. Change the mandate and the purchase list.
Worked example: one mandate, eight requests
The mandate from the runnable below: $20 per transaction, $50 in total, merchants api.example and data.example. An agent makes these requests in order. The sequence is illustrative; the checks are the three from section 05 plus the reserve and idempotency patterns from section 08.
| # | Request | Check | Spent after |
|---|---|---|---|
| 1 | $10 at api.example | 10 ≤ 20, 0 + 10 ≤ 50, merchant allowed | $10 |
| 2 | $25 at api.example | 25 > 20: refused on the per-transaction cap | $10 |
| 3 | $5 at evil.example | merchant not in scope: refused | $10 |
| 4 | $20 at data.example | 10 + 20 = 30 ≤ 50 | $30 |
| 5 | #4 times out; agent retries | same idempotency key: the ledger returns #4’s result | $30, no second charge |
| 6a | Two parallel $20 calls, check only | both read 30 + 20 = 50 ≤ 50, both pay | $70: over the cap |
| 6b | Same two calls, reserve first | first holds $20 (50 held); second: 50 + 20 > 50, refused | $50 |
| 7 | $1 at api.example | 50 + 1 > 50: refused | $50 |
Row 6a is the bug the three checks alone do not stop. Each check was right when it ran; both ran before either payment landed. Reserving turns check-and-spend into one atomic step. Row 5 is the same idea for retries: the key is made from the purchase, not the attempt, so the retry finds the first result instead of paying again.
Cost and trade-offs of each safeguard
Here Time is the extra work per payment, Space is the state you must keep, and Why is what you get for it.
| Case | Time | Space | Why |
|---|---|---|---|
| x402 pay-per-request | A 402 round trip, then the paid retry; the server calls /verify and /settle | Nothing on the client beyond a wallet | No accounts or checkout page, but no budget control either |
| Mandate check | Three comparisons before each payment | Per mandate: caps, merchant list, expiry, spent so far | Turns “please don’t overspend” into a refusal |
| Reserve, then capture | One atomic update on the mandate per payment | Open holds, released on failure | Parallel calls cannot share one remaining budget |
| Idempotency ledger | A lookup before every attempt | One row per intended purchase | A retry returns the first result, never a second charge |
| Cart Mandate (human present) | The user signs each cart | The signed cart | Strongest dispute evidence, but no autonomy |
| Intent Mandate (human not present) | One signature up front | The signed intent and every purchase under it | Autonomy inside limits; the limits must be tight |
Each safeguard costs a lookup or a write on your side and nothing at the rail. The expensive mistake is leaving one out.
Common mistakes
- Checking the budget without reserving it
Two concurrent tool calls each see enough budget and both pay, as in row 6a. Reserve the amount atomically, then capture or release.
- An idempotency key per attempt
A random key on each try makes every retry a new payment. Derive it from the run, mandate, merchant and cart, so every retry of one purchase carries the same key.
- Retrying a pending settlement
settlement_pendingis a non-terminal state: the transaction was broadcast but not confirmed. Retrying it as a failure can pay twice. Wait or poll on the same key. - Putting the budget in the prompt
“Spend at most $50” in a system prompt is advice an injected agent can ignore. The cap belongs in the payment layer, in front of every payment.
- Money as floating point
In binary floats, 0.1 + 0.2 is not 0.3, so a running total can drift past a cap or refuse the last valid cent. Keep amounts as integers in the smallest unit.
Where this shows up in production and interviews
- Paid APIs and data
A per-call price used to mean an account, a key and a monthly invoice. x402 lets an agent pay a fraction of a cent on the request itself, which suits short-lived agents that never sign up.
- Shopping on a user’s behalf
The AP2 “buy if the price drops” case. The agent holds an Intent Mandate with tight limits and an expiry, and the merchant can check that the purchase fits it.
- Disputes
When a charge is contested, the signed mandate, the cart and the settlement record are the evidence. Log refusals too: they show the limits worked.
- The interview version
In “design a payment gateway for agents”, cover the mandate check, the atomic reserve, an idempotency key per purchase and the pending state. Then walk a retry and a parallel call through it, as in rows 5 and 6.
Check yourself
With the $20 / $50 mandate, a looping agent makes ten $20 payments. How much does it spend?
$40, not $50. Payments one and two take it to $40; a third would make $60, which exceeds $50, and so does every one after it. The cap is a ceiling the agent never crosses, not an amount it is guaranteed to reach.
Spent is $45. Two parallel $5 payments arrive. What happens without reserving, and with it?
Without: both read 45 + 5 = 50 ≤ 50 and both pay, so spent is $55. With a reserve: the first holds $5 (50 held), the second sees 50 + 5 > 50 and is refused, so spent is $50.
The facilitator returns settlement_pending. Should the agent pay again?
No. The payment was broadcast and may still confirm. Treat it as in progress: keep the hold, poll, and use the same idempotency key, so a retry cannot create a second payment.
A user asks the agent to buy tickets next week if they fall below a price, and will not be online. Which AP2 mandate fits, and what should it contain?
An Intent Mandate: the user is not present at purchase time. It should hold the price limit, the quantity, the allowed sellers and an expiry, so the agent can act only inside what the user signed.
Quick answers
What is x402?
A machine-native checkout on the HTTP 402 status code: the server replies 402 with payment terms, the agent pays (usually a small stablecoin transfer) and retries with proof, then gets the resource — no human checkout page.
What is a mandate (AP2)?
A signed authorization scoping what an agent may spend — per-transaction ceiling, cumulative budget, allowed merchants, expiry. OAuth scopes, but for money. The agent acts freely inside it and is refused outside it.
How do spend caps stop a runaway agent?
Every payment is checked against the mandate before executing (amount ≤ per-txn, spent+amount ≤ total, merchant ∈ allowed). A looping or injected agent is refused once it would breach the cap — enforced by the payment layer, not the model.
Why does it matter now?
Autonomous agents need to pay mid-task and a human checkout defeats the point. x402, AP2 and ACP are published specs that make it work at scale, but it needs the same least-privilege discipline as any agent capability.
How does x402 work, and what is a facilitator?
x402 uses the HTTP 402 status code. The server answers a request with 402 and a PAYMENT-REQUIRED header describing what it accepts. The client signs a payment authorization and retries with a PAYMENT-SIGNATURE header. A facilitator service then verifies the payment through a read-only /verify call and commits it through /settle, and the server returns the resource with a PAYMENT-RESPONSE header. These are the version 2 header names; version 1 used different ones.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →
- The Model Context Protocol (MCP) HandbookThe open standard connecting AI agents to the outside world — why M×N bespoke integrations collapse to M+N, the host/client/server roles over JSON-RPC, the three primitives (tools, resources, prompts), the connect→discover→call session lifecycle, when MCP earns its keep, and the security sharp edges (a server's output is untrusted input).Read →
- The Loop Engineering HandbookStop prompting your agents — design the system that prompts them for you. The inner vs outer loop, the four loop types (heartbeat, cron, hook, goal), the six building blocks (automations, worktrees, skills, MCP connectors, subagents, external memory), stopping conditions and the verification split, state across runs, cost engineering, and the six failure modes that burn tokens at 3am.Read →
- The Context Engineering HandbookThe discipline that replaced prompt-tweaking: curating everything the model sees under a finite attention budget. The anatomy of a production context window, the three taxes on an overstuffed one (context rot, cost, behavioral drift), the four operations (write, select, compress, isolate), agent-specific patterns like compaction and just-in-time retrieval, six production habits, and where it sits in the prompt → context → loop → harness stack.Read →