x402 and HTTP 402: Machine-to-Machine Payments for AI Agents with Stablecoins

x402 and HTTP 402: Machine-to-Machine Payments for AI Agents with Stablecoins

x402 Protocol: HTTP 402 Machine Payments for AI Agents

For thirty years the web has carried a status code that nobody used. HTTP 402, “Payment Required,” was reserved in the original design for some future form of digital cash, and the future never arrived in a form browsers could adopt. Card networks, checkout pages and API keys filled the gap, and all of them assume a human with a billing relationship. An autonomous agent that wants to buy one weather lookup, one research PDF or ten seconds of GPU time has no good way to do that.

The x402 protocol is the most visible attempt to fix this. It puts the payment handshake inside the HTTP request itself: the server answers 402 with a machine-readable price, the client signs a stablecoin authorization and retries, and a third-party service settles the transfer. It matters now because agents are moving from demos to production budgets, and because the protocol has moved from a single-vendor project to Linux Foundation governance with payments incumbents attached.

You will leave with the exact message flow, the role of the facilitator, how gasless stablecoin settlement works at the token-contract level, how x402 relates to AP2 and card-based agent checkout, and a concrete threat model with mitigations.

What this covers: the background and history, the reference flow and its messages, settlement mechanics, the protocol landscape, failure modes (replay, price manipulation, double spend, prompt injection), and a practical adoption checklist.

Non-advisory disclaimer: this article is a systems and architecture analysis for engineers. It is not financial, investment, legal or compliance advice.

Context and Background

HTTP status codes in the 4xx range tell a client that its request failed for a reason it can fix. RFC 9110, the current HTTP semantics specification, lists 402 Payment Required in that family and says only that it is reserved for future use. No header, body format or retry behavior is defined, which is why every site that wanted to charge for content invented its own mechanism instead: session cookies, OAuth scopes, API keys tied to monthly invoices, or a redirect to a checkout page.

Those mechanisms work for humans and for long-lived software integrations. They fail for three situations that agents create. First, the buyer may not know the seller in advance, so there is no account to attach a key to. Second, the transaction may be worth a fraction of a cent, below the fixed cost of a card authorization. Third, the buyer is software acting on delegated authority, so “enter your card number on this page” is simply not an interface it can use.

Stablecoins attack the second and third problems. A dollar-pegged token on a low-fee chain can move value in a single signed message, with no merchant account and no issuer-side onboarding of the seller. The cost is that you now depend on a chain, a token issuer and a way to turn token balances back into operating cash. Our earlier piece on the architecture of agentic payments for AI commerce maps the whole field, from card-network tokens to wallets. This article zooms in on one protocol inside that map.

Coinbase incubated x402 and published it as an open-source repository under the coinbase/x402 name. Its README describes the goal as “an open standard for internet native payments” that is network, token and currency agnostic, with reference SDKs in TypeScript, Python and Go and chain support spanning EVM networks, Solana and Stellar. On September 23, 2025, Cloudflare announced it was partnering with Coinbase to create an x402 Foundation, and proposed a deferred payment scheme for cases where settlement need not be immediate. According to Coinbase’s developer documentation, the foundation launched under the Linux Foundation on April 2, 2026, with forty member organizations at launch; the premier members listed there include Amazon Web Services, American Express, Cloudflare, Coinbase, Google, Mastercard, Shopify, the Solana Foundation, Stripe and Visa. Treat membership as a signal of interest and not as a commitment to ship production support; the documentation does not say what each member will build.

Coinbase’s CDP documentation also states that its hosted facilitator has processed more than 100 million x402 payments across Base and Solana. That is a vendor-reported figure that we could not independently verify, and it counts payments, not unique buyers or revenue. It tells you the protocol runs at non-trivial volume, but nothing about how much of that volume is organic demand versus test traffic and subsidized campaigns.

How the x402 Protocol Works: The Reference Architecture

In one sentence, the x402 protocol lets an HTTP server reply 402 Payment Required with a structured list of acceptable payments, lets the client attach a signed payment payload to a retried request, and lets a facilitator verify and settle that payload on-chain so the server can release the resource and return a receipt.

