AI & Blockchain
16 min read

x402 Protocol Explained:
How AI Agents Pay for APIs
with USDC in 2026

The protocol that turned an unused HTTP status code into the payment layer for the autonomous agent economy. No accounts. No API keys. Just USDC and a transaction hash.

35M+

Transactions

<2s

Settlement

2

Networks

USDC

Token

Every developer has seen it in textbooks but never in the wild: HTTP 402 Payment Required. Defined in 1999, reserved “for future use,” and ignored for a quarter century. In 2025, Coinbase dusted it off, attached a USDC payment rail, and shipped x402 — an open protocol that lets any HTTP client pay for any HTTP resource in a single round-trip. By early 2026, over 35 million x402 transactions have settled on Base and Solana, and the protocol is becoming the default way AI agents purchase API access, bandwidth, compute, and real-world services.

This guide covers everything you need to understand x402: the history behind HTTP 402, how the protocol works step by step, how it compares with Google's AP2, which blockchain networks to choose, and a full working example of buying mobile proxies from Proxies.sx using x402. Whether you are building an agent framework or adding payment acceptance to your API, you will walk away with code you can ship today.

Chapter 1

What is x402? (The HTTP 402 Revival)

HTTP 402 was included in the original HTTP/1.1 specification (RFC 2616, published in 1999) alongside familiar codes like 200 OK, 404 Not Found, and 401 Unauthorized. The authors anticipated a future where browsers would negotiate micro-payments natively, but no payment infrastructure existed to make that practical. The code sat dormant for 26 years.

The Original RFC Language

“This code is reserved for future use. The server requires payment before processing the request.”

RFC 2616, Section 10.4.3

In mid-2025, Coinbase recognized that stablecoins on fast L2 chains had finally created the missing ingredient: programmable, near-instant, near-free money that software can move without human involvement. They released x402 as an open-source protocol specification with reference implementations for Node.js, Python, Go, and Solidity.

The premise is elegantly simple. A server that wants payment for a resource returns HTTP 402 instead of 200. The response body contains machine-readable payment terms: how much, which token, which chain, and where to send it. The client (typically an AI agent) reads those terms, submits a USDC transfer on-chain, and replays the original request with a payment proof header. The server verifies the proof and returns the resource. The entire flow takes under 3 seconds on Base and under 1 second on Solana.

Why x402 Matters Now

  • AI agents are autonomous spenders that cannot fill out checkout forms or manage OAuth flows
  • USDC on L2s settles in seconds with sub-cent fees, making micropayments viable
  • HTTP is the universal transport: every API, every language, every framework already speaks it
  • No intermediaries: the payment goes directly from agent wallet to service provider
Chapter 2

x402 vs Google AP2: What's the Difference?

Two protocols are competing (and sometimes cooperating) to become the standard for agent payments. Understanding their philosophies helps you pick the right one — or use both.

x402 is blockchain-native and permissionless. Any server can return a 402 response; any client with a funded wallet can pay. There is no registration, no approval process, and no intermediary that can block a transaction. Coinbase and Cloudflare champion it as the open, neutral standard for the agent economy.

Google AP2 (Agent Payments Protocol) was introduced by Google alongside Visa, Mastercard, PayPal, and Stripe. It is designed for enterprise-grade agent commerce with “mandates” — human-approved spending policies that define what an agent can buy, from whom, and up to what limit. AP2 works across credit cards, bank transfers, and crypto.

Featurex402Google AP2
SettlementOn-chain (USDC)Cards, bank, crypto
RegistrationNone requiredMerchant enrollment
Speed<3 secondsVariable (rail-dependent)
Fees<$0.01 (L2 gas)~2.5% (card), varies
Spending ControlsWallet balance onlyMandate policies
Human ApprovalNot requiredMandate-based
Open SourceFully openSpec open, rails closed
Best ForAutonomous agentsEnterprise guardrails

Bottom Line

If you are building a fully autonomous agent that needs to buy resources without any human in the loop, x402 is the clear choice. If you are building within an enterprise that requires spending approvals, audit trails, and compliance with existing payment infrastructure, AP2 provides those guardrails. Many teams in 2026 use x402 for agent-to-agent transactions and AP2 for agent-on-behalf-of-human transactions.

