ByAUJay
Metered Web3 Services: Designing Per‑Request Pricing with x402
A pragmatic guide for product and platform teams to ship pay‑per‑request APIs and web services using the x402 protocol (HTTP 402 “Payment Required”), with concrete patterns, code snippets, and emerging best practices.
x402 turns the dormant HTTP 402 status into a web‑native payment handshake. It’s open, chain‑agnostic, and designed for humans and AI agents to pay per call with stablecoins and other tokens—no accounts, no OAuth, no checkout flows. (docs.cdp.coinbase.com)
TL;DR (meta description)
x402 lets you sell API calls and web resources per request using the HTTP 402 status and a single header. In this post, 7Block Labs shows how to design pricing models, pick a facilitator, implement the exact/upto schemes, and launch on chains that settle in ~2s with zero protocol fees. (github.com)
Why per‑request pricing now
- Buyers increasingly are software: AI agents, background jobs, and server‑to‑server integrations. They need programmatic payments inside the same HTTP flow, not separate user checkouts or monthly invoices. x402 embeds payments into your existing request–response cycle. (coinbase.com)
- The protocol is open‑source (Apache‑2.0) with a public spec and multi‑language SDKs (TypeScript, Python, Go, Java), stewarded in Coinbase’s GitHub repo and growing third‑party ecosystem. (github.com)
- Adoption is accelerating: reports in Oct 2025 cite 10,000%+ monthly growth and hundreds of thousands of weekly transactions across chains as x402 endpoints and facilitators come online. Treat the exact figures as directional, but the momentum is real. (finance.yahoo.com)
What x402 actually standardizes
At its core, x402 specifies:
- A 402 JSON response shape (Payment Required Response) where your server states accepted payment options.
- A single request header clients attach after paying: X‑PAYMENT (base64‑encoded JSON payload).
- An optional response header: X‑PAYMENT‑RESPONSE, where you can return tx details for reconciliation.
- A facilitator API with /verify and /settle endpoints, so your service doesn’t need to run chain nodes or hold keys. (github.com)
x402 is transport‑native (pure HTTP): no new RPCs, no custom protocols. You return 402 with structured metadata; the client pays and retries the same URL with X‑PAYMENT. If you already know the terms (e.g., fixed cost), the initial 402 challenge can be skipped. (github.com)
The protocol flow (concrete)
- Client requests a paid resource.
- Server responds 402 with pricing and accepted rails (chain, token, scheme).
- Client constructs a scheme‑specific payment payload, signs EIP‑712 where applicable, and pays.
- Client retries with X‑PAYMENT; server verifies via local logic or a facilitator (/verify), settles via /settle, and returns 200 with your data and optional X‑PAYMENT‑RESPONSE. (github.com)
Example 402 body (simplified, valid fields from the spec):
{ "x402Version": 1, "accepts": [ { "scheme": "exact", "network": "base", "asset": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "maxAmountRequired": "1000", "resource": "https://api.example.com/premium-data", "description": "Stock price snapshot", "mimeType": "application/json", "payTo": "0xYourMerchantAddress", "maxTimeoutSeconds": 30, "extra": { "name": "USD Coin", "version": "2" } } ] }
What the client sends next (header):
X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYmFzZSIsInBheWxvYWQiOns... (base64 JSON)
The server’s success response can include:
X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0eEhhc2giOiIweDk4Yy4uLiIsIm5ldHdvcmtJZCI6ImJhc2UifQ==
Refer to the specification for the full TypeScript type definitions and header encoding rules. (github.com)
Schemes: exact now, upto for variable units
- exact: charge a fixed price per request (e.g., $0.01 for an endpoint). This ships in the core spec today across EVM implementations. (github.com)
- upto: let the caller authorize “up to” N units, and you settle the final amount post‑work based on usage (e.g., tokens generated, MB processed). Several SDKs, like thirdweb’s facilitator, expose an upto mode for EVM and SVM pilots while the community converges on standard semantics. This is the right fit for LLMs or any variable‑cost workloads. (portal.thirdweb.com)
Choosing chains and tokens (what works in production)
- EVM + USDC (EIP‑3009): Gasless, signature‑based transfers using transferWithAuthorization/receiveWithAuthorization. Many x402 stacks default to USDC because it supports EIP‑3009 natively. When called correctly (prefer receiveWithAuthorization from contracts), you avoid front‑running pitfalls. (eips.ethereum.org)
- EVM + any ERC‑20 with ERC‑2612 permit: thirdweb’s facilitator now auto‑detects whether a token supports permit versus EIP‑3009 and chooses the right flow. That unlocks 170+ EVM chains and a wide token universe. (portal.thirdweb.com)
- Settlement times: x402 literature markets “~2‑second settlement” and chain‑agnosticity. In practice, pick networks with fast finality and native USDC for best UX; protocol‑level fees are zero, but you’ll still pay gas and any facilitator fee. (x402.org)
Heads‑up details we’ve validated in the field:
- ERC‑3009 is EIP‑712‑based; use receiveWithAuthorization when moving tokens into your contract to prevent mempool preimage sniping. (eips.ethereum.org)
- Not every chain’s “USDC” is the same: bridged variants may not be EIP‑3009‑compatible. Verify token ABIs and domain separators (name, version) for permit/EIP‑3009 at runtime. (web3-ethereum-defi.readthedocs.io)
- Legacy tokens might lack ERC‑2612; build a graceful fallback (approve flow) or switch to Permit2 per your risk posture. (0x.org)
Facilitators: who verifies and settles the payment?
A facilitator abstracts RPCs, gas, and signature checks so your API team doesn’t. You can use:
- Coinbase x402 Facilitator: official reference with docs, Embedded Wallets integration, and business treasury settlement. Good fit if you want operational simplicity and optional fiat off‑ramp via Coinbase Business. (coinbase.com)
- thirdweb x402: client/server SDKs, wrapFetchWithPayment, node‑free verification/settlement and support for ERC‑2612 and EIP‑3009 flows; ships exact and upto modes. (portal.thirdweb.com)
- Ecosystem facilitators and gateways:
- AEON on BNB Chain (handles tokens with/without EIP‑3009). (finance.yahoo.com)
- Sol402 for Solana USDC pay‑per‑link/pay‑per‑API in minutes. (sol402.app)
- 402x (dashboard tooling “powered by x402”). (402x.io)
- Payin’s public explainer/spec walks the 4‑step protocol flow. (payin.com)
All facilitators must expose the same minimal REST: POST /verify, POST /settle, GET /supported. Swap providers without rewriting your app. (github.com)
Implementation: minimum viable 402 in under 30 minutes
Server (Express, EVM, USDC on Base), using the reference middleware pattern:
// server.ts import express from "express"; import { paymentMiddleware } from "x402/server"; // representative import per README const app = express(); // Charge $0.01 per call; receive funds to your address app.use(paymentMiddleware("0xYourMerchantAddress", { "/v1/report": "$0.01" })); app.get("/v1/report", async (_req, res) => { res.json({ ok: true, data: await buildReport() }); }); app.listen(3000);
The middleware handles: returning a conformant 402 JSON, verifying X‑PAYMENT via /verify, settling via /settle, and attaching X‑PAYMENT‑RESPONSE with txHash when successful. See the repo’s examples for complete environment setup. (github.com)
Client (browser/Node) that auto‑pays on 402:
import { wrapFetchWithPayment } from "thirdweb/x402"; import { createThirdwebClient } from "thirdweb"; import { createWallet } from "thirdweb/wallets"; const client = createThirdwebClient({ clientId: process.env.TW_CLIENT_ID! }); const wallet = await createWallet("io.metamask").connect({ client }); const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet); // Will automatically parse the 402, sign EIP-712, pay USDC, and retry const r = await fetchWithPay("https://api.example.com/v1/report"); console.log(await r.json());
This path requires no account creation, redirects, or UI prompts—appropriate for agents and backends. (portal.thirdweb.com)
Pricing models that map well to x402
-
Fixed per‑call (exact)
- Best for discrete, bounded work: “$0.01 per lookup,” “$0.05 per image upscaling.”
- Configuration: one accept entry with maxAmountRequired = price_in_atomic_units; reject on over‑quota by returning 402 again. (github.com)
-
Elastic usage (upto)
- For tokenized workloads like LLMs, storage, or egress: “$0.10 per 1K tokens,” “$0.002 per MB.”
- Flow: you quote a max cap; client authorizes upto N; after work, you settle actuals ≤ cap. Ship a usage meter and include a usage receipt in your response body. thirdweb’s stack already exposes upto controls as a preview. (portal.thirdweb.com)
-
Bundled bursts
- Sell a pre‑paid bundle (e.g., $5) with expiry in extra, and decrement server‑side until zero. Keep the 402 roundtrip only when the bundle is exhausted. The spec’s extra and outputSchema fields are ideal to advertise semantics/units. (github.com)
-
Dual‑rail fallbacks
- Offer multiple accepts entries (e.g., Base USDC, Solana USDC). Clients pick the fastest/cheapest they support; you keep one codepath. (github.com)
Pricing calibration tips we use with clients:
- Run “shadow metering” for 2–4 weeks: log per‑request units with $0 price to estimate a viable schedule before enabling settlement.
- Price in stablecoins (USDC) first; experiment with volatile tokens only once you have clear unit economics and hedging.
- Quote in user‑facing fiat in docs, but enforce on‑chain amounts with asset decimals in maxAmountRequired.
Security, trust, and auditability
- EIP‑712 everywhere: ensure typed data includes correct chainId, verifyingContract, token name/version when signing permit or EIP‑3009 authorizations. This prevents cross‑chain replay and mis‑domain signatures. (ercs.eips.fyi)
- Prefer receiveWithAuthorization over transferWithAuthorization when moving USDC into your contract. It binds the payee and reduces front‑run vectors. (eips.ethereum.org)
- KYT/AML: production facilitators may block flagged addresses; surface errors from the 402 JSON error field so callers can recover gracefully. (docs.cdp.coinbase.com)
- Idempotency: accept an Idempotency‑Key header, bind it to the payment preimage/txHash, and avoid double work if a client retries.
- Refunds/chargebacks: not in the base spec. Implement credits (negative usage) on your side or issue a compensating on‑chain transfer with a new X‑PAYMENT‑RESPONSE correlation ID.
- Observability: always log the X‑PAYMENT payload, the facilitator’s /verify response, and your final X‑PAYMENT‑RESPONSE. Pipe txHash to your BI stack.
Compliance and accounting
- Treasury ops: Coinbase’s facilitator can route proceeds to a Coinbase Business account with fiat conversion; others pay out directly to your merchant wallet. Design a reconciliation job that matches txHash in X‑PAYMENT‑RESPONSE to your invoice line items. (coinbase.com)
- Tax: treat each call as recognized revenue when you deliver the API response; store tx hash, chain, payer address, and unit economics in your ledger.
- Privacy: x402 does not require email/account IDs. If you need attribution, add a signed client tag in your request body or use per‑buyer wallet derivation.
Architecture patterns we recommend
- Edge 402 enforcement: mount x402 middleware at the edge (Cloudflare Worker, nginx module, or facilitator‑provided gateway) so you don’t compute before payment. Some gateways (e.g., g402) run under your own domain via CNAME to preserve SSL chains and enterprise trust. (g402.ai)
- Decouple metering from business logic: route all paid endpoints through a single verifier module that emits a canonical “PaymentVerified” event you can subscribe to for analytics and refunds.
- Strict timeouts: honor maxTimeoutSeconds from your own 402 challenges; if work overruns, return a partial with a fresh 402 for the remainder. (github.com)
- Discovery: if you want agent traffic, advertise in emerging catalog layers like “x402 Bazaar” (search/discovery index for agent‑grade endpoints). (coindesk.com)
Concrete example: pay‑per‑1K tokens for an LLM endpoint (upto)
- Metering unit: output tokens; price: $0.10 per 1K.
- Challenge: return an upto cap for the requested max_tokens, e.g., maxAmountRequired = ceil(max_tokens/1000 * $0.10) in atomic USDC.
- Client: authorizes upto cap, sets a 60‑second deadline; retries with X‑PAYMENT.
- Server: completes inference, computes actual tokens, settles actual ≤ cap, returns 200 with body: { usage: { tokens: 642, cost_usdc: “0.0642” }, txHash }.
- Observability: emit metrics per buyer wallet, with p95 end‑to‑end latency from 402 to final 200.
thirdweb’s upto support makes this pattern ergonomic today while the core spec evolves. (portal.thirdweb.com)
Ecosystem snapshot (Nov–Dec 2025)
- Spec & reference: coinbase/x402 repo with examples and ROADMAP; formal type definitions include PaymentRequirements, X‑PAYMENT schema, and Facilitator API. (github.com)
- Docs: Coinbase x402 docs explain the 402 semantics, agent usage, and EIP‑712 signing. (docs.cdp.coinbase.com)
- Tooling:
- thirdweb x402 (170+ EVM chains; auto‑detect permit vs EIP‑3009). (portal.thirdweb.com)
- Sol402 (Solana USDC pay‑per‑link/API). (sol402.app)
- 402x dashboard (multi‑chain commercialization tooling). (402x.io)
- Payin explainer/spec (developer‑friendly protocol walk‑through). (payin.com)
- Market signals: large volume spikes and new facilitators (e.g., AEON on BNB Chain). Again, numbers vary by source; we advise tracking your rails via Dune or your facilitator’s analytics. (finance.yahoo.com)
Pitfalls to avoid
- Assuming all “USDC” are equal: verify EIP‑3009 presence; for ERC‑2612, fetch token name/version dynamically for EIP‑712 domain. (web3-ethereum-defi.readthedocs.io)
- Forgetting replay protection: include chainId and verifyingContract; set short validity windows (validBefore) on authorizations. (ercs.eips.fyi)
- Building your own key management: let a facilitator or embedded wallets (e.g., Coinbase Embedded Wallets) handle custody and signing where possible. (docs.cdp.coinbase.com)
- Over‑customizing the 402 JSON: stick to the spec’s fields (resource, asset, payTo, maxAmountRequired, extra). Clients depend on predictable shapes. (github.com)
Launch checklist (7Block Labs playbook)
-
Product
- Define the metering unit (request, 1K tokens, MB).
- Start with exact; graduate to upto once you have precise metering.
- Price in USDC; publish a fiat mapping table for docs.
-
Engineering
- Integrate facilitator and middleware; return spec‑compliant 402.
- Implement idempotency and rate limits; emit canonical events.
- Log X‑PAYMENT, /verify result, and txHash for accounting.
-
Security & Compliance
- EIP‑712 domain checks; short deadlines; receiveWithAuthorization. (eips.ethereum.org)
- KYT outcomes surfaced in error field; fallback UX for blocked payers. (docs.cdp.coinbase.com)
- Reconciliation job that matches txHash ↔ request ↔ revenue line.
-
Ops
- Shadow meter for 2–4 weeks; then turn on settlement.
- Wire Dune or your data lake to tx hashes for live dashboards.
- Document buyer responsibilities (wallet funding, supported rails).
If you’re comparing to L402/LSAT (Lightning)
Lightning’s L402 (formerly LSAT) pioneered 402‑based paid APIs using macaroons + Lightning invoices. It’s production‑proven (e.g., Aperture proxy) and great for sats‑denominated micropayments. x402 generalizes the 402 paradigm across blockchains and tokens, with stablecoin‑centric flows and HTTP‑first headers. Many product teams will choose based on rails availability and org readiness; both approaches keep payments in‑flow. (docs.lightning.engineering)
Where this is heading
We’re seeing a convergence around:
- A common 402 response shape across chains and tokens.
- Agent‑first tooling (SDKs that auto‑negotiate 402, pick rails, and retry). (docs.cdp.coinbase.com)
- Discovery layers (x402 Bazaar) so agents can find/price endpoints. (coindesk.com)
- New schemes (upto, streaming, Permit2) and broader token support. (docs.cdp.coinbase.com)
Work with 7Block Labs
We’ve shipped x402 pilots on Base, Optimism, and Solana for per‑request APIs in data, media, and AI inference. If you want to:
- Stand up an edge 402 gateway under your domain,
- Model per‑request economics and roll out exact/upto pricing,
- Integrate facilitators without touching keys, and
- Instrument Dune‑grade analytics tied to txHash,
reach out—our accelerator packages get you live in weeks, not quarters.
References and further reading
- x402 spec, headers, facilitator API, and examples (coinbase/x402 repo). (github.com)
- Coinbase x402 docs: HTTP 402 semantics, Embedded Wallets, and agent flow. (docs.cdp.coinbase.com)
- thirdweb x402: server/client, ERC‑2612 + EIP‑3009 support, exact/upto. (portal.thirdweb.com)
- Sol402 (Solana USDC), 402x dashboard, Payin explainer. (sol402.app)
- Adoption signals and ecosystem news (CoinDesk, Yahoo Finance, Cointelegraph). (coindesk.com)
- L402/LSAT and Aperture for Lightning‑native paid APIs. (docs.lightning.engineering)
Like what you're reading? Let's build together.
Get a free 30‑minute consultation with our engineering team.