x402 protocol request flow between an AI agent client, a resource server, a facilitator and a blockchain

Figure 1: The x402 protocol request flow. The client never submits a transaction itself; it signs an authorization that the facilitator submits.

Figure 1 shows the sequence for the common case. The agent requests a protected resource with no payment. The server returns 402 with a JSON body. The agent signs an authorization matching one of the offered options, repeats the request with the payload in a header, the server asks the facilitator to verify and then settle, and only after settlement succeeds does the server return 200 with the resource. The details of each step matter, so the next sections take them one at a time.

The 402 response: a machine-readable price

In the v1 specification published in the Coinbase repository, the 402 body is a JSON object with three top-level fields: x402Version, error (a human-readable string), and accepts, an array of payment options. Each entry in accepts is a PaymentRequirements object. The documented fields are scheme, network, maxAmountRequired, asset, payTo, resource, description, maxTimeoutSeconds and an optional scheme-specific extra object.

Read these as a contract offer. scheme names how payment is made; the scheme in common use is exact, meaning the client pays precisely the stated amount. network identifies the chain, asset is the token contract address, payTo is the recipient wallet, and maxAmountRequired is expressed in the token’s smallest unit, so a USDC price of 0.01 dollars appears as 10000 given six decimals. maxTimeoutSeconds bounds how long the signed authorization may remain valid. Because accepts is an array, a server can offer the same price on several chains or in several tokens and let the client pick whatever its wallet holds.

The array design is the first thing that separates x402 from a hard-coded API price list. A server can quote dynamically: a heavier query costs more, a cached response costs less, a peak-time request carries a surcharge. The price is whatever the 402 says at that moment for that exact resource, and the client decides whether to pay it. That puts the decision at the right place, since only the client knows its budget.

The payment header and the receipt

The client answers by repeating the original request with a payment payload. In v1 that payload is base64-encoded JSON in an X-PAYMENT header, and a successful response may carry an X-PAYMENT-RESPONSE header with the settlement outcome. Version 2, announced on the x402 site, removes the deprecated X-* header convention and renames the headers PAYMENT-REQUIRED, PAYMENT-SIGNATURE and PAYMENT-RESPONSE. It also moves to CAIP chain identifiers so networks are named in a standard, cross-ecosystem way, and adds extension hooks and a discovery extension through which facilitators can index available paid endpoints. Anything you build should read the version field and tolerate both header families during the migration window.

The payload itself contains the version, the scheme, the network and a scheme-specific payload object. For the exact scheme on EVM chains, that object carries an EIP-712 typed signature plus the authorization parameters it covers. Nothing in it is a broadcast transaction. This is the design choice that makes everything else work: the client signs a statement of intent, and somebody else turns that intent into a transaction.

The facilitator: verification and settlement as a service

A facilitator, in the repository’s words, is a server that facilitates verification and execution of payments for one or many networks. The specification defines three REST endpoints: POST /verify, which validates a payload without touching the chain; POST /settle, which executes the verified payment on-chain; and GET /supported, which lists the scheme and network combinations the facilitator handles.

The split exists for a practical reason. Resource servers are usually ordinary web applications written by people who do not want to run a node, hold gas tokens, simulate transactions or track chain reorganizations. The facilitator absorbs all of that. A server that wants to stay in control can run its own facilitator, since the interface is just three endpoints, but most early adopters use a hosted one.

The Coinbase-hosted facilitator is the best-documented example. Its documentation describes it as a service that validates signed payments, screens transactions, submits settlement on-chain and reports the result back to the resource server. It lists support for Base, Polygon, Arbitrum and World Chain plus Solana, supports all ERC-20 tokens on its EVM networks through EIP-3009 or Permit2, and supports SPL tokens on Solana. On pricing, it states that the first 1,000 on-chain facilitator transactions each month are free, each additional one costs 0.001 US dollars, and verification is always free. Those are vendor-published terms as of this writing and may change.