Chapter 3

How x402 Payments Work (Step-by-Step)

From the first HTTP request to receiving the paid resource, the entire x402 flow takes five steps and under three seconds.

1

Agent sends a normal HTTP request

The AI agent makes a standard GET or POST request to the API endpoint. At this point, the agent does not know if payment is required.

http
GET /v1/proxy/create?country=US&type=4g HTTP/1.1
Host: api.proxies.sx
Accept: application/json
2

Server returns HTTP 402 with payment terms

The server recognizes the resource requires payment and responds with a 402 status. The response headers and body contain machine-readable payment terms.

http
HTTP/1.1 402 Payment Required
Content-Type: application/json
X-PAYMENT-NETWORK: base
X-PAYMENT-TOKEN: USDC
X-PAYMENT-ADDRESS: 0xF8cD900794245fc36CBE65be9afc23CDF5103042
X-PAYMENT-AMOUNT: 3500000
X-PAYMENT-DECIMALS: 6

{
  "error": "payment_required",
  "amount": "3.50",
  "currency": "USDC",
  "network": "base",
  "address": "0xF8cD900794245fc36CBE65be9afc23CDF5103042",
  "description": "1 GB mobile proxy bandwidth",
  "expires_in": 300
}
3

Agent signs and submits USDC transfer

The agent reads the payment terms, constructs a USDC transfer to the specified address for the quoted amount, signs it with its wallet key, and broadcasts the transaction.

javascript
// Agent-side: pay the 402 invoice
const tx = await usdcContract.transfer(
  "0xF8cD900794245fc36CBE65be9afc23CDF5103042",
  3500000n  // 3.50 USDC (6 decimals)
);
await tx.wait(); // ~2 seconds on Base
const txHash = tx.hash;
4

Agent retries the request with payment proof

The agent replays the original request, adding an X-PAYMENT-PROOF header containing the on-chain transaction hash.

http
GET /v1/proxy/create?country=US&type=4g HTTP/1.1
Host: api.proxies.sx
Accept: application/json
X-PAYMENT-PROOF: 0x8a7d...3f2e
X-PAYMENT-NETWORK: base
5

Server verifies payment, returns the resource

The server checks the transaction on-chain: correct recipient, correct amount, sufficient confirmations. If valid, it returns HTTP 200 with the requested resource.

json
HTTP/1.1 200 OK
Content-Type: application/json

{
  "status": "active",
  "proxy": {
    "host": "us-4g-7721.proxies.sx",
    "port": 5057,
    "username": "agent_x402_f3a1",
    "password": "kT9xMwP2qr",
    "protocol": "socks5",
    "country": "US",
    "type": "4g",
    "bandwidth_gb": 1
  },
  "payment": {
    "tx_hash": "0x8a7d...3f2e",
    "amount": "3.50",
    "currency": "USDC",
    "network": "base"
  }
}
Chapter 4

Payment Networks: Base vs Solana

x402 supports multiple chains, but two dominate production usage in 2026. Both use USDC as the settlement token.

Base (Ethereum L2)

By Coinbase

Finality~2 seconds
Tx Fee<$0.01
USDC ContractNative (Circle)
EcosystemEVM-compatible
Best ForEVM developers, Coinbase users

Proxies.sx Base Address

0xF8cD900794245fc36CBE65be9afc23CDF5103042

Solana

High-speed L1

Finality~400ms
Tx Fee<$0.001
USDC ContractNative (Circle)
EcosystemRust/Anchor
Best ForSpeed-critical, high-volume

Proxies.sx Solana Address

6eUdVwsPArTxwVqEARYGCh4S2qwW2zCs7jSEDRpxydnv

Which Network Should You Choose?

For most AI agent use cases, Base is the pragmatic default. It has the deepest USDC liquidity on any L2, direct Coinbase on-ramp support, and the Coinbase x402 SDK treats it as the primary chain. Choose Solana if sub-second settlement is critical to your workflow (e.g., high-frequency scraping agents that create hundreds of proxy sessions per minute) or if your agent already operates in the Solana ecosystem.

