ByAUJay
Building Agentic Commerce Rails: x402 Patterns for Machine-to-Machine Payments
Short summary: x402 turns the once-unused HTTP 402 status code into an internet‑native payment rail that AI agents and services can speak over plain HTTP. This guide distills concrete x402 patterns, code-level details, and emerging best practices to help you ship machine-to-machine payments that settle in seconds across chains.
Why x402 matters for decision‑makers
The agent economy needs a payment primitive that is:
- Web-native (no custom sockets or SDK lock‑in),
- Programmatic for machines (no human checkout),
- Cheap enough for micropayments,
- Fast enough to keep request latency acceptable.
x402 delivers this by standardizing pay-per-request over HTTP using 402 Payment Required, a pair of well-defined headers, and a “facilitator” role for verification/settlement. It’s chain-agnostic, supports multiple payment schemes, and can be added to existing APIs as middleware. (github.com)
A 90‑second mental model of x402
- Your API stays HTTP/HTTPS.
- If a client (human or agent) hits a paid endpoint without a proof of payment, your server replies 402 with machine-readable payment requirements.
- The client pays using the scheme/network you accept (e.g., USDC on an EVM L2) and retries with an X-PAYMENT header that encodes the payment proof.
- You verify locally or by calling a facilitator’s /verify, optionally ask the facilitator to /settle, then respond 200 with X-PAYMENT-RESPONSE that includes tx details. (github.com)
Key protocol objects and headers:
- PaymentRequirements (your 402 response payload)
- X-PAYMENT (client’s payment payload)
- X-PAYMENT-RESPONSE (your 200 response back) (github.com)
The x402 stack in 2025: what’s real, where to build
- Core spec and reference stacks: Coinbase’s x402 repo ships spec, types, middleware, a facilitator API, and examples in TS/Go/Java/Python. It defines the “exact” scheme now, with “upto” (usage-capped) proposed. (github.com)
- Multi-chain: Official stance is chain and token agnostic; marketing phrase “2-second settlement” reflects typical L2/Solana block times, not a requirement. Treat it as target UX. (x402.org)
- Solana: Dedicated ecosystem page and starter templates exist (Next.js stacks, facilitators, explorers). If you want sub‑cent fees with fast finality, this path is hot. (solana.com)
- EVM gasless: Thirdweb’s facilitator verifies and settles x402 payments and can sponsor gas using EIP‑7702 so clients don’t need native gas. Good default for web2‑grade UX. (portal.thirdweb.com)
- USDC signatures and token quirks: Many flows rely on EIP‑3009 (transferWithAuthorization) and/or ERC‑2612 permit. Know chain/token differences—e.g., Polygon PoS “USDC” historically didn’t match EIP‑3009 semantics 1:1. (web3-ethereum-defi.readthedocs.io)
- BNB gaps: Because many BNB Chain assets don’t ship EIP‑3009, Infra402 wraps assets (e.g., xBNB) to restore signature‑only x402 flows and facilitator‑level settlement/analytics. Useful if BNB is in your go‑to‑market. (infra402.com)
- Third‑party wallets/CLIs: x402 wallet CLIs exist for agent automation: create EIP‑3009 authorizations, operate on Base/Ethereum/Base Sepolia. Handy for headless agents and CI. (x402-wallet.com)
Related but distinct:
- Interledger’s Open Payments and STREAM are account‑to‑account settlement APIs (great for bank/wallet integrations), not HTTP 402 headers; you can compose them for fiat on/off‑ramps or cross‑network routing. (github.com)
- Cloudflare’s Pay‑Per‑Crawl shows 402 at Internet scale with price negotiation via headers, validating the 402 handshake pattern; it’s not x402, but the semantics rhyme. (blog.cloudflare.com)
The x402 patterns we recommend shipping in 2025
Below are concrete “rails” we deploy for clients. Copy the patterns, not just the code.
1) 402 Handshake: Reactive vs Intent‑First
- Reactive (discovery-first): The client hits your paid endpoint, you 402 with requirements. Client pays, retries with X-PAYMENT. Latency adds one round trip. Best for heterogeneous agents discovering pricing on the fly. (github.com)
- Intent‑First (precommit): Client proactively includes payment proof (or a capped willingness‑to‑pay) on the first request based on your advertised requirements. You 200 straight away if valid. Inspired by at‑scale 402 patterns (think crawler‑max‑price vs crawler‑exact‑price). (blog.cloudflare.com)
Practical tip:
- Publish a .well-known/prices.json (or embed in OpenAPI x‑extension). Agents can fetch once, cache with max-age, and go intent‑first to avoid the extra 402.
2) Exact Price Payments (today’s production workhorse)
Use the “exact” scheme, quote a fixed amount, and require EIP‑3009 authorization (USDC) or ERC‑2612 permit (other ERC‑20s) for signature‑only flows. Your PaymentRequirements should include: scheme, network, maxAmountRequired (atomic units), payTo, asset, and maxTimeoutSeconds. (github.com)
Example PaymentRequirements (excerpt):
{ "x402Version": 1, "accepts": [{ "scheme": "exact", "network": "eip155:8453", // Base mainnet "maxAmountRequired": "10000", // 0.01 USDC if 6 decimals "resource": "https://api.example.com/premium-data", "description": "Pay-per-call for premium data", "mimeType": "application/json", "payTo": "0xMerchantWallet...", "maxTimeoutSeconds": 10, "asset": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // example "extra": { "name": "USD Coin", "version": "2" } }] }
Contract nuance: If using EIP‑3009, ensure you consume authorizations exactly once (receiveWithAuthorization) and record the nonce to prevent replay. Non‑compliant bridges/tokens may require a fallback path. (web3-ethereum-defi.readthedocs.io)
3) Usage‑Capped “Upto” Payments (emerging)
For metered APIs (LLM tokens, compute seconds), define an “upto” requirement (client signs permission up to a cap; you charge the exact consumption). This scheme is discussed as an extension in x402; nail your measurement, idempotency, and partial‑fulfillment semantics up front. (github.com)
Production tips:
- Over‑authorize up to a session cap (e.g., $0.25), debit exactly consumed, return the unspent cap in your X-PAYMENT-RESPONSE for client accounting.
- Return structured metering: billable_units, unit_price, total_charged.
4) Gasless UX via EIP‑7702 or Paymasters
Two turnkey paths:
- 7702 sponsorship (recommended where supported): Promote EOAs to “smart EOAs” with session keys and sponsor gas so agents sign once, no native gas required. thirdweb exposes this in one config flag. (portal.thirdweb.com)
- ERC‑4337 + Paymaster for USDC gas: Circle’s Paymaster can draw gas from user USDC via an EIP‑2612 permit, ideal when your wallet stack is already 4337‑native. (circle.com)
When tokens lack EIP‑3009/2612:
- Wrap/upgrade approach (BNB example): Infra402’s wrapping turns arbitrary assets into 3009‑style signature flows, preserving “signature‑only” x402 UX. (infra402.com)
5) Facilitator‑First Architecture
Outsource verification and settlement to a facilitator microservice (your infra or a vendor). The spec defines /verify, /settle, and /supported. Keep your resource server stateless and fast; call the facilitator for the heavy lifting. thirdweb’s facilitator supports 170+ EVM chains out of the box. (github.com)
Pattern:
- Write‑path: resource → facilitator.verify() → fulfill → facilitator.settle() → respond.
- Resilience: if settle fails post‑fulfillment, persist a “debt” record and run a compensating settlement job with alerts.
6) Dual‑Network Acceptance
Advertise multiple accepts entries: e.g., USDC on Base and SOL on Solana. Always encode the chain in both requirement and proof, and verify chain‑id to avoid cross‑chain replay. Solana builders: use the x402 Solana starter and facilitator to keep the exact same handshake. (github.com)
7) Receipts and Attestations
Return X-PAYMENT-RESPONSE with settlement details (txHash, networkId). Mirror to your analytics warehouse. Agents can ingest this header as structured data for expense accounting and retries. It’s part of the core spec. (github.com)
8) Idempotency and Replays
- Require an Idempotency-Key on paid endpoints, dedupe on your side.
- For EIP‑3009, enforce unique nonce and validity windows (validAfter/validBefore). Some chain/token variants diverge; test replays on each chain you support. (web3-ethereum-defi.readthedocs.io)
9) Refunds and Disputes
Implement a /refunds endpoint keyed by the original X-PAYMENT and txHash. Settlements are final on-chain; you refund as a fresh on-chain payment with your own receipt header. Include a “reason” code taxonomy for reconciliations.
10) Pricing Discovery and Caching
- Publish machine-readable pricing (per endpoint) and cache control.
- Use 402 only for churn‑free negotiation. Large crawlers at web scale already do intent negotiation with headers (max‑price, exact‑price). Adopt the same ergonomics in x402 clients. (blog.cloudflare.com)
Code: minimal Express server with a facilitator
Below is an intentionally small sketch integrating the core x402 flow on an EVM L2 with a facilitator. It omits authz edge cases, logging, and retries for brevity.
import express from "express"; import { encodePaymentHeader, verifyWithFacilitator, settleWithFacilitator } from "./x402-kit"; // your wrapper import { toAtomic } from "./pricing"; const app = express(); const payTo = process.env.MERCHANT!; // 0x... const asset = process.env.USDC!; // ERC-20 address const network = "eip155:8453"; // Base mainnet const price = toAtomic("0.01", 6); // 0.01 USDC function paymentRequirements() { return { x402Version: 1, accepts: [{ scheme: "exact", network, maxAmountRequired: price.toString(), resource: "https://api.example.com/premium-data", description: "Premium dataset, per-request", mimeType: "application/json", payTo: payTo, maxTimeoutSeconds: 10, asset, extra: { name: "USD Coin", version: "2" } }] }; } app.get("/premium-data", async (req, res) => { const paymentHeader = req.header("X-PAYMENT"); if (!paymentHeader) { res.status(402).json(paymentRequirements()); return; } // Verify payment intent & payload const ver = await verifyWithFacilitator({ x402Version: 1, paymentHeader, paymentRequirements: paymentRequirements().accepts[0], }); if (!ver.isValid) { res.setHeader("X-PAYMENT-RESPONSE", encodePaymentHeader({ error: ver.invalidReason })); res.status(402).json(paymentRequirements()); return; } // Fulfill work and try to settle const body = { data: "your premium JSON goes here" }; const settle = await settleWithFacilitator({ x402Version: 1, paymentHeader, paymentRequirements: paymentRequirements().accepts[0], }); res.setHeader("X-PAYMENT-RESPONSE", encodePaymentHeader(settle)); res.status(200).json(body); }); app.listen(3000);
- Swap in a real facilitator: thirdweb’s facilitator exposes /verify and /settle and can sponsor gas with EIP‑7702. (portal.thirdweb.com)
- For Solana, use the Solana x402 template and facilitator; the HTTP flow is identical, payloads differ. (solana.com)
Security checklist that actually catches bugs
- Replay resistance:
- EIP‑3009: Enforce unique authorization nonces server‑side, and consume with receiveWithAuthorization; beware chain‑specific deviations (Polygon PoS historical caveats). (web3-ethereum-defi.readthedocs.io)
- Non‑EVM: Use native network replay guards (e.g., Solana memo/nonces via your facilitator).
- Header tampering: Always verify the on‑chain proof. Do not trust client‑declared amounts/receivers without verification.
- HTTPS only: Reject x402 over plaintext; treat X-PAYMENT like auth.
- Timeboxes: Honor maxTimeoutSeconds from your own requirements and your business SLA. If fulfillment overruns, either partial‑fulfill or refund.
- Settlement failure handling: If verification passes but settlement fails, respond 200 (you did the work) but write a compensating settlement job and raise an alert. Facilitator “success: false” should not silently drop. (github.com)
- Multi‑tenant separation: If you run a facilitator for many merchants, isolate signer keys and audit all /settle paths. thirdweb’s facilitator uses your server wallet for receiving; keep keys HSM‑backed. (portal.thirdweb.com)
Architecture blueprints
- “Stripe‑for‑Agents” aggregator
- Who: Platforms enabling thousands of developers to sell API, compute, or data to agents.
- What: Multi‑tenant facilitator + marketplace; take a platform fee via x402 “developer fee” (where supported) or second‑line settlement rule. Sponsor gas with 7702 out of the box to cut onboarding friction. (blog.thirdweb.com)
- DePIN & robotics payments
- Combine x402 as the money rail with an agent trust/identity layer (see ERC‑8004: Trustless Agents) to reduce fraud between devices (docks, drones, sensors). Projects like M402 position identity/reputation next to x402 settlement. (eips.ethereum.org)
- Enterprise hybrid: x402 + Interledger/Open Payments
- Use x402 at the edge for on‑demand API monetization; sweep merchant balances daily into banked accounts using Open Payments over ILP where your treasury team needs ACH/SCT rails and counterparty KYC. (github.com)
Tooling snapshot: what to evaluate this quarter
- Coinbase x402 reference implementation (specs, TS SDKs, examples). (github.com)
- x402.org ecosystem index (learners, tools, servers). (x402.org)
- thirdweb x402 facilitator + 7702 sponsorship + session keys (170+ EVM chains). (portal.thirdweb.com)
- Solana x402 templates and facilitator options. (solana.com)
- h402 protocol variant (EVM + Solana support and roadmap for “upto/streamed/subscription”). Useful to study alt header and settlement designs. (github.com)
- Proxy402 docs (conceptual primer for team onboarding). (docs.proxy402.com)
- Infra402 (BNB-first wrapping to unlock signature‑only flows). (infra402.com)
- Reference 402 behavior at web scale (Cloudflare PPC docs). (developers.cloudflare.com)
Pricing and UX: patterns that convert
- Quote in stablecoins by default (USDC on Base/Solana), then optionally offer volatile assets for prosumers.
- Latency budget: aim for sub‑500 ms added by verification+settlement; facilitator‑verify during processing, settle asynchronously if network is congested.
- Partial refunds: for “upto” sessions, surface unspent cap in X-PAYMENT-RESPONSE so agents can reconcile budgets.
- “Try free then pay”: gate expensive result generation (final output) behind x402; return previews or low‑res artifacts for free.
- Developer ergonomics: provide a client helper that automatically handles 402, signs, pays, retries, and exposes typed errors. That’s how the x402 client examples are structured. (github.com)
Compliance and risk notes (what legal will ask)
- x402 keeps PII minimal: it’s per‑request settlement, no mandatory accounts. Keep it that way unless you’re subject to KYC thresholds.
- Tax: issue on‑chain receipts and monthly summaries; X-PAYMENT-RESPONSE headers + ledger tables suffice for most auditors if reconciled to bank statements (when sweeping via Open Payments/ILP or an exchange). (openpayments.dev)
- Chargebacks: there are none on-chain. Your refund policy must be explicit, automated, and logged.
Appendix: client ergonomics and header design inspiration
At Internet scale, crawlers negotiate price with headers and 402 round‑trips (max‑price vs exact‑price) before receiving a 200 with a “charged” confirmation header. If your agents fetch paid content, adopt the same pattern with x402: intent‑first where possible; 402 fallback when not. (blog.cloudflare.com)
For line‑level dev docs on 402 status semantics, MDN clarifies the status is “reserved” historically—x402 gives it standardized meaning for payments. (developer.mozilla.org)
Where 7Block Labs helps
- Discovery workshop: pick your chains, scheme(s), and facilitator model (build/run vs partner).
- Reference implementation: we’ll ship a production‑grade x402 gateway with 7702 gasless, idempotency, retries, alerts, analytics, and refund flows in 4–6 weeks.
- Marketplace/DePIN blueprints: combine x402 with ERC‑8004 trust signals and Open Payments for bank sweeps.
If you want agents to pay your APIs in under a second without forcing accounts, x402 is the shortest path from “we should charge for this” to live revenue.
References and further reading
- x402 protocol spec and examples. (github.com)
- x402.org overview and ecosystem. (x402.org)
- thirdweb x402 facilitator and EIP‑7702 gas sponsorship. (portal.thirdweb.com)
- Solana x402 builders page and templates. (solana.com)
- EIP‑3009 USDC nuances (Polygon PoS caveat) and tooling. (web3-ethereum-defi.readthedocs.io)
- Circle Paymaster for 4337 gas with USDC. (circle.com)
- Infra402 (BNB-first wrapping for x402). (infra402.com)
- h402 variant (EVM+Solana). (github.com)
- Interledger Open Payments and STREAM. (github.com)
- Cloudflare Pay‑Per‑Crawl (402 at scale). (blog.cloudflare.com)
- ERC‑8004 Trustless Agents (draft). (eips.ethereum.org)
Like what you're reading? Let's build together.
Get a free 30‑minute consultation with our engineering team.

