---
title: HTTP 402-based Payment Protocol (x402)
url: https://www.emergentmind.com/topics/http-402-based-payment-protocol-x402
type: topic
---

# HTTP 402-based Payment Protocol (x402)

Searching arXiv for the cited x402 papers and related protocol/security references.
x402 is an HTTP 402–based payment protocol that repurposes the standard `402 Payment Required` status code into a machine-to-machine payment handshake for APIs, content, and agentic services. Across the literature, it is described as an open, blockchain-agnostic, HTTP-native mechanism in which a client first receives a payment challenge, then returns a signed payment authorization or settlement proof, after which the server grants the requested resource. The protocol is used in autonomous-agent settings because it preserves ordinary HTTP request/response structure while introducing payment, settlement, and receipt semantics at the application layer [2507.19550][2604.15367].

## 1. Protocol semantics and transaction flow

The core semantic move in x402 is the reinterpretation of HTTP 402 from a dormant status code into an explicit payment trigger. One implementation-oriented description states that `402 Payment Required` is the “intent to pay” trigger, and that request semantics change from “you are unauthorized” in `401` to “you must pay.” In the same description, the client retries the original request with an `X-Payment` header after successful payment, while the server may return `402` again if the price or facilitator changes [2604.11430].

A common flow appears across several papers. In the minimal three-round version, the client sends an initial request without payment, the server responds with a structured payment challenge, the client constructs and signs a payment authorization, and the retried request carries that authorization in a payment header; a successful exchange ends with `200 OK` and a settlement receipt header [2507.19550]. A more detailed eight-step sequence adds explicit middleware interception before signing, facilitator-side settlement on Base L2, an on-chain receipt, and a final replay of the original HTTP request carrying the receipt [2604.11430].

The protocol is also represented as a finite-state automaton. One formalization uses `S_0 = Idle`, `S_1 = AwaitingPayment`, `S_2 = VerifyingPayment`, `S_3 = Paid`, `S_4 = Completed`, and `S_e = Error`, with transitions from an unpaid request to `402`, from `X-PAYMENT` submission to verification, and from successful settlement to `200 OK` plus receipt [2507.19550]. In Agent-OSI, a related state progression runs from `DISCOVERY` through `PAYMENT_CHALLENGE_RECEIVED`, `ESCROW_SETUP_IN_PROGRESS`, `PAYMENT_VERIFIED`, `EXECUTING_SERVICE`, `PROVENANCE_GENERATED`, and `ESCROW_RELEASED` to `COMPLETED` [2602.13795].

An important implementation variant is APEX, which realizes a `challenge–settle–consume` lifecycle rather than a direct on-chain retry pattern. There, `GET /data` returns `402` and a `ref_id`; `POST /pay` settles the challenge and issues a short-lived signed token; a subsequent `GET /data` with `X-Payment-Token` atomically transitions the ledger state from `SETTLED` to `CONSUMED` before releasing the protected data [2604.02023].

## 2. Message forms, headers, and signed payloads

The literature does not present a single canonical RFC grammar. The SoK explicitly states that it “does not publish a formal RFC or LaTeX grammar for x402,” and that “the precise header names and JSON field names are left to implementers”; what is preserved across variants is the end-to-end binding between the original request, the 402 challenge, the signed payment credential, and the receipt [2604.15367].

Representative message variants are summarized below.

| Source | Payment challenge | Payment / receipt submission |
|---|---|---|
| [2507.19550] | JSON with `token`, `to`, `network`, `amount`, `nonce`, `expiry` | `X-PAYMENT`, then `X-PAYMENT-RESPONSE` |
| [2604.15367] | `Payment-Scheme: x402`, `Payment-Request: {...}` or JSON body | `Authorization: Payment x402 <Base64(signature)>`, then `Payment-Receipt` |
| [2605.00071] | `Payment-Method: x402` with JSON body fields including `payer`, `payee`, `resource`, `amount`, `nonce` | `Payment-Authorization: <base64(\sigma)>`, then `Payment-Status` |
| [2603.16899] | `X402-Payment-Required`, `X402-Payment-Address`, `X402-Payment-Metadata` | `H402-Payment-*` commitment headers |

One widely cited payment challenge contains a token or coin identifier, payment destination, network, amount, nonce, and expiry timestamp [2507.19550]. Another uses a `PaymentSpec` with `schemes`, `price`, `network`, and `facilitator` [2604.11430]. The SoK additionally gives examples with `requestId`, `dueHeight`, `Payment-RequestId`, and `Payment-Payload-Digest` [2604.15367].

A detailed schema appears in the hardening work, where the signed payload is a `PaymentRequest`:
$$
\texttt{PaymentRequest} = \{
\mathrm{resource\_url}:\texttt{String},
\mathrm{description}:\texttt{String},
\mathrm{reason}:\texttt{String},
\mathrm{amount}:\texttt{Integer},
\mathrm{chain\_id}:\texttt{Integer},
\mathrm{facilitator}:\texttt{Address}
\}.
$$
Its metadata substructure is
$$
\texttt{Metadata} = \{
\mathrm{resource\_url}:\texttt{String},
\mathrm{description}:\texttt{String},
\mathrm{reason}:\texttt{String}
\}.
$$
This is notable because `resource_url`, `description`, and `reason` are transmitted to both the payment server and the centralized facilitator API before settlement [2604.11430].

Cryptographic realization varies by deployment. Several papers describe EIP-712 typed-data signatures over the payment object [2604.11430][2604.15367]. The technical specification in the multi-agent-economies work instead centers the payment assertion on EIP-3009 `transferWithAuthorization`, encoded in `X-PAYMENT` and verified before on-chain submission [2507.19550]. CPMM introduces an `H402` commitment layer with ephemeral Ed25519 keys, Schnorr signatures, capability hashes, SLA hashes, and quality-linked payment commitments [2603.16899].

A recurrent requirement is request binding. The SoK defines a digest such as
$$
\mathrm{digest} = H(\text{request\_method} \,\|\, \text{request\_uri} \,\|\, \text{request\_body}),
$$
and presents `Payment-Payload-Digest` as the binding between the HTTP request and the payment credential [2604.15367]. Later security analyses sharpen this into a request-bound signature extension:
$$
\sigma = \mathsf{Sign}_{sk}\Bigl(M,\;v,\;n,\;expiry,\;\mathcal H(\text{Method}\,\|\,\text{URI}\,\|\,\text{Body})\Bigr),
$$
specifically to prevent cross-resource substitution [2605.30998].

## 3. Settlement architectures and execution models

The settlement layer is where x402 diverges most sharply across implementations. In the facilitator-based EVM realization, the client signs an EIP-712 payment token, sends it to a facilitator API on Base L2, the facilitator smart contract verifies the signature and transfers the USDC amount from the agent’s wallet to the server’s address, and an on-chain receipt is emitted; the client then retries the original request with that receipt in `X-Payment`, after which the server verifies inclusion and success status [2604.11430].

The general technical specification is broader. It describes x402 as blockchain-agnostic: the `network` field can point to different ledgers, the facilitator knows how to speak to the named chain RPC or node endpoint, and confirmation may be awaited synchronously or asynchronously. It also allows incremental micropayments, represented as a sequence of authorizations $\delta_1,\delta_2,\dots,\delta_n$, with settlement triggered once $\sum_{i=1}^{n}\delta_i$ crosses a threshold $T$ or a timeout occurs [2507.19550].

Agent-OSI presents a distinct escrow-centered model. There, the user agent submits a service invocation, the service agent answers with a `402 Payment Required` challenge, the user agent invokes `EscrowContract.createEscrow(...)` off-HTTP, the resulting on-chain `EscrowLocked` event is returned as a receipt, the service agent verifies the event against `quoteId`, `payer`, `payee`, `amount`, and `nonce`, executes the service, delivers the result with provenance, and finally calls `releaseEscrow` [2602.13795]. In the prototype, this off-chain negotiation plus on-chain lock/release pattern reduced per-session gas from approximately `326 000` in a “Web3 baseline” to approximately `159 000` in the x402 prototype, i.e. “approximately 51%” lower [2602.13795].

A fiat-adapted variant appears in APEX. Instead of on-chain settlement, APEX uses FastAPI, SQLite, HMAC-signed short-lived tokens, and idempotent settlement handling. `POST /pay` records `INITIATED → SETTLED`, issues a token with expiry, and the subsequent `GET /data` verifies HMAC, checks `exp ≥ now`, requires ledger state `SETTLED`, and atomically updates to `CONSUMED` [2604.02023]. This does not discard the x402 logic; it adapts the HTTP 402 payment-gating pattern to “UPI-like fiat workflows” while preserving replay resistance and policy control [2604.02023].

Regulated stablecoin deployments add yet another execution architecture. The compliance-aware design uses a relay that reconstructs a canonical message
$$
m = \mathrm{ABIEncode}(\text{payer},\text{payee},\text{resource},\text{amount},\text{currency},\text{valid\_after},\text{valid\_before},\text{nonce}),
$$
verifies the signature with `ecrecover`, checks nonce uniqueness, and calls `PolicyWrapper.executeWithAuthorization(...)`; `PolicyManager` then returns `PASS`, `PENDING`, or `FAIL`, and the wrapper emits a `ComplianceAttestation` event even when a transfer is held pending [2605.00071].

## 4. Security assumptions, invariants, and attack surface

The security literature treats x402 as a cross-layer protocol whose risk profile cannot be reduced either to ordinary web security or to ordinary on-chain payment security. The SoK states that x402 assumes a TLS-protected channel; that agent private keys must be kept in hardware wallets or HSMs; that freshness requires nonces or block-height timeouts; that a cryptographic binding between HTTP request and payment credential is essential; and that the protocol is designed for “Level 3 fully autonomous agents,” with “no manual approval per transaction” [2604.15367].

A later formalization defines five security invariants: Payment Integrity, Value Consistency, Context Binding, Authorization Uniqueness, and Execution Conservation. In its notation, payment integrity requires
$$
\forall r,\;\text{if } \textsf{deliver}(r)\text{ then }
\exists Tx\in B : (\mathsf{Sender}(Tx)=pk_s \land \mathsf{Receiver}(Tx)=M),
$$
while context binding requires that a valid authorization bind to exactly one resource identifier, and execution conservation requires expensive work to begin only when payment is `CONFIRMED` or `LOCKED` [2605.30998].

Two failures recur in the empirical papers. The first is a semantic or cryptographic gap. One analysis argues that when the EIP-712 message signs only merchant, amount, nonce, and expiry, with no resource identifier, a valid authorization for one resource can be transplanted to another resource of the same price; this is framed as a break of Context Binding [2605.30998]. The second is a temporal gap. Because verification is typically off-chain and settlement updates chain state only later, concurrent requests using the same authorization can both pass verification before any nonce is marked used on-chain [2605.30998][2605.11781].

The “Five Attacks” paper makes this concrete. It models x402 as a split between synchronous authorization and asynchronous on-chain settlement, then reports: `RGP₀ up to 5.18 %` under `p_reorg=0.05, δ=400 ms` for optimistic execution; a replay experiment against a live Sepolia endpoint yielding `248 grants, 1 settlement`; a local caching setup in which `1 000` unpaid requests resulted in `100 %` cache hits when `Cache-Control` was absent; and discovery-layer manipulation in which a single poisoned endpoint achieved average `71.8 %` selection, while `r=5` Sybils yielded approximately `60.2 %` selection [2605.11781].

Dynamic-pricing extensions create additional risk. In the “upto” or allowance model, the shopper signs $\langle M, V_{\max}, n, expiry\rangle$ rather than an exact value, and the merchant later pulls the measured amount. The security analysis shows that concurrent requests can all pass an initial allowance snapshot, while only a subset of settlement pulls succeed later. The reported resource leakage ratio can reach `100%` on production middleware; the paper also states `L≈0.977` in overdraft bursts, and `L=1.0` when all pulls revert [2605.30998].

These results directly counter a common assumption that on-chain settlement, by itself, guarantees atomic payment-for-service. The attack papers instead argue that x402’s main difficulties arise at the seam between HTTP timing, off-chain verification, facilitator policy, and eventual blockchain finality [2605.11781][2605.30998].

## 5. Hardening: privacy filtering, replay controls, spending policy, and compliance

One of the most detailed hardening efforts targets metadata leakage. The hardening paper observes that x402 payment requests embed `resource URLs`, `descriptions`, and `reason strings`, and that this metadata is transmitted to both the payment server and the centralized facilitator API before on-chain settlement, with neither party typically bound by a data processing agreement. Its `HardenedX402Client` inserts four pre-signing controls: `PIIFilter`, `PolicyEngine`, `ReplayGuard`, and `AuditLog` [2604.11430].

The `PIIFilter` is Presidio-based and supports two detection modes, `regex` and `nlp`, over six entity types: `EMAIL`, `PERSON`, `SSN`, `IBAN`, `CC`, and `PHONE`. The evaluation uses a “labeled synthetic corpus of 2,000 x402 metadata triples” with “875 injected PII labels of 6 types” and a `42-configuration` sweep. The recommended configuration is `mode = nlp`, `entity_types = all six`, `min_score = 0.4`, yielding `micro-F1 = 0.894`, `precision = 0.972`, and `p99 latency = 5.73 ms`; the paper states this is “well within the 50ms overhead budget” [2604.11430].

Replay controls appear in several forms. The hardening middleware computes an HMAC-SHA256 fingerprint over serialized token fields and stores it in a TTL-bounded cache [2604.11430]. APEX enforces single-use semantics by atomically updating the ledger from `SETTLED` to `CONSUMED`; if zero rows are updated, replay is rejected [2604.02023]. In the compliance-aware stablecoin design, replay protection is pushed on-chain via `mapping(bytes32=>bool) usedNonce` and `require(!usedNonce[nonce], "Replay")` [2605.00071].

Policy-governed spending is a second hardening layer. The middleware paper specifies `max_per_call_usd`, `daily_limit_usd`, and `max_per_endpoint_usd`, with violations raising `PolicyViolationError` before signing [2604.11430]. APEX implements per-request maximum and daily budget checks over ledger entries, and reports that `policy enforcement reduces total spending by 27.3% while maintaining 52.8% success rate for legitimate requests`; it also reports `20/20 blocked (100%)` for both `replay_attack` and `invalid_token`, with “low latency overhead (19.6ms average)” for invalid-token blocking [2604.02023].

The compliance literature generalizes spending policy into on-chain guardrails. In the compliance-aware architecture, `PolicyManager.check(...)` applies a DSL in which one `FAIL` yields overall `FAIL`, no `FAIL` but at least one `PENDING` yields `PENDING`, and all `PASS` yields `PASS`; `ComplianceAttestation(bytes32 txId, uint8 status, uint256 timestamp, bytes32 proofsHash)` records `status ∈ {0=PASS,1=PENDING,2=FAIL}` and a `keccak256(vcs_payload)` binding for auditability [2605.00071].

The mitigation literature adds protocol-level measures: per-request spending caps bound to the signing key; EIP-712 typed-data signatures for both `PaymentRequest` and `PaymentReceipt`; RFC 9421 HTTP Message Signatures over the request/response cycle; facilitator-bound settlement; request-bound signatures over method, URI, and body; stateful nonce linearization; `Cache-Control: no-store, private`; and logging of every 402 challenge/credential pair for posterior audit [2604.15367][2605.11781][2605.30998].

## 6. Place within agent economies, discovery systems, and micro-economic frameworks

x402 is frequently embedded in broader agent-economy architectures rather than treated as an isolated payment primitive. The multi-agent-economies work integrates ledger-anchored `AgentCards` for discoverability with x402 for micropayments, presenting the combination as infrastructure for secure and verifiable identities plus HTTP-based compensation across organizational boundaries [2507.19550]. Agent-OSI places HTTP 402 in a six-layer reference stack as an application-level payment challenge “analogous to HTTP 401 for authentication,” with escrow-based settlement and verifiable receipts rather than a new network-layer protocol [2602.13795].

Because x402 generates an on-chain graph of paid API interactions, it has also been used as a discovery signal. TraceRank models each x402 payment as an endorsement weighted by payer reputation, USD value, and temporal recency. Its core iteration is
$$
\mathbf{r}^{(t+1)} = \mathbf{s} + \alpha W^\top \mathbf{r}^{(t)},
$$
with fixed point
$$
\mathbf{r} = (I-\alpha W^\top)^{-1}\mathbf{s}.
$$
In a simulated graph of `100 K agents` and `5 K services`, the combined `TraceRank × Semantic` method reports `Precision@5 = 0.88` and `nDCG@10 = 0.84`, compared with `0.62/0.52` for volume-only and `0.75/0.70` for semantic-only baselines [2510.27554].

CPMM extends x402 into a richer micro-economic framework. It combines `X402/H402` micropayments with NANDA capability commitments and ACNBP negotiation, includes `Economic Proposal`, `Payment Instruction`, and `Quality Attestation` JSON records, and defines a quality-based price function
$$
p(q)=p_0\prod_{j=1}^{d} f_j(q_j).
$$
The same work introduces “privacy elasticity of demand” and states that the repeated bilateral game converges to a constrained Radner equilibrium [2603.16899].

Taken together, these studies present x402 less as a single frozen wire format than as an HTTP-level payment pattern with several realizations: direct facilitator settlement, escrow-mediated delivery, fiat tokenization, compliance-gated stablecoin execution, and capability-priced quality markets. What remains stable across these realizations is the use of `402 Payment Required` as the payment challenge, plus the requirement that payment authorization, request context, settlement state, and service delivery be cryptographically and operationally bound end to end [2507.19550][2604.15367][2605.30998].

Source: https://www.emergentmind.com/topics/http-402-based-payment-protocol-x402