Both networks are production-ready and supported by Proxies.sx. You can switch between them by changing a single environment variable in your agent configuration.

Chapter 5

Real Implementation: Buying Mobile Proxies with x402

Here is a complete, working example of an AI agent purchasing a 4G mobile proxy from Proxies.sx using x402 on Base.

Full Agent Script (Node.js / TypeScript)

typescript
import { ethers } from "ethers";

const PROXIES_API = "https://api.proxies.sx/v1";
const BASE_RPC = "https://mainnet.base.org";
const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const AGENT_KEY = process.env.AGENT_WALLET_KEY!;

// ERC-20 ABI (only transfer)
const ERC20_ABI = [
  "function transfer(address to, uint256 amount) returns (bool)"
];

async function buyProxyWithX402() {
  // Step 1: Request a proxy resource
  const res = await fetch(
    `${PROXIES_API}/x402/proxy/create?country=US&type=4g`
  );

  if (res.status !== 402) {
    throw new Error(`Expected 402, got ${res.status}`);
  }

  // Step 2: Parse payment terms from 402 response
  const terms = await res.json();
  console.log("Payment required:", terms.amount, terms.currency);

  // Step 3: Execute USDC payment on Base
  const provider = new ethers.JsonRpcProvider(BASE_RPC);
  const wallet = new ethers.Wallet(AGENT_KEY, provider);
  const usdc = new ethers.Contract(USDC_BASE, ERC20_ABI, wallet);

  const amountRaw = ethers.parseUnits(terms.amount, 6);
  const tx = await usdc.transfer(terms.address, amountRaw);
  const receipt = await tx.wait();
  console.log("Payment tx:", receipt.hash);

  // Step 4: Retry with payment proof
  const proxyRes = await fetch(
    `${PROXIES_API}/x402/proxy/create?country=US&type=4g`,
    {
      headers: {
        "X-PAYMENT-PROOF": receipt.hash,
        "X-PAYMENT-NETWORK": "base",
      },
    }
  );

  // Step 5: Receive proxy credentials
  const proxy = await proxyRes.json();
  console.log("Proxy ready:", proxy);
  // {
  //   host: "us-4g-7721.proxies.sx",
  //   port: 5057,
  //   username: "agent_x402_f3a1",
  //   password: "kT9xMwP2qr",
  //   protocol: "socks5"
  // }

  return proxy;
}

buyProxyWithX402().catch(console.error);

Quick Test with curl (Step 1 Only)

You can inspect the 402 response from any terminal to see the payment terms before writing agent code:

bash
curl -i "https://api.proxies.sx/v1/x402/proxy/create?country=US&type=4g"

# HTTP/1.1 402 Payment Required
# X-PAYMENT-NETWORK: base
# X-PAYMENT-TOKEN: USDC
# X-PAYMENT-ADDRESS: 0xF8cD900794245fc36CBE65be9afc23CDF5103042
# X-PAYMENT-AMOUNT: 3500000
#
# {"error":"payment_required","amount":"3.50","currency":"USDC",...}

Even Easier: Use the MCP Server

If your agent runs inside Claude, Cursor, or any MCP-compatible client, you do not need to write payment code at all. The Proxies.sx MCP Server handles x402 negotiation automatically. Just say “Create a US 4G proxy” and the server handles everything.

json
// claude_desktop_config.json - x402 mode
{
  "mcpServers": {
    "proxies-sx": {
      "command": "npx",
      "args": ["-y", "@proxies-sx/mcp-server"],
      "env": {
        "AGENT_WALLET_KEY": "your-private-key",
        "NETWORK": "base"
      }
    }
  }
}
Chapter 6

Building Your Own x402-Enabled API

Adding x402 payment acceptance to any API takes about 50 lines of middleware. Here is a production-ready Express.js example.

x402 Middleware for Express.js

typescript
import express from "express";
import { ethers } from "ethers";

