7Block Labs
Blockchain Technology

ByAUJay

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

Short Summary

x402 brings HTTP 402 back to life with a practical, open protocol that allows your APIs to price each request and get paid in stablecoins--no accounts or API keys needed! In this post, we’ll dive into how it operates, why USDC on Base is the go-to choice, and how you can launch it in production today, complete with real-world examples and some best practices you should consider.

Why this matters now

HTTP 402, or “Payment Required,” was originally set aside for a future where machines could handle payments for resources. Well, that future is now a reality! The x402 protocol lays out a clear way for servers to send a 402 challenge, how clients can make their payments, and how to verify those transactions. This means you can sell any endpoint for anywhere between $0.001 and $1.00, all automatically and in real-time, using stablecoins. Check it out here: (developer.mozilla.org)


What is x402 (and what it isn’t)

  • x402 is a payments protocol that plays nicely with HTTP:

    • When the server sends back a 402 status, it includes machine-readable “payment requirements.”
    • The client then signs a payment payload and resubmits the same HTTP request, adding an X-PAYMENT header.
    • The server checks everything and settles the transaction (either locally or through a facilitator), and then responds with a 200 status and your usual JSON. (github.com)
  • It’s pretty flexible and works with various assets and chains, but the go-to option right now is USDC, which uses EIP‑3009 signatures on Base (and SPL on Solana). (docs.cdp.coinbase.com)
  • And just to clarify, it’s not a custodial gateway. The facilitator’s role is to verify and broadcast the transaction on-chain; it can't move any funds without the buyer’s okay. (docs.cdp.coinbase.com)

x402 stands out from Lightning’s L402/LSAT, which uses macaroons along with Lightning invoices. If you're looking for features like dollar-denominated pricing, top-notch KYT/OFAC screening, and on-chain settlement, then x402 is where you want to be. But if you'd rather stick with sats and prioritize Lightning-first authentication, then check out L402 + Aperture. You can dive deeper into the details here: (docs.lightning.engineering).


How the 402 → pay → retry handshake works

  1. The client hits up your API.
  2. Your server responds with a 402 status, throwing in some JSON that lays out the payment requirements (like price, asset, payTo, network, and timeout).
  3. The client whips up a signed payment payload and gives it another go with X-PAYMENT.
  4. The server checks things out and settles the payment (usually with a facilitator involved).
  5. Finally, the server sends back a 200 status, including an X-PAYMENT-RESPONSE packed with settlement details (like tx hash and network) (github.com).

From a visual and technical standpoint, this whole process boils down to a single HTTP roundtrip involving one 402 “challenge” followed by one paid retry.


The 402 response: a concrete, production-ready example

