x402 lets AI agents pay for API access directly over HTTP. Instead of creating accounts, storing API keys, or waiting for invoices, an agent requests a paid endpoint, receives an HTTP 402 Payment Required response with payment details, pays in stablecoins such as USDC, then retries with proof of payment. The server verifies the payment and returns the resource. For API providers, x402 adds per-request monetization without subscription plumbing. For agents, it removes signup friction and enables autonomous tool use. This guide covers the full integration from both the server and agent perspective, including code examples, spending controls, and framework compatibility.
HTTP status code 402 has been reserved in the HTTP spec since 1999 with the note "reserved for future use." Coinbase built x402 to finally give it a standard implementation — a protocol that lets any HTTP server require payment for any resource and lets any HTTP client (including AI agents) pay automatically.
The protocol sits at the HTTP layer, which means it works with any API regardless of what the API does under the hood. A data provider, a compute service, a generation endpoint — if it speaks HTTP, it can use x402. The payment itself settles in USDC on Base (Coinbase's L2) or Solana, both of which offer sub-second finality and gas costs well under a cent.
As of early 2026, x402 has processed over $600 million in transaction volume. Google, AWS, Stripe, Anthropic, and Cloudflare have integrated it. This is production infrastructure, not a spec draft sitting in a GitHub issue.
The payment cycle follows standard HTTP request/response semantics. There is no separate payment API, no webhook callback, and no out-of-band settlement. The payment happens inline with the API call itself.
Step 1: The AI agent makes a standard HTTP request. Nothing special on the first attempt.
Step 2: The server responds with HTTP 402 and a PAYMENT-REQUIRED header containing Base64-encoded JSON. This JSON includes an accepts array with one or more payment options — each specifying the scheme (exact for fixed price, upto for maximum-price auctions), price, settlement network (using CAIP-2 identifiers like eip155:8453 for Base), and the recipient address.
Step 3: The agent decodes the payment requirements, selects a payment option, and signs an off-chain USDC authorization (EIP-3009 or Permit2). This is important: the agent does not submit a blockchain transaction directly and does not need native gas tokens (ETH or SOL). It only signs an authorization that the Facilitator will submit on its behalf.
Step 4: The agent retries the same request with a PAYMENT-SIGNATURE header containing the Base64-encoded signed payment payload (including x402Version: 2, the scheme, network, and cryptographic signature).
Step 5: The server passes the signed payload to a Facilitator (a verification and settlement service, typically Coinbase CDP, Cloudflare, or self-hosted). The Facilitator verifies the signature, submits the transaction on-chain, and confirms settlement. The server returns 200 OK with the data and a PAYMENT-RESPONSE header containing the settlement result. USDC arrives in the provider's wallet immediately.
The whole round trip typically finishes in under three seconds. Each API call is a self-contained economic transaction, which is fundamentally different from subscription tiers, OAuth flows, or end-of-month invoice reconciliation.
On the server side, x402 is implemented as middleware that intercepts requests to protected endpoints. If a request arrives without a valid payment proof, the middleware returns 402 with payment instructions. If a valid proof is present, it passes the request through to the handler.
// Express middleware for x402 V2 payment gating import { paymentMiddleware } from '@coinbase/x402-server'; // Define which routes require payment (V2 format) const payRoutes = { 'GET /api/premium-data': { accepts: [{ scheme: 'exact', price: '$0.05', network: 'eip155:8453', // Base mainnet (CAIP-2) payTo: process.env.WALLET_ADDRESS, }], }, }; app.use(paymentMiddleware({ routes: payRoutes, facilitator: 'https://x402.coinbase.com/facilitator', })); // Discovery endpoints stay free (no route config = no gate) app.get('/api/catalog', (req, res) => { res.json({ endpoints: listAvailableEndpoints() }); });
The same pattern in Python with FastAPI:
# FastAPI middleware for x402 V2 payment gating import json, base64 from fastapi import FastAPI, Request, Response from x402.facilitator import verify_payment app = FastAPI() FACILITATOR = "https://x402.coinbase.com/facilitator" def encode_payment_required(price, network, pay_to): payload = {"accepts": [{ "scheme": "exact", "price": price, "network": network, "payTo": pay_to, }]} return base64.b64encode(json.dumps(payload).encode()).decode() @app.middleware("http") async def x402_gate(request: Request, call_next): if request.url.path.startswith("/api/catalog"): return await call_next(request) signature = request.headers.get("PAYMENT-SIGNATURE") if not signature or not await verify_payment(signature, FACILITATOR): return Response( status_code=402, headers={"PAYMENT-REQUIRED": encode_payment_required( "$0.05", "eip155:8453", WALLET_ADDRESS )} ) return await call_next(request)
The key architectural decision here is which endpoints to gate. Gating everything on day one is a common mistake — agents in test environments typically do not carry funded wallets, and they will simply leave if every endpoint demands payment before they can even understand what you offer. The pattern that works: keep discovery, metadata, and health-check endpoints free. Gate data retrieval, computation, and generation.
This is the part most documentation skips. The x402.org and Coinbase docs explain the server side well, but the agent side — how an autonomous AI agent safely holds funds, decides whether to pay, and avoids draining its wallet in a bad loop — is largely undocumented.
An x402-capable agent needs three things: a funded wallet it can sign transactions with, logic to intercept HTTP 402 responses and decide whether to pay, and spending controls to prevent runaway costs.
// Agent-side x402 V2 handler with spending limits import { signPayment } from '@coinbase/x402-client'; interface SpendingPolicy { maxPerCall: number; // max USDC per single API call maxDaily: number; // daily budget cap allowedDomains: string[]; // only pay these hosts } const policy: SpendingPolicy = { maxPerCall: 1.00, maxDaily: 50.00, allowedDomains: ['data-api.example.com'], }; let dailySpend = 0; async function x402Fetch(url: string, init?: RequestInit) { const res = await fetch(url, init); if (res.status !== 402) return res; // Decode PAYMENT-REQUIRED header (Base64 JSON) const b64 = res.headers.get('PAYMENT-REQUIRED'); if (!b64) throw new Error('402 without PAYMENT-REQUIRED header'); const requirements = JSON.parse(atob(b64)); const option = requirements.accepts[0]; const amount = parseFloat(option.price.replace('$', '')); // Enforce spending policy const host = new URL(url).hostname; if (!policy.allowedDomains.includes(host)) throw new Error(`Refused: ${host} not in allowlist`); if (amount > policy.maxPerCall) throw new Error(`Refused: $${amount} exceeds per-call limit`); if (dailySpend + amount > policy.maxDaily) throw new Error(`Refused: daily budget exhausted`); // Sign off-chain authorization (no gas needed) const signature = await signPayment({ x402Version: 2, scheme: option.scheme, network: option.network, payTo: option.payTo, amount: option.price, }); dailySpend += amount; // Retry with PAYMENT-SIGNATURE header return fetch(url, { ...init, headers: { ...init?.headers, 'PAYMENT-SIGNATURE': signature }, }); }
The SpendingPolicy is the critical piece that prevents an agent from spending $10,000 overnight. Without it, a retry loop against a paid endpoint will drain the wallet at machine speed. The policy enforces three constraints: a maximum price per individual call (so the agent refuses unexpectedly expensive endpoints), a daily budget cap (so total spend is bounded regardless of call volume), and a domain allowlist (so the agent only pays known, trusted API providers).
A key detail: the agent signs an off-chain authorization (EIP-3009 or Permit2), not an on-chain transaction. The Facilitator submits the actual blockchain transaction on the agent's behalf. This means the agent does not need native gas tokens (ETH for Base, SOL for Solana) — it only needs a USDC balance. This is a major UX simplification: you fund the agent's wallet with USDC and nothing else.
Where does the agent store its private key? In production, the wallet key should live in a secure enclave, HSM, or secrets manager — not in environment variables or hardcoded in source. Coinbase AgentKit provides managed wallet infrastructure specifically for this use case, handling key storage and transaction signing without exposing the raw key to the agent process.
Giving an AI agent a funded wallet and access to paid APIs creates a new class of operational risk that most teams underestimate. The agent does not understand money. It understands that calling the API gets it data it needs to complete a task, and it will call the API as many times as it needs to, as fast as it can.
These controls should live in a governance layer between the agent and the network, not inside the agent's own code. The agent should not be able to modify its own spending limits any more than an employee should be able to raise their own expense limit.
x402 support varies significantly across AI agent frameworks. Some handle it natively, others require custom integration work.
| Framework | x402 Support | Integration Approach |
|---|---|---|
| Coinbase AgentKit | Native | Built-in wallet + x402 payment handling |
| Cloudflare Agents | Native | Workers-based x402 middleware, both server and client |
| MCP (Model Context Protocol) | Via tool server | Build an MCP tool that wraps x402Fetch; works with Claude, GPT, etc. |
| LangChain / LangGraph | Custom tool | Wrap x402Fetch as a LangChain Tool with spending policy |
| AutoGen | Custom tool | Register x402Fetch as a callable function for agents |
| CrewAI | Custom tool | Create a CrewAI Tool class wrapping the x402 client |
| OpenAI Agents SDK | Custom tool | Define as a function tool with payment parameters |
For frameworks that require custom integration, the pattern is the same: wrap the x402Fetch function (or equivalent) as a tool that the agent can call, and enforce spending policies at the tool level rather than relying on the agent to self-regulate.
| Network | Finality | Gas Cost | Stablecoin | Notes |
|---|---|---|---|---|
| Base (Mainnet) | ~2 seconds | ~$0.001 | USDC | Default for Coinbase ecosystem. Highest x402 adoption. |
| Base (Sepolia) | ~2 seconds | Free | Test USDC | Testnet. Use for development and staging. |
| Solana | ~400ms | ~$0.00025 | USDC | Fastest finality. Growing x402 adoption. |
| Polygon | ~2 seconds | ~$0.001 | USDC | Supported via Polygon x402 integration. |
| Algorand | ~3 seconds | ~$0.001 | USDC | Newer x402 support. |
For most new integrations, Base is the practical default — it has the widest x402 ecosystem support, Coinbase provides the primary facilitator infrastructure, and the gas costs are negligible. Solana is worth considering if sub-second finality matters for your use case (high-frequency trading data feeds, for example) or if your agents already operate in the Solana ecosystem.
| Approach | Access Granted Via | Works for Autonomous Agents | Per-Request Billing | Requires Account |
|---|---|---|---|---|
| x402 | HTTP 402 + USDC payment | Yes, natively | Yes | No |
| API Keys | Static token in header | Partially (key must be provisioned manually) | Depends on provider | Yes |
| OAuth 2.0 | Token exchange flow | Complex (requires consent, refresh tokens) | No | Yes |
| Subscription billing | Stripe/Paddle plan | No (requires human signup + payment method) | No (flat monthly) | Yes |
| Prepaid credits | Credit balance + API key | Partially (balance must be topped up manually) | Yes | Yes |
The fundamental difference is that x402 requires no pre-existing relationship between the agent and the API provider. The agent does not need to sign up, store a key, or maintain a billing account. It just pays per call and gets data back. For autonomous agents that need to discover and use APIs on their own, this removes the single biggest friction point: the human-operated account creation step that every other approach requires.
| Protocol | Backed by | Payment Model | Best For |
|---|---|---|---|
| x402 | Coinbase | HTTP-native, per-call, USDC | API monetization, simple per-request billing |
| ACP | Stripe + OpenAI | Negotiation-based, supports subscriptions | Complex pricing, recurring agent relationships |
| AP2 | Agent-to-agent, multi-step workflows | Orchestration chains, delegated tasks |
For straightforward API monetization — where agents pay per call for data, computation, or generation — x402 is the simplest starting point. It maps directly to HTTP semantics that every developer already understands, and the integration surface is minimal (one middleware on the server, one fetch wrapper on the client).
ACP adds a negotiation layer on top, which is useful when you need dynamic pricing, volume discounts, or recurring billing relationships between agents and providers. If your pricing model is more complex than "this endpoint costs $X per call," ACP may be worth evaluating — but it adds significant complexity and most teams do not need it at launch.
AP2 solves a different problem: agent-to-agent task delegation, where one agent hires another agent to complete a sub-task. Unless you are building an agent marketplace or multi-agent orchestration platform, AP2 is not relevant to API monetization.
Describe your setup and what you are trying to connect. We will send back a written assessment covering architecture, risk surface, and whether x402 fits your use case. No calls, no pitch decks, no obligation.
Request an Assessment