const app = express();
const BASE_RPC = "https://mainnet.base.org";
const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const MY_WALLET = "0xF8cD900794245fc36CBE65be9afc23CDF5103042";

// Minimal ERC-20 ABI for event parsing
const ERC20_ABI = [
  "event Transfer(address indexed from, address indexed to, uint256 value)"
];

// x402 middleware: protect any route with USDC payment
function requirePayment(amountUSDC: string, description: string) {
  return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const proof = req.headers["x-payment-proof"] as string;

    if (!proof) {
      // No payment proof: return 402 with terms
      res.status(402).json({
        error: "payment_required",
        amount: amountUSDC,
        currency: "USDC",
        network: "base",
        address: MY_WALLET,
        description,
        expires_in: 300,
      });
      return;
    }

    // Verify the payment on-chain
    try {
      const provider = new ethers.JsonRpcProvider(BASE_RPC);
      const receipt = await provider.getTransactionReceipt(proof);

      if (!receipt || receipt.status !== 1) {
        res.status(400).json({ error: "invalid_payment", message: "Transaction failed or not found" });
        return;
      }

      // Parse USDC Transfer event
      const iface = new ethers.Interface(ERC20_ABI);
      const transferLog = receipt.logs.find(log => {
        try {
          const parsed = iface.parseLog({ topics: [...log.topics], data: log.data });
          return parsed?.name === "Transfer"
            && parsed.args.to.toLowerCase() === MY_WALLET.toLowerCase()
            && log.address.toLowerCase() === USDC_BASE.toLowerCase();
        } catch { return false; }
      });

      if (!transferLog) {
        res.status(400).json({ error: "payment_not_found", message: "No USDC transfer to our address" });
        return;
      }

      const parsed = iface.parseLog({ topics: [...transferLog.topics], data: transferLog.data });
      const paidAmount = ethers.formatUnits(parsed!.args.value, 6);

      if (parseFloat(paidAmount) < parseFloat(amountUSDC)) {
        res.status(400).json({ error: "insufficient_payment", required: amountUSDC, received: paidAmount });
        return;
      }

      // Payment verified - proceed
      (req as any).payment = { txHash: proof, amount: paidAmount, from: parsed!.args.from };
      next();
    } catch (err) {
      res.status(500).json({ error: "verification_failed", message: "Could not verify payment" });
    }
  };
}

// Protected endpoint: $3.50 USDC for a proxy session
app.get("/v1/proxy/create",
  requirePayment("3.50", "1 GB mobile proxy bandwidth"),
  (req, res) => {
    const payment = (req as any).payment;
    res.json({
      status: "active",
      proxy: {
        host: "us-4g-7721.example.com",
        port: 5057,
        username: "agent_" + payment.txHash.slice(0, 8),
        password: generateSecurePassword(),
        protocol: "socks5",
      },
      payment: {
        tx_hash: payment.txHash,
        amount: payment.amount,
        currency: "USDC",
        network: "base",
      },
    });
  }
);

function generateSecurePassword(): string {
  return Math.random().toString(36).slice(2, 12);
}

app.listen(3000, () => console.log("x402-enabled API running on :3000"));

On-Chain Verification

Every payment is verified against actual blockchain state. No trust assumptions, no fake receipts.

No Key Management

You never hold agent keys. Agents sign their own transactions. You only verify the result.

Drop-in Middleware

Wrap any existing route with requirePayment() and it becomes x402-enabled immediately.

Chapter 7

x402 Adoption in 2026

From a reference spec to 35 million+ transactions in under a year, x402 adoption has been explosive.

35M+

Total Transactions

4,200+

APIs Accepting x402

$280M+

USDC Settled

12

SDK Languages

The growth is driven by several converging factors. Circle expanded native USDC to seven chains in 2025, ensuring deep stablecoin liquidity wherever agents operate. Coinbase integrated x402 into its Commerce API, giving any Coinbase merchant instant agent-payment acceptance. Cloudflare added x402 support at the CDN edge, meaning even static resources can be paywalled without backend changes.