For USDC on the Base mainnet (chainId 8453; USDC address 0x833589…2913), your server can send transactions here: (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 included in the open x402 spec (v1). When you see “scheme: exact,” it means the client has to pay exactly the maxAmountRequired in the specified asset and network. Check it out on GitHub!


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

On EVM networks, x402 leverages EIP‑712 typed data to handle USDC transfers using EIP‑3009’s transferWithAuthorization/receiveWithAuthorization. This allows for signature-only transfers that don't require any gas fees, so the facilitator can easily broadcast them without needing prior approval or native ETH from the buyer. You can learn more about it here.

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

The decoded JSON looks like this:

{
  "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 method that USDC v2 uses to allow for transfers through just signatures. Check it out here: (eips.ethereum.org).
  • If you’re looking for USDC on the Base mainnet, you can find it at 0x833589…2913 (it’s got 6 decimals). For more details, head over to (developers.circle.com).

On success, servers might include:

X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0eEhhc2giOiIweGFiaWMiLCJuZXR3b3JrSWQiOiI4NDUzIn0=

Where do txHash and networkId come from in facilitator settlement?

You can dive into the details over at the GitHub repository.


Solana variant (SPL USDC) in x402

On Solana, x402’s “exact” scheme works by using a partially-signed SPL transfer transaction (that’s base64-encoded) in the payload. The facilitator simply adds the fee payer’s signature and sends it out. So, you still follow the 402 → X-PAYMENT path, but with a Solana transaction instead of EIP‑712. Check it out here: (x402.gitbook.io).

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

Most facilitators usually accept USDC (SPL) as well as other SPL/Token‑2022 tokens. You'll find that the response and verification look pretty similar to what you'd expect with EVM. For more details, check out this link: x402.gitbook.io.


Why USDC on Base is the default for enterprises

  • You can count on predictable, dollar-denominated pricing with USDC, thanks to EIP-3009, which makes one-shot, gas-abstracted transfers a breeze. Check it out here: (eips.ethereum.org).
  • If you're using Coinbase, their hosted facilitator (CDP) lets you enjoy fee-free USDC settlements on the Base mainnet. Plus, they handle KYT/OFAC checks and SLAs, making it super easy to get started. More details here: (docs.cdp.coinbase.com).
  • When it comes to Base chain IDs, you've got 8453 for the mainnet and 84532 for Sepolia. Both are well-supported in the infrastructure and tooling world, and you can find the official USDC contract address published by Circle. Dive into the info here: (docs.base.org).

Note: If you're looking for non-USDC assets, keep in mind that facilitators and SDKs are branching out beyond EIP-3009 (you'll see things like EIP-2612 “permit” and Permit2 popping up). But for now, USDC is definitely the easiest way to go. (github.com)


Shipping x402 in your stack (Node and Python)

Adding a Payment Middleware

To get started with integrating a payment middleware, we'll need to:

  1. Identify Paid Routes: Let's outline which routes will require payment.
  2. Point to a Payment Facilitator: We'll also need to connect to a payment facilitator to handle transactions.

Step 1: List of Paid Routes

Here's a quick rundown of the routes that will need a payment attached to them:

  • /premium-content
  • /exclusive-offers
  • /subscriptions
  • /donations

Step 2: Payment Facilitator

For handling payments smoothly, we can use a reliable payment facilitator. Some popular options include:

  • Stripe: Great for flexible integrations and easy API usage.
  • PayPal: Widely recognized, providing a familiar interface for users.
  • Square: Good for in-person and online transactions alike.

Choosing the Right One

When picking a facilitator, consider factors like fees, ease of integration, and support for different payment methods. Based on your needs, you might want to try out a couple to see which fits best.

By following these steps, you can effectively set up your payment middleware and keep your transactions secure and seamless!

  • 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 align perfectly with the official Quickstarts and cover all the header, base64, and facilitator logic you need. Check it out here: (x402.gitbook.io)


Verification and settlement: you choose the trust boundary

  • Local verify/settle: Set up your own chain connections and check those signatures right on your infrastructure.
  • Facilitator verify/settle (recommended): Make a call to /verify, then follow it up with /settle on a facilitator. You'll receive an isValid response and a txHash. Finally, send a 200 status back to the client along with X-PAYMENT-RESPONSE. (github.com)

CDP’s facilitator setup includes Base and Solana (along with testnets), plus fee-free USDC settlement on Base. You’ll find API key scoping there too. On top of that, there are community and self-hosted facilitators available across Base, Solana, Polygon, Avalanche, and a bunch of other networks. Check it out here: (docs.cdp.coinbase.com)


Discovery: get found by AI agents (x402 Bazaar)

When you set discoverable: true in your route configuration, CDP’s facilitator will make your endpoint available in the x402 Bazaar. This way, buyers and agents can easily find and call it via their programs. If you want to check out all the discoverable services, just hit this endpoint:

GET https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources

You can find more details at (x402.gitbook.io).


Pricing and metering patterns we see working

  • Pricing kicks off at around $0.001 to $0.01 per call, but you might want to bump that up for GPU/LLM use or if you're dealing with large data sets. Just a heads-up, the spec breaks down pricing into atomic units (since USDC has 6 decimal points, 1 USDC equals 1,000,000 units). Check it out on GitHub.
  • Set your maxTimeoutSeconds between 60 and 120. This way, signatures can get through smoothly, and you keep the request nice and warm. More details are available here.
  • Stick to one path for each SKU, like /v1/forecast for the budget-friendly option, /v1/history for mid-range, and /v1/forecast/pro for the premium stuff.
  • Make sure to return the mimeType along with a quick description. This helps agents pick the right route without any hassle.
  • Don’t forget to add an outputSchema! This will give agents a clear idea of what to expect, but keep it simple to minimize friction. You can find more info here.

Roadmap to Dynamic Billing

x402 is laying out the schemes, and guess what? “exact” is launching today! Meanwhile, we’ve got “upto/stream/permit2” in the works, which are all about enabling token-based streaming or setting “up to X” limits for LLM tokens or bandwidth. Keep an eye on those public PRs and issues if you want to get in on the action early. Check it out here: github.com


Security, compliance, and ops checklists

  • EIP‑712 Correctness: Make sure that the chainId, verifyingContract, and token name/version match up with your USDC (or any custom token you’ve got). If you're working in the EVM, just call the token’s name() and version() (for USDC: it’s “USD Coin” and version “2”). You can find more details here.
  • Nonce/TTL: Set a validBefore time of about 60 seconds and throw in a random 32-byte nonce to keep things secure; this way, you can reject replay attacks and late issues. Check out more on this here.
  • KYT/OFAC: Use a facilitator to screen transactions--CDP does this on Base, so you can feel a bit more at ease. Learn more here.
  • Reconciliation: Don't forget to decode the X-PAYMENT-RESPONSE (think txHash, networkId) and stash it alongside your request ID. Also, if your backend isn’t idempotent, be sure to send idempotency keys in the resource URL. More info can be found here.
  • Observability: Make sure to log those 402s along with the accepts[0] fields. Also, keep track of verify and settle durations, and if any payment doesn’t go through, log the invalidReason.
  • Token Choice Caveats: Keep in mind that USDC implements EIP‑3009, but some bridged tokens (like the legacy Polygon USDC.e) aren't exactly 1:1 compatible with EIP‑3009. Double-check that your specific contract supports transferWithAuthorization on the target chain. Dive deeper here.

Example: metering a GPU inference endpoint

  1. Protect your call to /v1/infer on Base for just $0.003: price: "$0.003", network: "base".
  2. When the client accesses /v1/infer, they get a 402 response along with accepts[0].
  3. The client’s SDK (either x402-axios or x402-fetch) automatically picks up that 402, creates the EIP-712 payload, signs it, retries with X-PAYMENT, and then grabs the txHash from the X-PAYMENT-RESPONSE.
  4. You’ll get the inference JSON back right away after everything’s verified; meanwhile, the facilitator takes care of settling onchain in the background and sends back the txHash (which takes about seconds on Base). (x402.gitbook.io)

Stablecoins vs. Lightning: quick decision matrix

  • Go for x402 if you're looking for:

    • USD pricing that uses stablecoins
    • Solid enterprise compliance (think KYT/OFAC)
    • Easy HTTP-native integration with EIP‑712/EIP‑3009 semantics
    • Discovery options for agent ecosystems (Bazaar)
  • Pick L402 (Aperture) if you want:

    • Sats-first micropayments using Lightning
    • Macaroon-based authentication (with attenuation/delegation)
    • A reverse proxy that handles pricing and challenges for you (github.com)

Both models rely on HTTP 402, but they each take a different approach and use distinct authentication methods.


Emerging best practices (late‑2025)

  • Make your endpoints discoverable: The x402 Bazaar is basically your go-to spot for agents on the lookout for pay‑per‑use capabilities. Just make sure to include a clear description along with the input/output schema. Check it out here: (x402.gitbook.io).
  • Go with Base+USDC for the first launch: This combo has the lowest integration risk, no fees for settling through CDP, plus a bunch of solid tools to work with. More info can be found here: (docs.cdp.coinbase.com).
  • Consider offering a Solana SKU for high‑throughput or mobile wallets: You can use the same server code; just switch out the network and asset as needed. Dive deeper into this here: (x402.gitbook.io).
  • Adopt permit/Permit2 once the SDKs settle down: This will help you expand token coverage beyond EIP‑3009. For more details, head to this link: (github.com).
  • Add a 402 cache: If you've got multiple callers hitting the same resource back-to-back, caching the accepts object for a minute can really ease the load on the facilitator.

Implementation pitfalls we see (and how to avoid them)

  • If you're seeing the "invalid_exact_evm_payload_signature" error, it's likely due to a mismatch in the domain data for EIP‑712 (specifically, the name and version don't match). To fix this, grab the name() and version() straight from the token contract--like for USDC, you'll find the name as “USD Coin” and the version as “2.” Check it out here: (github.com).
  • Watch out for using testnet network strings on the mainnet. For instance, don’t mix up "base-sepolia" with just "base." Always double-check your chain and USDC balance to avoid this issue. More details are here: (docs.cdp.coinbase.com).
  • Don’t assume the buyer has gas! EIP‑3009 is designed to be gas-abstracted, meaning the facilitator covers the gas fees. But you still need to choose a network where EIP‑3009 operates correctly. For more info, you can read this: (eips.ethereum.org).
  • When dealing with Polygon USDC.e, keep in mind that it’s not fully compatible with EIP‑3009. It's a good idea to test the functions of your target token before you list it in accepts[]. You can find more on this topic here: (web3-ethereum-defi.readthedocs.io).

Procurement guide: facilitator options

  • CDP (Coinbase): If you're looking for something robust, check out the Base/Solana mainnets with fee-free USDC settlement on Base. It’s got KYT/OFAC compliance and SLAs, but you'll need API keys to get started. This one's really geared towards enterprises. (docs.cdp.coinbase.com)
  • Community facilitators: Perfect for quick prototyping! They offer wide network coverage over platforms like Base, Solana, Polygon, and Avalanche. Just make sure to validate the reliability and token support before diving in. (x402.gitbook.io)
  • Self-hosted: Want complete control? You can add your own EVM chains by just providing the chainId, USDC address, and viem chain config. It’s all yours! (x402.gitbook.io)

Add agents to the party (MCP)

x402 SDKs come with handy client/server helpers for MCP (Model Context Protocol). This makes it super easy for AI agents to parse 402, handle payments, and call on your tools--all without the hassle of hardcoded API keys. To get started, just wrap your MCP server with the x402 MCP adapter. Check out the details here: (x402.gitbook.io).


Compliance and data residency

  • The x402 protocol is all about being stateless and focusing solely on payments; you won’t need to gather any personal information to process a request.
  • If your sector has specific regulations, don’t worry--CDP has plans for optional attestations (like KYC or geo-restrictions) that will be enforced at the facilitator level. For now, you can manage access by setting up allowlists right at the app layer. Check out the details here.

Launch checklist (7Block Labs implementation plan)

  • Select networks/assets:

    • Phase 1: Start off with Base + USDC on the mainnet, and you can optionally use Base Sepolia for staging. Check out the details here.
    • Phase 2: Introduce Solana USDC for those heavy mobile-wallet users. More info can be found here.
  • Integrate middleware on the most valuable endpoints first. Don't forget to set a price and a timeout!
  • Wire up the facilitator so it connects /verify to /settle. Make sure to store the txHash and networkId from the X‑PAYMENT‑RESPONSE. You can refer to the code here.
  • Add "discoverable: true" and some short schemas to enable listing in the Bazaar. This step is optional but definitely recommended! Dive into more details here.
  • Keep an eye on the metrics: Track 402 issued, verification latency, settlement success rate, and revenue per route.
  • Run a game day: Time to simulate some issues like invalid signatures, expired validBefore timestamps, insufficient funds, and network congestion.

7Block Labs can handle everything from start to finish: integrating protocols, choosing facilitators, setting up token and chain configurations, ensuring observability, and paving the way for dynamic billing schemes as they roll out in the spec.


Appendix: quick client snippets

  • Axios (automatic handling of 402 errors and retry for paid requests):
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 follow the specified header formats and handle retries. Check it out here!


Further reading / specs

  • x402 Protocol: Check out the types, headers, and endpoints like /verify, /settle, and X-PAYMENT-RESPONSE. Here’s a helpful link to GitHub for some solid examples.
  • Coinbase Facilitator: Learn about networks, enjoy fee-free USDC on Base, and get the lowdown on their compliance stance over at Coinbase Docs.
  • EIP-3009 Spec: This deals with transferWithAuthorization and receiveWithAuthorization. Plus, don’t miss out on USDC’s implementation of EIP-3009. You can dive deeper here.
  • Base Chain IDs and USDC Addresses: If you need references for chain IDs and USDC addresses, check out this neat guide on Base Docs.
  • Bazaar Discovery Endpoint: This is your go-to for searching agentic services. Get all the details on the Bazaar Discovery Layer.
  • L402/LSAT and Aperture: Want to understand Lightning-based 402? Head over to Lightning Engineering for more info.

If you're looking for some help to figure out the first paid route--from pricing to dashboards--7Block Labs has got you covered! They'll create and deliver a production-ready x402 integration in just two weeks. After that, they'll keep working to refine it for dynamic schemes and support across multiple networks.

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

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

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.

© 2026 7BlockLabs. All rights reserved.