All posts

How an AI agent pays for a single API call: x402, explained with code

Kevin Wang
Kevin Wang
Founder, AnyAPI · June 22, 2026
x402agent-paymentsapitutorial
How an AI agent pays for a single API call: x402, explained with code

An AI agent finds the perfect API for one task. To call it, the API wants an account, a saved card, and a monthly plan.

The agent has none of those. It cannot fill a signup form, store a card, or wait for a human to approve an invoice.

Almost every paid API on the web assumes a person is behind the keyboard. x402 drops that assumption.

It revives an HTTP status code that sat unused for 25 years, so an agent can pay for a single call inline, with no account at all.

The short version
  • x402 turns HTTP 402 "Payment Required" into a real payment handshake. A server answers an unpaid request with 402 and the price; the client pays and retries.
  • The agent pays per call, with no account, key, or subscription. Payment is a signed message in a header, not a checkout flow.
  • It settles in stablecoins (USDC) on a fast chain. The signature is gasless for the payer; a facilitator submits it on-chain.
  • It is one of several agent-payment standards. Stripe's MPP, Google's AP2, and the older L402 sit alongside it, and some of them interoperate.

What x402 actually is

x402 is an open standard for paying over HTTP. It is built around 402 Payment Required, a status code the spec has reserved "for future use" since the late 1990s.

RFC 9110 (June 2022) still says exactly that. No convention ever filled the code in, and x402 is the one that finally did.

Coinbase published x402 on May 6, 2025, under an Apache-2.0 license. A year later it outgrew a single vendor.

On April 2, 2026, the Linux Foundation took over hosting it as the x402 Foundation. Google, Visa, Mastercard, AWS, Microsoft, Shopify, Circle, and the Solana Foundation are all named participants.

  1. 1999402 reserved, then unused
  2. May 2025Coinbase ships x402
  3. Dec 2025v2: spec, SDK, facilitators
  4. Mar 2026Stripe + Tempo ship MPP
  5. Apr 2026Linux Foundation takes it over
x402 from dormant status code to foundation-governed standard. The May 2025 launch and the April 2026 Linux Foundation move are the load-bearing dates.

The mechanism is small on purpose. A server advertises a price on a 402; a client attaches a signed payment and asks again.

The server verifies the payment, does the work, and returns the result. That is the whole protocol, and the rest is detail.

Why an agent can't just use a credit card

Card rails were built for humans, and they break in two ways when the buyer is software.

First, an agent cannot complete the human parts: the signup, the saved card, the email receipt, the dispute flow.

Second, the economics are wrong for one API call. Card networks carry per-transaction minimums in the tens of cents, so charging two-tenths of a cent loses money on fees alone.

x402 fits the shape of the request instead. Payment is one signed message, created and sent by the same code that makes the call, for an amount as small as a fraction of a cent.

That is why the agent-payment forecasts run so large. McKinsey projected (October 17, 2025) that AI agents could mediate $3 trillion to $5 trillion of consumer commerce by 2030.

That is a forecast, not a meter reading. Later in this post I show what the real numbers look like today.

The honest framing: cards give you chargebacks and buyer protection x402 has no equivalent for, and x402 gives you per-call settlement cards cannot price. They solve different problems.

The payment handshake, step by step

Here is the full round trip, end to end.

AgentServerFacilitatorChain1request, no payment2402 + price3retry, signed X-PAYMENT4verify signature5run the work6settle on-chain7200 OK + data
The x402 handshake across the four parties. The 402 challenge (step 2) is the move that makes it work.

Now the same thing in code. The client makes a normal request with no payment:

curl -i -X POST https://api.example.com/v1/run/some.endpoint \
  -H "Content-Type: application/json" \
  -d '{"query": "anything"}'

The server answers 402 Payment Required and, in the body, the exact terms of payment:

{
  "x402Version": 1,
  "error": "X-PAYMENT header is required",
  "accepts": [
    {
      "scheme": "exact",
      "network": "base",
      "maxAmountRequired": "2000",
      "resource": "https://api.example.com/v1/run/some.endpoint",
      "description": "some.endpoint",
      "mimeType": "application/json",
      "payTo": "0xC0ffee...Payee",
      "maxTimeoutSeconds": 60,
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "extra": { "name": "USD Coin", "version": "2" }
    }
  ]
}

Read the fields, because they are the contract.

scheme: "exact" means pay this amount, no more, no less. maxAmountRequired: "2000" is in atomic units, so 2000 at six decimals is 0.002 USDC, two-tenths of a cent.

asset is the USDC contract on Base, payTo is the recipient, and maxTimeoutSeconds is how long the quote holds. accepts is an array, so a server can offer several networks or prices and let the client pick.

The client builds a payment, base64-encodes it into an X-PAYMENT header, and sends the identical request again:

curl -X POST https://api.example.com/v1/run/some.endpoint \
  -H "Content-Type: application/json" \
  -H "X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLC..." \
  -d '{"query": "anything"}'

If the payment checks out, the server runs the work and returns 200 OK with the result, plus an X-PAYMENT-RESPONSE header carrying the on-chain settlement. One extra round trip, and the agent paid for exactly what it used.

In practice nobody hand-rolls that header. The official client SDK wraps fetch and runs the 402-sign-retry loop for you:

import { wrapFetchWithPayment } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";

// the agent's wallet, funded with a few dollars of USDC
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY);
const fetchWithPay = wrapFetchWithPayment(fetch, account);

// looks like a normal fetch; the 402, the signature, and the retry are automatic
const res = await fetchWithPay("https://api.example.com/v1/run/some.endpoint", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "anything" }),
});

const data = await res.json();

From the agent's side it is one call. The wallet, the 402, and the retry are plumbing.

What the signature actually authorizes

The payment is not a transaction the agent broadcasts. It is a signed authorization that the server, or its facilitator, submits on the agent's behalf.

On an EVM chain, x402 uses EIP-3009 transferWithAuthorization. The client signs an EIP-712 typed message that says "move this much USDC from me to the payee," and someone else pays the gas to put it on-chain.

So the agent's wallet only needs USDC, not the chain's native gas token. The decoded X-PAYMENT payload is roughly this:

{
  "x402Version": 1,
  "scheme": "exact",
  "network": "base",
  "payload": {
    "signature": "0x9f8e...",
    "authorization": {
      "from": "0xAgentWallet...",
      "to": "0xC0ffee...Payee",
      "value": "2000",
      "validAfter": "0",
      "validBefore": "1781490000",
      "nonce": "0x4c1d...e7"
    }
  }
}

The nonce and validBefore are the replay protection: a signature is good once, and only until it expires.

The server, or a facilitator like Coinbase's hosted one, calls /verify before doing any work and /settle after. The default token is USDC, and the production networks are Base and Solana.

Two design choices are worth naming. The exact scheme is the common one, but the spec also describes upto (authorize a ceiling, charge for actual usage) and batch settlement (collect many tiny payments, settle once on-chain).

The verify-then-settle split also matters. A server can confirm payment is good, run the work, and only settle if the work succeeds.

x402 is one of several agent-payment standards

x402 is not the only attempt to let software pay software. The press framing of "x402 versus everything" misses that several of these sit at different layers and compose.

The useful split is by what each one actually moves:

StandardBacked byRailAccount to pay?Status
x402Coinbase, now Linux FoundationStablecoin (USDC) on Base/SolanaNoLive since May 2025
MPPStripe and TempoStablecoin, cards, LightningNoLaunched March 2026
Google AP2Google plus 60+ partnersRail-agnostic (signed mandates)Tied to a userAnnounced September 2025
Stripe/OpenAI ACPStripe and OpenAICardsBuyer enters card in chatLive in ChatGPT
L402Lightning LabsBitcoin LightningNoProduction since 2020

A few notes the headlines skip. Stripe's Machine Payments Protocol (MPP), launched March 18, 2026, also revives HTTP 402, and Stripe says the core x402 exact flow maps onto its model.

Google's AP2 does not move money at all; it produces a signed mandate that any rail, including x402, can settle against. L402 is the elder here, in production on Bitcoin Lightning since 2020.

So this is less a winner-take-all race than a set of overlapping standards, some of them built to interoperate.

How much of this is real

The institutional lineup is real. The volume is small.

That gap is the most important thing to understand before you bet a product on it, and most write-ups skip it.

Reported cumulative transactions range from 75 million to 100 million depending on the source and date, with no single audited figure.

The daily reality is more sobering. CoinDesk reported (March 11, 2026) only about $28,000 in genuine daily volume, "much of it from testing and 'gamed' transactions rather than real commerce."

A February 2026 spike to millions of transactions was attributed to infrastructure testing and wash trading, not buyers.

Feb 2026 spike: 3.8M3.8MFeb 2026 spikeTypical day: 131k131kTypical day
x402 daily transaction count: the February 2026 spike (attributed to infrastructure testing and wash trading) against a typical day. Source: CoinDesk / Artemis, March 2026.

Strip out the noise and the real recurring demand is tiny but legible.

Over 30 days in mid-2026, on-chain data put genuine usage in the low single-digit thousands of dollars per service. It clusters in exactly the place the standard was designed for: agents buying API, data, and inference calls.

StableEnrich: $3,120$3,120StableEnrichBlockRun YOPO: $2,680$2,680BlockRun YOPOHYRE Agent: $1,420$1,420HYRE Agent
The top recurring x402 services by 30-day on-chain volume, in USD, mid-2026. The dollar amounts are small, and they cluster around agents buying data and inference APIs. Source: x402scan via x402 Inc., May 2026.

There are real critiques under the hood, too.

EIP-3009 only works with tokens that implement it, which leaves out USDT and DAI and even a large share of USDC (a later extension widens this).

Facilitators carry the gas and infrastructure cost with no protocol-level fee, which raises the obvious question of who keeps them running once the subsidies end.

Most traffic flows through one hosted facilitator today, which sits awkwardly next to the decentralization pitch. None of these are fatal, and none are resolved.

What it looks like from the server side

We wired x402 into our own API gateway, so the server half of this is not hypothetical for me.

The interesting part was not emitting the 402. It was deciding when to charge.

The gateway prices each challenge from the exact request body, because some endpoints charge per input item. So the unpaid challenge and the paid retry have to carry the same body, or the amount the agent signed will not match the work it gets.

The other choice that mattered: verify the payment, run the work, and only settle on-chain if the run succeeds. A failed call settles nothing, so the agent is never charged for data it did not receive.

That asymmetry, easy to get wrong, is the whole reason per-call payment feels fair instead of risky. It is the same per-request, USD-priced model the rest of the catalog already uses, with the wallet swapped in for the API key.

The point is bigger than our gateway. x402 lets any server quote a price in a 402 and any agent pay it in a header, and that is a genuinely new thing on the web, whoever ships it.

Frequently asked questions

What is x402?

x402 is an open standard for paying over HTTP, built on the 402 Payment Required status code. A server answers an unpaid request with 402 and a price; the client attaches a signed stablecoin payment and retries. Coinbase published it in May 2025, and the Linux Foundation now hosts the project.

Why is it called x402?

The name comes from HTTP status code 402, "Payment Required." That code has been reserved "for future use" in the HTTP specification since the late 1990s and never had a standard meaning. x402 is the convention that finally fills it in, using the code for its original intended purpose.

Do you need cryptocurrency to use x402?

To pay, yes, today. The agent's wallet holds a stablecoin, usually USDC, and signs a payment authorization. It does not need the chain's gas token, because the payment is gasless for the payer: a facilitator submits it on-chain. Other standards like Stripe's MPP add card rails alongside stablecoins.

Is x402 free to use?

The protocol is open and free. The cost is the payment itself plus on-chain fees. Coinbase's hosted facilitator gives 1,000 free transactions per month, then charges $0.001 per transaction, with chain gas paid separately. You can also run your own facilitator and avoid that fee.

How is x402 different from a normal API key?

An API key assumes you already signed up, saved a card, and have a billing relationship. x402 needs none of that. The agent pays for one call inline, with a signed message in a header, and walks away. There is no account to create and no subscription to manage.

What is the difference between x402 and Stripe's MPP?

Both revive HTTP 402 for agent payments. x402 settles stablecoins on Base or Solana and is governed by the Linux Foundation. Stripe's Machine Payments Protocol, launched March 2026, adds card and Lightning rails. Stripe has said x402's core flow maps onto MPP, so they overlap rather than strictly compete.

Is x402 an official standard?

It is an open standard, Apache-2.0 licensed, and since April 2, 2026 it is hosted by the Linux Foundation with participants including Google, Visa, Mastercard, AWS, and Circle. It is not an IETF RFC. Stripe's MPP, by contrast, is on the IETF standards track.

What blockchain does x402 use?

The production networks are Base (an Ethereum layer 2) and Solana, with USDC as the default token. Self-hosted facilitators add other EVM chains. On EVM it uses EIP-3009 signed authorizations, and on Solana it uses a partially-signed transaction where the facilitator pays the fee.

Is x402 actually used in production today?

Lightly. Reported cumulative transactions run into the tens of millions, but CoinDesk found only about $28,000 in genuine daily volume in March 2026, with much of the headline activity being testing and wash trading. Real recurring use is small and concentrated in agents buying data and inference APIs.

Can an AI agent pay without holding a wallet?

Not with x402 directly: the agent needs a wallet and a private key to sign payments. That is a real operational cost, since funding and securing that key is now part of running the agent. Custodial wallet services and platforms like Coinbase's CDP exist to manage that key on the agent's behalf.

How do I add x402 to my own API?

Add the payment middleware for your framework (Express, Hono, Next.js, FastAPI, and Go are supported), set a price and a payee address per route, and point it at a facilitator for verification and settlement. The middleware emits the 402 and checks payments; you do not touch chain code unless you self-host the facilitator.

Every endpoint priced in plain USD, payable per call. New accounts start with free credit, so you can wire up an agent before funding a wallet.

Browse the data catalog