On the agent side, the major frameworks — LangChain, CrewAI, AutoGPT, and Claude's MCP ecosystem — now ship x402 payment adapters out of the box. When an agent encounters a 402 response, it automatically checks its wallet balance, evaluates whether the price fits its budget constraints, and pays. The entire decision loop is well-documented and takes a fraction of a second.

Notable Adopters

Coinbase Commerce

Native x402 acceptance for all merchants

Cloudflare Workers

Edge-level 402 payment gates

Replicate

Pay-per-inference for ML models

Proxies.sx

Mobile proxy bandwidth and ports

Firecrawl

Web scraping credits via x402

SERP APIs

Search engine result pages per query

The trajectory is clear: by the end of 2026, any API that wants to serve autonomous agents will need either x402, AP2, or both. The cost of adoption is minimal (a middleware layer), and the upside — accessing a market of millions of AI agents with budgets — is substantial. For API providers, the question is no longer “should we support agent payments?” but “how quickly can we ship it?”

FAQ

Frequently Asked Questions

Q1What is the x402 protocol?

x402 is an open protocol that repurposes HTTP status code 402 (Payment Required) for machine-to-machine payments. When an AI agent requests a paid resource, the server returns a 402 response with payment terms (price, token, chain, address). The agent pays with USDC on Base or Solana, then retries the request with an on-chain transaction hash as proof. The server verifies the payment and grants access. The entire round-trip takes under 3 seconds.

Q2How does x402 differ from Google AP2?

x402 is blockchain-native, permissionless, and settles payments on-chain with USDC. Google AP2 is a broader framework that supports credit cards, bank transfers, and crypto, with "mandate" policies for human-approved spending limits. x402 is best for fully autonomous agents; AP2 is better for enterprise environments where spending controls and compliance trails are required. Many teams use both protocols for different use cases.

Q3Which blockchains does x402 support?

The two primary production networks are Base (Ethereum L2 by Coinbase) with ~2-second finality and sub-cent fees, and Solana with ~400ms finality and even lower fees. Both use USDC as the settlement token. The protocol specification is chain-agnostic, and implementations for Arbitrum, Optimism, and Polygon also exist.

Q4Do AI agents need accounts or API keys to use x402?

No. That is the core innovation. An agent only needs a crypto wallet funded with USDC. It discovers the price from the 402 response, pays on-chain, and presents the transaction hash as proof. No registration, no API keys, no OAuth flows, no human checkout. The wallet IS the identity.

Q5How much do x402 transaction fees cost?

On Base, network fees (gas) are typically under $0.01 per transaction. On Solana, fees are fractions of a cent. The actual cost of the API resource is set by the server, not the protocol. There are no protocol-level fees, intermediary cuts, or percentage takes. The payment goes directly from the agent wallet to the service provider wallet.

Q6Can I add x402 acceptance to my existing API?

Yes. The typical approach is a middleware layer that returns 402 for protected routes when no payment proof is present, and verifies the on-chain transaction when a proof header is provided. Reference implementations exist for Node.js, Python, Go, Ruby, and Rust. For Cloudflare Workers, a single Wasm plugin handles it at the edge.

Q7Is x402 secure against double-spending or replay attacks?

x402 payments settle on-chain, giving both parties a cryptographically verifiable receipt. Servers verify the payment proof against actual blockchain state (correct recipient, correct amount, sufficient confirmations) before granting access. Each transaction hash is unique and can only be used once. Replay protection is inherent in the blockchain consensus mechanism.

Q8How does Proxies.sx use x402?

Proxies.sx accepts x402 payments for mobile proxy bandwidth ($3.50/GB) and port rentals ($18-40/month). AI agents request proxy resources, receive a 402 with the USDC price, pay on Base or Solana, and instantly receive SOCKS5/HTTP proxy credentials. No account registration required. The MCP Server also supports x402, so Claude and Cursor users get automatic payment handling through natural language commands.

Ready to Accept x402 Payments?

Proxies.sx is live with x402 on Base and Solana. Start buying mobile proxy bandwidth with USDC — no account required.

PROXIES.SX Team

Building AI-native proxy infrastructure