The pricing structure has an architectural consequence worth stating plainly. A flat per-settlement fee of a tenth of a cent is negligible against a 5-dollar API call but is 10 percent of a 0.01-dollar one, and over 100 percent of a 0.0005-dollar one. The protocol makes micropayments technically possible, but the economics of per-request settlement impose a practical floor on price points unless you batch or defer settlement. That is the motivation behind the upto and batch-settlement scheme names that the CDP documentation lists alongside exact for EVM networks, and behind Cloudflare’s deferred payment proposal.

Settlement Mechanics: Why Gasless Stablecoin Transfers Make This Work

Everything above could be done with any signed payment instrument. What makes x402 practical on EVM chains is a token-level feature: EIP-3009, “Transfer With Authorization,” implemented by Circle’s USDC and a few other tokens. It lets a token holder sign an off-chain message authorizing a specific transfer, which any third party can then submit and pay gas for.

Gasless stablecoin settlement in the x402 exact scheme using an EIP-3009 transfer with authorization

Figure 2: Settlement for the exact scheme on EVM. The payer signs an authorization, the facilitator checks it, pays gas and submits it, and the token contract burns the nonce so it cannot be reused.

The authorization fields are from, to, value, validAfter, validBefore and a 32-byte nonce. The signature covers all of them under an EIP-712 domain that binds it to the token contract and chain. Because the payer never sends a transaction, the payer’s wallet needs no native gas token. An agent holding only USDC can pay, which removes an entire class of operational failure (“agent is out of ETH”).

What the facilitator verifies

The specification lists the checks a facilitator performs before settling: the signature is valid and recovers to the stated payer, the payer has sufficient balance, the amount is at least the required amount, the current time falls inside the validAfter to validBefore window, the authorization parameters match the payment requirements (recipient, asset, network), and a transaction simulation succeeds. The simulation catches cases that static checks cannot, such as a token contract that is paused or a payer that was blocklisted by the issuer after signing.

For Solana, the exact scheme uses the SPL token TransferChecked instruction. Because Solana transactions are built differently, the specification enforces a strict instruction layout and bounds the compute unit price, so a payer cannot be tricked into signing a transaction whose fee is far higher than expected.

Replay protection by construction

The spec describes multiple layers of replay protection. In EIP-3009 each authorization carries a random 32-byte nonce, and the token contract records it as used once the transfer executes. Submitting the same signed authorization a second time reverts, with no cooperation needed from the facilitator or the server. The explicit validity window adds a second layer: even an authorization that was never executed becomes worthless after validBefore. Finally, the payment requirements echo the resource and recipient so a signature collected for one purchase does not clear a different one.

This layering is why the protocol can tolerate untrusted intermediaries. A facilitator that sees a payload cannot redirect funds to another recipient, because to is inside the signed message. It cannot increase the amount, for the same reason. The worst a dishonest facilitator can do with a valid payload is refuse to settle, settle it exactly as signed, or delay settlement until just before expiry. We return to the delay case in the failure-modes section.

Where chain choice enters

Chain selection controls three variables: confirmation latency, per-transaction cost and token availability. A server that waits for a block confirmation before releasing data adds seconds to every call; one that releases after verification but before final settlement takes on credit risk equal to the price of the resource. That is a real design decision, and a cheap, idempotent, low-value resource (a price quote) often justifies optimistic release, while an expensive, non-repeatable one (a model inference that cost real GPU time) justifies waiting for settlement.

Deeper Analysis: Where x402 Sits Among Agent Payment Protocols

x402 is frequently compared with AP2, the Agent Payments Protocol that Google introduced, and with checkout-oriented protocols for agent shopping. The comparison is often framed as a contest, but the layers do different jobs. Our thesis, which is an analytical opinion and not a vendor claim, is that x402 is a transport-level payment primitive, not an authorization framework, and that most confusion comes from asking it to answer questions it was never designed to answer.

Layered view of agentic payments showing intent and trust, transport, and settlement layers with x402 in the transport layer

Figure 3: A layered view of agentic payments. x402 and HTTP 402 live in the transport layer; mandate protocols sit above it and settlement rails below it.

What x402 answers and what it does not

x402 answers a narrow question: “this resource costs this much, here is a signed instruction paying it, was it valid and was it settled?” It does not answer “did the human actually authorize this agent to spend on this category of thing?” or “is this merchant who it claims to be?” or “who is liable if the agent bought the wrong item?” Those are mandate, identity and dispute questions.

AP2 is aimed at that upper layer. Google’s repository for the A2A x402 extension describes the extension as bringing cryptocurrency payments to the Agent-to-Agent protocol, built on x402 as the underlying payment layer and listing AP2 among related protocols. The repository shows a v0.1 specification and a Python implementation, which tells you the maturity level: usable for experiments, not a settled standard. If you need verifiable user mandates, signed intent records and a dispute trail, you need something above x402, and today that composition is early-stage work.

Why the HTTP-native design is the real innovation

The part that is genuinely new is not stablecoins, since those have existed for years, or signed transfers, which are standard practice. It is that payment becomes a first-class step in the request/response loop. A client library can treat 402 the way it treats a redirect or an authentication challenge: parse, act, retry. That means existing HTTP tooling (caches, gateways, CDNs, API management) can participate without bespoke integration.

Cloudflare’s involvement illustrates this. Its announcement described x402 support in its Agents SDK and MCP servers, an x402 playground, and a proposal for a deferred scheme in which the client sends Payment, Signature-Input and Signature headers (using HTTP message signatures) and the server replies with a Payment-Response header, decoupling the cryptographic handshake from settlement. That proposal is a design direction published by Cloudflare, not a finalized part of the core specification, and we could not confirm which parts have been adopted into the foundation’s spec.

The same insight explains the MCP angle. A tool server speaking the Model Context Protocol can expose paid tools and return a 402-style payment-required error that an agent runtime handles automatically within its tool-calling loop. The agent’s planner never needs to know a payment occurred; the runtime enforces a budget and signs. Our piece on agentic AI security and prompt injection explains why that separation, where the planner proposes and a policy layer disposes, is the only defensible pattern.

A minimal implementation sketch

The shape of a client-side handler is short enough to show. The following is illustrative pseudocode in Python style, not a drop-in library call; real SDKs exist for TypeScript, Python and Go and handle signing, version negotiation and error cases.

# Illustrative sketch of an x402 client loop (not a real SDK API)
def fetch_with_payment(url, wallet, policy):
    resp = http_get(url)
    if resp.status != 402:
        return resp
    offer = pick_offer(resp.json()["accepts"], wallet.balances())
    policy.check(host=url_host(url), amount=offer["maxAmountRequired"],
                 pay_to=offer["payTo"], asset=offer["asset"])
    payload = wallet.sign_exact(offer)          # EIP-3009 authorization
    paid = http_get(url, headers={"X-PAYMENT": b64(payload)})
    policy.record(url, offer, paid.headers.get("X-PAYMENT-RESPONSE"))
    return paid

Notice that policy.check sits before the signature. That ordering is the single most important line in the sketch: the policy decision must precede signing, because a signed authorization cannot be recalled except by letting it expire or by spending the nonce.

On the server side, the shape is symmetrical: middleware inspects the request, returns 402 with a price if no payment header exists, and otherwise calls the facilitator. The popular SDKs implement this as framework middleware keyed by route, with a price attached to each protected path. The server code never touches a private key; it only needs a receiving address.

A worked cost example

Consider an agent that calls a paid data API 200 times per day at a quoted price of 0.002 dollars per call. Gross spend is 0.40 dollars per day. If every call settled individually on a facilitator that charges 0.001 dollars per settlement after the free tier, the facilitator fee would be 0.20 dollars per day, which is half the revenue. Chain gas, if borne by the facilitator, is absorbed into that fee and into its margin. Now suppose the server instead issues a short-lived session credential after the first successful payment, as the v2 session concept allows, and charges for 50 calls per settlement. The settlement count drops to four per day, and the fee drops to 0.004 dollars. These figures use the published facilitator fee but an invented usage pattern; they show the shape of the economics, not a benchmark.

The lesson is that pricing granularity and settlement granularity are different design variables. Per-call prices can be tiny as long as settlement is amortized, and that is where the upto and batch-settlement ideas in the CDP documentation and Cloudflare’s deferred proposal come in.

Decision matrix: when x402 fits

Situation x402 fit Why
Public API, unknown callers, per-request price Strong No account needed; price is in the 402
Agent buying physical goods with consumer protections Weak Needs mandates, dispute and card-network recourse
Sub-cent calls at high volume Conditional Needs session or batch settlement to beat fees
Regulated client that cannot hold stablecoins Weak Wallet and custody requirements
Enterprise integration with monthly invoicing Weak Keys and invoices are simpler
Agent-to-agent services in a marketplace Strong Discovery plus per-call pricing

Trade-offs, Gotchas, and What Goes Wrong

The protocol is small, which means most risk lives in how you deploy it. Figure 4 pairs the main threats with the control that addresses each.

Threat model for x402 payments pairing replay, price manipulation, settlement failure, malicious facilitator and prompt injection with mitigations

Figure 4: Threats and mitigations for x402 deployments. Each failure mode maps to a control that lives in the client policy layer, the server, or the facilitator choice.

Replay and double spend

Replay of a signed EVM authorization fails at the token contract because the nonce is consumed on first use. The more realistic problem is double delivery: the facilitator settles, but the response to the server is lost, the server times out, the client retries, and the server charges again with a fresh authorization. Defend against it by keying delivery to the authorization nonce, so a retry carrying the same payload returns the already-purchased resource, and by making the client reuse the same payload on retry instead of signing a new one.

True double spend, where the payer’s balance is insufficient at settlement, is caught at verification only as of the moment of checking. A payer can sign two authorizations that together exceed the balance, and whichever settles second reverts. A server that releases the resource on verification alone, before settlement, eats that loss. This is the credit-risk decision described earlier, and it should be explicit, priced and capped.

Price manipulation and quote integrity

The client signs whatever it decides to pay, so the danger is in the client’s decision. A compromised or malicious server can change the quoted amount between calls, quote a different payTo, or offer an asset that is a worthless look-alike token. The maxAmountRequired field is a ceiling the client must compare to its own policy, not a number to obey. Clients should hold an allowlist of assets and networks, a per-host and per-call price ceiling, and should alert on a price change greater than a set percentage relative to the last quote for the same resource.

A subtler issue is the time gap between quote and settlement. The authorization window is bounded by maxTimeoutSeconds, and the spec’s time-window check means a facilitator can hold a payload until near expiry. For volatile pricing that matters little in dollar-pegged tokens, but it matters if a server quotes in a non-stable asset, which is one more reason to restrict assets.

Facilitator trust and availability

A facilitator cannot steal funds under the signature scheme, but it is a single point of failure for availability and a centralizing force for policy. Coinbase’s facilitator, per its documentation, screens transactions. That is a compliance feature and also a censorship surface: a payment can be refused for reasons the buyer cannot contest. Servers that want independence should support more than one facilitator, verify settlement on-chain themselves for high-value sales, or run their own.

Prompt injection and the drained wallet

The most severe practical risk is not cryptographic. An agent that reads web content can be told by that content to fetch a URL that returns a 402 for a large amount. If the client pays automatically and the budget is generous, the injected instruction becomes a payment. Spending caps per session, per host and per day, an allowlist of payable domains, and human approval above a threshold are the controls. Keep the hot wallet balance small: treat it as petty cash, funded in small increments from a treasury that the agent cannot touch.

Stablecoin acceptance raises questions about taxation, sanctions screening, money transmission rules and accounting treatment that vary by jurisdiction and that this article does not address. Our analysis of proposed GENIUS Act stablecoin rules on reserves and capital covers part of the US issuer-side regulatory picture, which determines which tokens a conservative enterprise will be allowed to hold. Operationally, chain congestion, token issuer freezes and facilitator outages all translate to failed purchases, so agents need graceful fallbacks, such as a cached answer or a degraded free tier.

Practical Recommendations

Start by choosing where x402 belongs in your stack. If you operate an API and want to monetize it for unknown software callers, add x402 middleware to one low-risk, read-only route, price it above the facilitator fee by a comfortable multiple, and measure real settlement counts before extending it. If you operate agents, put the payment capability behind a policy service that is separate from the model, so prompts cannot alter limits.

Pick a facilitator deliberately. Hosted services reduce effort but add a dependency and a compliance filter; self-hosting adds key management and chain operations. Whichever you choose, log the /verify and /settle responses and reconcile them against on-chain events daily, because reconciliation is how you detect both fraud and silent facilitator errors.

Design prices around settlement cost. If your per-call price is below roughly ten times the per-settlement fee, plan for sessions, prepaid balances or batch settlement. And prepare for version drift: v1 and v2 use different header names, so read the version, support both, and test against the foundation’s reference implementations as they evolve.

A short checklist for production readiness:

  • A per-host, per-call, per-day spend ceiling enforced before signing.
  • An allowlist of networks and token contracts the client will pay in.
  • Idempotent delivery keyed by authorization nonce.
  • A documented decision on release-before-settlement, with a loss cap.
  • At least one fallback facilitator, or a plan to run your own.
  • Daily reconciliation of settlements against chain data.
  • A small hot-wallet balance with automated top-up limits.
  • Logging of every 402 seen, accepted or refused, for audit.

For the wider context of agents operating inside industrial and enterprise systems, where budgets, identity and tool governance matter just as much, see our overview of agentic digital twins for AI-driven industrial analysis.

Frequently Asked Questions

What is the x402 protocol?

The x402 protocol is an open standard that uses the HTTP 402 Payment Required status code to let a server charge for a resource and let a client pay inside the same request flow. The server returns a machine-readable price, the client attaches a signed payment payload, and a facilitator verifies and settles it, usually in a stablecoin such as USDC. It was incubated at Coinbase and is now governed by the x402 Foundation under the Linux Foundation.

What does HTTP 402 Payment Required mean?

HTTP 402 is a client-error status code that RFC 9110 lists as reserved for future use, with no defined semantics. For decades it had no standard behavior. x402 gives it one: the response body carries an accepts array describing acceptable payments, and the client retries with a payment header. Because 402 itself is unspecified, any other use of it, such as a proprietary billing flow, is a separate convention that will not interoperate with x402 clients.

What is a facilitator in x402?

A facilitator is a server that verifies and executes payments on behalf of resource servers, so those servers do not need to run blockchain infrastructure. It exposes POST /verify, POST /settle and GET /supported. Under the signature-based scheme it cannot change the recipient or amount, but it can refuse or delay settlement. Coinbase operates a hosted facilitator, and the interface is simple enough that servers can run their own or use alternatives.

Do AI agents need ETH or gas tokens to pay with x402?

Not for the common EVM flow. The exact scheme uses EIP-3009 transfer authorizations, where the payer signs an off-chain message and the facilitator submits the transaction and pays gas. An agent holding only USDC can therefore pay. Token support matters: the token must implement EIP-3009 or the facilitator must support another path such as Permit2, which Coinbase’s documentation lists. On Solana, fee handling follows the network’s own transaction model.

How is x402 different from AP2?

x402 is a payment transport: it prices a resource and carries the signed payment. AP2, the Agent Payments Protocol, addresses the layer above, such as verifiable evidence that a user authorized an agent to buy something. Google’s A2A x402 extension shows the two can be combined, but that extension is at an early v0.1 specification stage. Choose x402 for pay-per-request access, and look at mandate-based protocols when you need user authorization trails or consumer protections.

Is x402 safe for autonomous agents to use?

The cryptography prevents replay and recipient tampering, but safety depends on policy. The main risks are agents paying inflated or malicious quotes, prompt-injected spending, and over-trusting a single facilitator. Enforce spend ceilings, network and token allowlists and per-host budgets before the agent signs, keep wallet balances small, and require human approval above thresholds. Treat the payment layer as untrusted input handling, not as a trusted tool.

Further Reading

By Riju — about

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *