Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Agentic Payments
Handbook~14 min readAgentsworked math + runnable code
Handbook

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.

01

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.

x402 — pay inside the request/response loop
GET /data
→
402
price + terms
→
pay + retry
proof attached
→
200 + data

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.

02

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:

1. GET /premium-data
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.

03

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.

mandate = { per_txn_max, max_total, allowed_merchants, expiry }  ·  signed, not guessable

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.

The key idea

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).

04

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:

MandateCapturesUsed when
Intent MandateThe 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 MandateThe user's signed approval of the exact items and priceThe 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.

05

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.

authorize ⟺ amount ≤ per_txn_max  AND  spent+amount ≤ max_total  AND  merchant ∈ allowed

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.

06

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.

no caps: injected agent runs 100 payments → account drained
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.

07

The protocol landscape

The protocols solve different layers, so they overlap less than the acronyms suggest.

ProtocolLayerWho and what
x402SettlementHTTP 402 plus a facilitator that verifies and settles. Originated at Coinbase; the repository now lives under the x402 Foundation.
AP2AuthorizationGoogle's mandates as verifiable credentials, extending A2A and MCP.
ACP (Agentic Commerce Protocol)CheckoutAn 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.

08

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:

key = hash(run_id, mandate_id, merchant, cart_hash)  # same on every retry of this purchase
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.

09

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.

Read next

The rails this builds on: Payment System and Digital Wallet. The least-privilege discipline: AI Security.

RUN IT YOURSELF

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.

CPython · WebAssembly
By the numbers

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.

#RequestCheckSpent after
1$10 at api.example10 ≤ 20, 0 + 10 ≤ 50, merchant allowed$10
2$25 at api.example25 > 20: refused on the per-transaction cap$10
3$5 at evil.examplemerchant not in scope: refused$10
4$20 at data.example10 + 20 = 30 ≤ 50$30
5#4 times out; agent retriessame idempotency key: the ledger returns #4’s result$30, no second charge
6aTwo parallel $20 calls, check onlyboth read 30 + 20 = 50 ≤ 50, both pay$70: over the cap
6bSame two calls, reserve firstfirst holds $20 (50 held); second: 50 + 20 > 50, refused$50
7$1 at api.example50 + 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.

Trade-offs

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.

CaseTimeSpaceWhy
x402 pay-per-requestA 402 round trip, then the paid retry; the server calls /verify and /settleNothing on the client beyond a walletNo accounts or checkout page, but no budget control either
Mandate checkThree comparisons before each paymentPer mandate: caps, merchant list, expiry, spent so farTurns “please don’t overspend” into a refusal
Reserve, then captureOne atomic update on the mandate per paymentOpen holds, released on failureParallel calls cannot share one remaining budget
Idempotency ledgerA lookup before every attemptOne row per intended purchaseA retry returns the first result, never a second charge
Cart Mandate (human present)The user signs each cartThe signed cartStrongest dispute evidence, but no autonomy
Intent Mandate (human not present)One signature up frontThe signed intent and every purchase under itAutonomy 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.

Watch for

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_pending is 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.

In the wild

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.

Self-check

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.

Frequently asked

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.

The Agentic Payments Handbook · Vibe Engines · 2026 · reported protocol traction from public sources · more handbooks →
Finished this one? 0 / 209 Handbooks done
NextThe Agentic AI Interview Handbook Closest handbook to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks