7Block Labs
Blockchain Technology

ByAUJay

x402 Explained: Turning HTTP 402 into Stablecoin-Paid API Access

Short summary: x402 revives HTTP 402 with a practical, open protocol that lets your APIs price each request and get paid in stablecoins, no accounts or API keys required. This post shows how it works, why USDC on Base is the default, and how to ship it in production today, with concrete examples and emerging best practices.

Why this matters now

HTTP 402 “Payment Required” was reserved for a future web where machines could pay for resources. That future just arrived. The x402 protocol standardizes how a server challenges with 402, how a client pays, and how settlement is verified—so you can sell any endpoint for $0.001–$1.00, instantly and programmatically, using stablecoins. (developer.mozilla.org)


What is x402 (and what it isn’t)

  • x402 is an HTTP-native payments protocol:
    • Server replies 402 with machine-readable “payment requirements.”
    • Client signs a payment payload and retries the same HTTP request with an X-PAYMENT header.
    • Server verifies and settles (locally or via a facilitator) and returns 200 with your normal JSON. (github.com)
  • It’s asset- and chain-agnostic, but the production default is USDC with EIP‑3009 signatures on Base (and SPL on Solana). (docs.cdp.coinbase.com)
  • It’s not a custodial gateway: the facilitator verifies and broadcasts onchain; it cannot move funds without the buyer’s signature. (docs.cdp.coinbase.com)

x402 differs from Lightning’s L402/LSAT (macaroons + Lightning invoices). If you want dollar‑denominated pricing, enterprise‑grade KYT/OFAC screening, and onchain settlement, x402 is the right primitive; if you want sats and Lightning-first auth, look at L402 + Aperture. (docs.lightning.engineering)


How the 402 → pay → retry handshake works

  1. Client calls your API
  2. Your server replies 402 with JSON payment requirements (price, asset, payTo, network, timeout)
  3. Client constructs a signed payment payload and retries with X-PAYMENT
  4. Server verifies/settles (often via a facilitator)
  5. Server returns 200 and includes X-PAYMENT-RESPONSE with settlement details (tx hash, network) (github.com)

Visually and technically, this is all a single HTTP roundtrip with one 402 “challenge” and one paid retry.


The 402 response: a concrete, production-ready example

For USDC on Base mainnet (chainId 8453; USDC address 0x833589…2913), your server could send: (docs.base.org)

HTTP/1.1 402 Payment Required
Content-Type: application/json

{
  "x402Version": 1,
  "accepts": [
    {
      "scheme": "exact",
      "network": "base",
      "maxAmountRequired": "1000",           // 0.001 USDC (USDC has 6 decimals)
      "resource": "https://api.example.com/v1/forecast",
      "description": "Per-request weather forecast",
      "mimeType": "application/json",
      "outputSchema": {
        "input": { "type": "http", "method": "GET" },
        "output": null
      },
      "payTo": "0xYourMerchantAddress",
      "maxTimeoutSeconds": 60,
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "extra": { "name": "USD Coin", "version": "2" }
    }
  ]
}

Fields and semantics are part of the open x402 spec (v1). “scheme: exact” means the client must pay exactly maxAmountRequired in the stated asset and network. (github.com)


The paid retry: X-PAYMENT header for EVM (USDC/EIP‑3009)

On EVM networks, x402 uses EIP‑712 typed data to authorize a USDC transfer via EIP‑3009’s transferWithAuthorization/receiveWithAuthorization, enabling signature-only, gas‑abstracted transfers the facilitator can broadcast (no prior approve or native ETH required for the buyer). (eips.ethereum.org)

GET /v1/forecast?city=SF HTTP/1.1
Host: api.example.com
X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6MSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYmFzZSIsInBheWxvYWQiOnsiYXV0aG9yaXphdGlvbiI6eyJmcm9tIjoiMHhCdXllciIsInRvIjoiMHhZb3VyTWVyY2hhbnRBZGRyZXNzIiwidmFsdWUiOiIxMDAwMCIsInZhbGlkQWZ0ZXIiOiIwIiwidmFsaWRCZWZvcmUiOiIxNzM1Njg5NjAwIiwibm9uY2UiOiIweEFiY2QifSwic2lnbmF0dXJlIjoiMHhTaWduYXR1cmUifX0=

The decoded JSON looks like:

{
  "x402Version": 1,
  "scheme": "exact",
  "network": "base",
  "payload": {
    "authorization": {
      "from": "0xBuyer",
      "to":   "0xYourMerchantAddress",
      "value": "1000",
      "validAfter": "0",
      "validBefore": "1735689600",
      "nonce": "0x…32bytes"
    },
    "signature": "0x…"
  }
}
  • EIP‑3009 is the mechanism USDC v2 implements to enable this signature‑only transfer flow. (eips.ethereum.org)
  • USDC on Base mainnet lives at 0x833589…2913 (6 decimals). (developers.circle.com)

On success, servers may include:

X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0eEhhc2giOiIweGFiaWMiLCJuZXR3b3JrSWQiOiI4NDUzIn0=

Where txHash/networkId come from facilitator settlement. (github.com)


Solana variant (SPL USDC) in x402

On Solana, x402’s “exact” scheme uses a partially-signed SPL transfer transaction (base64-encoded) in the payload; the facilitator adds the fee payer signature and broadcasts. You still do 402 → X-PAYMENT, just with a Solana transaction instead of EIP‑712. (x402.gitbook.io)

{
  "x402Version": 1,
  "scheme": "exact",
  "network": "solana",
  "payload": {
    "transaction": "base64-encoded-partially-signed-transaction"
  }
}

Most facilitators accept USDC (SPL) and other SPL/Token‑2022 tokens; the response/verification is the same shape as EVM. (x402.gitbook.io)


Why USDC on Base is the default for enterprises

  • Predictable, dollar‑denominated pricing (USDC) with EIP‑3009 for one‑shot, gas‑abstracted transfers. (eips.ethereum.org)
  • Coinbase’s hosted facilitator (CDP) offers fee‑free USDC settlement on Base mainnet, with KYT/OFAC checks and SLAs—turnkey production posture. (docs.cdp.coinbase.com)
  • Base chain IDs: 8453 (mainnet) and 84532 (Sepolia) are widely supported in infra/tooling, and the official USDC contract address is published by Circle. (docs.base.org)

Note: If you need non‑USDC assets, facilitators and SDKs are expanding beyond EIP‑3009 (e.g., adding EIP‑2612 “permit” and Permit2), but today USDC is the smoothest path. (github.com)


Shipping x402 in your stack (Node and Python)

Add a payment middleware, list which routes are paid, and point at a facilitator.

  • Express (Node):
import express from "express";
import { paymentMiddleware } from "x402-express";
// For mainnet facilitator with CDP keys:
// import { facilitator } from "@coinbase/x402";

const app = express();

app.use(paymentMiddleware(
  "0xYourMerchantAddress",
  { "GET /v1/forecast": { price: "$0.001", network: "base" } },
  // For testnet without keys:
  { url: "https://x402.org/facilitator" }
));

app.get("/v1/forecast", (req, res) => { res.json({ tempF: 70 }); });
app.listen(4021);
  • FastAPI (Python):
from fastapi import FastAPI
from x402.fastapi.middleware import require_payment

app = FastAPI()
app.middleware("http")(
    require_payment(
        path="/v1/forecast",
        price="$0.001",
        pay_to_address="0xYourMerchantAddress",
        network="base",
    )
)

These match the official Quickstarts and encapsulate all header/base64/facilitator logic for you. (x402.gitbook.io)


Verification and settlement: you choose the trust boundary

  • Local verify/settle: run your own chain connections and verify signatures on your infra.
  • Facilitator verify/settle (recommended): call /verify then /settle on a facilitator, get back isValid and a txHash; return 200 to the client with X-PAYMENT-RESPONSE. (github.com)

CDP’s facilitator (production): Base and Solana (plus testnets), fee‑free USDC settlement on Base, API key scoped; community and self‑hosted facilitators also exist across Base, Solana, Polygon, Avalanche, and more. (docs.cdp.coinbase.com)


Discovery: get found by AI agents (x402 Bazaar)

If you set discoverable: true on your route config, CDP’s facilitator will list your endpoint in the x402 Bazaar so buyers/agents can discover and call it programmatically. You can query all discoverable services at:
GET https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources. (x402.gitbook.io)


Pricing and metering patterns we see working

  • Start at $0.001–$0.01 per call; raise for GPU/LLM or bulk data. The spec encodes price as atomic units (USDC has 6 decimals; 1 USDC = 1,000,000 units). (github.com)
  • Set maxTimeoutSeconds to 60–120 so signatures can clear and you can keep the request warm. (x402.gitbook.io)
  • Use one path per SKU: e.g., /v1/forecast (cheap), /v1/history (mid), /v1/forecast/pro (premium).
  • Return mimeType and brief description so agents can choose the right route.
  • Add outputSchema so agents know what to expect; keep it small to reduce friction. (x402.gitbook.io)

Roadmap to dynamic billing: x402 defines schemes; “exact” ships today; “upto/stream/permit2” are active areas, enabling token‑based streaming or “up to X” caps for LLM tokens or bandwidth. Track the public PRs/issues to adopt early. (github.com)


Security, compliance, and ops checklists

  • EIP‑712 correctness: chainId, verifyingContract, token name/version must match your USDC (or custom token). For EVM, use the token’s name() and version() (USDC: “USD Coin”, version “2”). (x402.gitbook.io)
  • Nonce/TTL: set validBefore ~60s and a random 32‑byte nonce; reject replays and late arrivals. (eips.ethereum.org)
  • KYT/OFAC: use a facilitator that screens transactions (CDP does this on Base). (docs.cdp.coinbase.com)
  • Reconciliation: decode X-PAYMENT-RESPONSE (txHash, networkId) and store it with your request ID; ship idempotency keys in the resource URL if the backend isn’t idempotent. (github.com)
  • Observability: log 402s with the accepts[0] fields; log verify/settle durations and invalidReason if a payment fails.
  • Token choice caveats: USDC implements EIP‑3009; some bridged tokens (e.g., legacy Polygon USDC.e) aren’t 1:1 EIP‑3009 compatible; verify the exact contract supports transferWithAuthorization on your target chain. (web3-ethereum-defi.readthedocs.io)

Example: metering a GPU inference endpoint

  1. Protect /v1/infer at $0.003 on Base: price: "$0.003", network: "base".
  2. Client hits /v1/infer; receives 402 with accepts[0].
  3. Client’s SDK (x402-axios or x402-fetch) auto‑detects 402, constructs the EIP‑712 payload, signs, retries with X‑PAYMENT, then parses X‑PAYMENT‑RESPONSE for txHash.
  4. You return the inference JSON immediately after verification; facilitator settles onchain in the background and returns txHash (~seconds on Base). (x402.gitbook.io)

Stablecoins vs. Lightning: quick decision matrix

  • Choose x402 when you want:
    • USD pricing with stablecoins
    • Enterprise compliance (KYT/OFAC)
    • HTTP-native integration with EIP‑712/EIP‑3009 semantics
    • Discovery for agent ecosystems (Bazaar)
  • Choose L402 (Aperture) when you want:
    • Sats-first micropayments over Lightning
    • Macaroon-based auth (attenuation/delegation)
    • Reverse proxy that prices and challenges for you (github.com)

Both models use HTTP 402; they just settle on different rails and use different auth primitives.


Emerging best practices (late‑2025)

  • Make your endpoints discoverable: x402 Bazaar will be where agents find pay‑per‑use capabilities; include concise description + input/output schema. (x402.gitbook.io)
  • Prefer Base+USDC for first launch: lowest integration risk, fee‑free settlement via CDP, strong tooling. (docs.cdp.coinbase.com)
  • Offer a Solana SKU for high‑throughput or mobile wallets; same server code—swap network and asset. (x402.gitbook.io)
  • Adopt permit/Permit2 once the SDKs stabilize to broaden token coverage beyond EIP‑3009. (github.com)
  • Add a 402 cache: if multiple callers hit the same resource in rapid succession, cache the accepts object for a minute to reduce facilitator load.

Implementation pitfalls we see (and how to avoid them)

  • Wrong domain data in EIP‑712 (name/version mismatch) → “invalid_exact_evm_payload_signature.” Fetch name() / version() from the token contract (USDC: name “USD Coin”, version “2”). (github.com)
  • Using testnet network strings on mainnet (e.g., "base-sepolia" instead of "base"). Verify your chain and USDC balance. (docs.cdp.coinbase.com)
  • Assuming the buyer has gas: EIP‑3009 is gas‑abstracted; the facilitator sponsors gas, but your server still needs a network choice where EIP‑3009 works. (eips.ethereum.org)
  • Polygon USDC.e differences: not fully EIP‑3009-compatible; test your target token’s functions before listing it in accepts[]. (web3-ethereum-defi.readthedocs.io)

Procurement guide: facilitator options

  • CDP (Coinbase): Base/Solana mainnets, fee‑free USDC settlement on Base, KYT/OFAC, SLAs; requires API keys. Best for enterprise. (docs.cdp.coinbase.com)
  • Community facilitators: quick prototyping, broad network coverage (e.g., Base, Solana, Polygon, Avalanche). Validate reliability and token support. (x402.gitbook.io)
  • Self‑hosted: full control; add your own EVM chains by providing chainId, USDC address, and viem chain config. (x402.gitbook.io)

Add agents to the party (MCP)

x402 SDKs include client/server helpers for MCP (Model Context Protocol) so AI agents can automatically parse 402, pay, and call your tools—no hardcoded API keys. Start by wrapping your MCP server with the x402 MCP adapter. (x402.gitbook.io)


Compliance and data residency

  • x402 is stateless and payment‑only; you don’t collect PII to accept a request.
  • If your industry requires restrictions, CDP’s roadmap includes optional attestations (KYC/geo) enforced at the facilitator; in the meantime, you can also gate by allowlists at the app layer. (docs.cdp.coinbase.com)

Launch checklist (7Block Labs implementation plan)

  • Select networks/assets:
    • Phase 1: Base + USDC (mainnet), optional Base Sepolia for staging. (docs.base.org)
    • Phase 2: Add Solana USDC for mobile‑wallet heavy users. (x402.gitbook.io)
  • Integrate middleware on the most valuable endpoints first; set price + timeout.
  • Wire facilitator /verify → /settle; store txHash + networkId from X‑PAYMENT‑RESPONSE. (github.com)
  • Add “discoverable: true” + short schemas to list in Bazaar (optional but recommended). (x402.gitbook.io)
  • Instrument metrics: 402 issued, verification latency, settlement success rate, revenue per route.
  • Run a game‑day: simulate invalid signatures, expired validBefore, insufficient funds, and network congestion.

7Block Labs can own the end‑to‑end: protocol integration, facilitator selection, token/chain configuration, observability, and a runway to dynamic billing schemes as they land in the spec.


Appendix: quick client snippets

  • Axios (auto 402 handling and paid retry):
import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
import axios from "axios";
import { privateKeyToAccount } from "viem/accounts";

const api = withPaymentInterceptor(axios.create({ baseURL: "https://api.example.com" }), privateKeyToAccount(process.env.PRIVATE_KEY!));

const res = await api.get("/v1/forecast?city=SF");
console.log(res.data);
console.log(decodeXPaymentResponse(res.headers["x-payment-response"]));
  • Fetch:
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
const fetchWithPayment = wrapFetchWithPayment(fetch, /* viem account */);

const res = await fetchWithPayment("https://api.example.com/v1/forecast?city=SF");
console.log(await res.json());
console.log(decodeXPaymentResponse(res.headers.get("x-payment-response")!));

Both flows implement the spec’d header formats and retries. (x402.gitbook.io)


Further reading / specs

  • x402 protocol (types, headers, /verify, /settle, X‑PAYMENT‑RESPONSE) and examples. (github.com)
  • Coinbase facilitator (networks, fee‑free USDC on Base, compliance posture). (docs.cdp.coinbase.com)
  • EIP‑3009 spec for transferWithAuthorization/receiveWithAuthorization; USDC’s EIP‑3009 implementation. (eips.ethereum.org)
  • Base chain IDs and USDC address references. (docs.base.org)
  • Bazaar discovery endpoint for agentic service search. (x402.gitbook.io)
  • L402/LSAT and Aperture for Lightning-based 402. (docs.lightning.engineering)

If you want a hand scoping the first paid route (from pricing to dashboards), 7Block Labs will blueprint and ship a production‑ready x402 integration in two weeks, then iterate toward dynamic schemes and multi‑network support.

Like what you're reading? Let's build together.

Get a free 30‑minute consultation with our engineering team.

Related Posts

7BlockLabs

Full-stack blockchain product studio: DeFi, dApps, audits, integrations.

7Block Labs is a trading name of JAYANTH TECHNOLOGIES LIMITED.

Registered in England and Wales (Company No. 16589283).

Registered Office address: Office 13536, 182-184 High Street North, East Ham, London, E6 2JA.

© 2025 7BlockLabs. All rights reserved.