Build a Pay-Per-Call API That Charges AI Agents in USDC (x402 Build Log)

Three independent platforms shipped agent-to-agent payment rails in August: AWS GA’d Bedrock AgentCore Payments with x402 “under the hood” (CryptoTimes), Binance launched Agent OS with “Binance x402” rails (TechCrunch), and Zerion integrated AgentCash for ~$0.01 USDC/call billing (CryptoBriefing). If you run an API that serves AI agents, “sell to agents over HTTP 402” is a clear near-term monetization path — yet few public posts walk the full implementation. This build log does.

How This Guide Was Built This build guide is based on official documentation, published source code, and community reports — we did not run the stack hands-on. Every code snippet references the official x402 SDK, Coinbase Developer Platform quickstarts, or Zerion’s published developer docs. All 16 primary sources were verified HTTP 200 on 2026-09-03. Inline citations link to primary sources throughout.

The worked example mirrors how Zerion monetizes its wallet-data API: a paywalled endpoint that returns normalized on-chain wallet data for $0.01 USDC per call — no API keys, no signup, no subscription. Agents discover the endpoint, pay automatically over plain HTTP, and get their data.


Why Now: Three August 2026 Adoptions Prove Agent-to-Agent Payments Are Live

Between August 18 and 28, 2026, three independent x402 adoptions landed that make agent-to-agent payments a buildable opportunity today. AWS made Bedrock AgentCore Payments generally available on Aug 18, with the flow “built around the x402 protocol” and wallets from Coinbase or Stripe Privy (AWS ML blog). Binance launched Agent OS on Aug 20, bundling Binance APIs, Wallet Agentic Hub, and Binance x402 as core components (CryptoTimes). And on Aug 28, Zerion’s API integrated AgentCash, letting agents query on-chain data across 38+ chains at ~$0.01 USDC per call with no API key (CryptoBriefing).

Coinbase had already laid the groundwork: Coinbase Business began accepting USDC directly from AI agents via x402 in July 2026, noting agent traffic recently surpassed human traffic on Base docs (news.bitcoin.com). The infrastructure is live. What’s missing is merchant supply — which is exactly what this build log addresses.


How x402 Works: The HTTP 402 Handshake, Headers, and Facilitator

x402 activates RFC 9110’s reserved HTTP 402 status code, which was defined but left for future use (RFC 9110). The handshake is a four-step HTTP exchange defined in the official x402 spec repo:

  1. Client requests a protected endpoint.
  2. Server responds 402 Payment Required with a base64 PAYMENT-REQUIRED header containing payment terms (amount, asset, chain, payTo address, facilitator URL, scheme).
  3. Client pays on-chain, then retries with a PAYMENT-SIGNATURE header.
  4. Server verifies via the facilitator’s /verify endpoint, serves 200 OK with the data plus a PAYMENT-RESPONSE header (base64 settlement proof), and the facilitator’s /settle finalizes on-chain.

The V2 spec (current, launched Dec 2025) moved all payment data into HTTP headers beside the 402, made multi-chain default (Base, Solana, more), and split spec/SDK/facilitators into separate packages (x402.org V2 launch). Three payment schemes are defined: exact, upto, and batch-settlement (GitHub x402 README).

Scheme Payment model Best for Settlement Source
exact Fixed amount per request Simple pay-per-call APIs (e.g., Zerion $0.01/call) Immediate on-chain per call GitHub x402 README
upto Capped amount (agent pays ≤ max) Variable-cost endpoints where overpayment must be prevented Immediate, capped GitHub x402 README
batch-settlement EVM escrow + vouchers High-frequency routes (many calls, periodic settlement) Batched on-chain via escrow GitHub x402 README

Scaffold the Paywalled Server: Install and Wire paymentMiddleware

The official x402 SDK turns any Express route into a paywalled USDC endpoint with roughly one line of middleware. Per the GitHub README’s installation section, install the minimal server packages:

npm install @x402/core @x402/express @x402/evm

Then wrap any route with paymentMiddleware, passing a config object that maps routes to accepted payment schemes (route-map shape condensed below; the full signature is in the README):

import { paymentMiddleware } from '@x402/express';

const walletDataConfig = {
  accepts: ['exact'],  // or 'upto', 'batch-settlement'
  description: 'Normalized wallet portfolio data — $0.01 USDC per call on Base',
  // amount, asset, chain, payTo, facilitatorUrl set via environment or config
};

app.get(
  '/v1/wallets/:address/portfolio',
  paymentMiddleware({ 'GET /v1/wallets/:address/portfolio': walletDataConfig }),
  (req, res) => {
    // Fetch wallet data (mirrors Zerion's pattern)
    res.json({ portfolio: { totalUsd: 12480.32, chains: ['base', 'ethereum'] } });
  }
);

This mirrors the Coinbase seller quickstart’s “charge for an endpoint” pattern. The middleware intercepts unauthenticated requests, returns 402 Payment Required with the PAYMENT-REQUIRED header, and only calls your handler once payment is verified. For a full production config, the README shows the complete paymentMiddleware signature including facilitatorUrl, receiverAddress, and scheme-specific options (GitHub x402 README).


Client Flow: Pay from an Agent Wallet, Retry, Receive Data

An agent pays for your endpoint automatically using the @x402/fetch wrapper, which handles the full handshake under the hood. Per the GitHub README, install the client packages:

npm install @x402/core @x402/evm @x402/fetch

The client flow is three steps: hit the endpoint, pay the 402, retry with the payment signature. Using @x402/fetch:

import { x402Fetch } from '@x402/fetch'; // export name condensed from README — check @x402/fetch docs for the current API

const response = await x402Fetch(
  'https://api.yourservice.com/v1/wallets/0xabc.../portfolio',
  {
    privateKey: process.env.AGENT_WALLET_PRIVATE_KEY,
    // x402Fetch automatically: gets 402, decodes PAYMENT-REQUIRED,
    // pays USDC on Base, retries with PAYMENT-SIGNATURE
  }
);
const data = await response.json(); // 200 OK + PAYMENT-RESPONSE header

For a raw curl walkthrough, the manual sequence is: request → receive 402 + PAYMENT-REQUIRED → construct and send the on-chain payment → retry with the PAYMENT-SIGNATURE header (GitHub x402 README). For agent-side wallet setup, Coinbase’s Agentic Wallets (npx awal) creates a purpose-built wallet in under two minutes with agent skills for authenticate/fund/send/trade, gasless on Base, and native x402 support (news.bitcoin.com). This is the cleanest way to give your agent a paying wallet with session caps and per-transaction limits.


Production Path: CDP Quickstart vs Testnet Facilitator vs Self-Facilitation

For production, the Coinbase Developer Platform offers a hosted facilitator that verifies and settles x402 payments — and it has already processed more than 100 million x402 payments across Base and Solana (Coinbase x402 overview). The CDP seller quickstart walks through the merchant path: configure your endpoint, set a price in USDC, and receive payouts to any address — CDP custodial, Coinbase Business, Prime, or self-custody.

Three production options exist, per the x402 README’s “Choosing a Production Path” and docs.x402.org:

  1. CDP production facilitator — Hosted, battle-tested (100M+ payments), handles /verify and /settle. Best for most merchants.
  2. Public testnet facilitator — For development and quickstarts only; not for real funds.
  3. Self-facilitation — Run your own facilitator for full control; documented but requires running verification and settlement infrastructure.

The CDP quickstart also covers the Business Checkouts API, which generates an x402_url for agents alongside a hosted payment URL for humans — meaning one integration serves both audiences. Coinbase’s x402 launched May 6, 2025 with the explicit goal of making HTTP 402 a real payment primitive (Coinbase launch post).


Real-World Merchant Reference: Zerion’s $0.01/Call API on Base and Solana

Zerion’s API is the flagship x402 merchant: since March 2026, agents pay $0.01 USDC per call on Base (and Solana) for normalized wallet data — portfolios, DeFi positions, PnL, prices — with no API key, no rate limits, no subscription (Zerion blog). The Zerion x402 dev docs show the flow: agents request data, hit a 402, pay $0.01 USDC, and receive the same JSON:API response they’d get with a keyed request.

You can test the live flow immediately. Zerion’s official AI repo (zeriontech/zerion-ai) documents the CLI install and x402 flow:

# Install the CLI
npm i -g zerion-cli

# Query wallet data via x402 (pays $0.01 USDC on Base automatically)
export WALLET_PRIVATE_KEY=your_agent_wallet_key
npx zerion-cli init
zerion-cli wallet portfolio 0xabc... --x402

The live demo endpoint pattern is api.zerion.io/v1/wallets/{address}/transactions/ — hit it without a key, and you’ll get a 402 with payment terms (Zerion dev docs). Zerion used the Coinbase Developer Platform to accept payments, and their integration now covers 38+ chains following the AgentCash integration (CryptoBriefing). This is your reference for pricing, flow, and developer experience.


Discoverability: Listing on AgentCash and the x402 Ecosystem

A paywalled endpoint only generates revenue if agents can find it. AgentCash — launched early July 2026 — provides the discovery and payment layer: agents find and pay for APIs via CLI or agent skill, and merchants list their endpoints for agent consumption (AgentCash docs). The network grew from ~250 premium APIs at launch to 3,200+ APIs with 500+ apps (including Coinbase Wallet) by late August (CryptoBriefing).

To list your endpoint, AgentCash’s pay-per-call API guide walks through the flow: your server returns 402 with the payment-terms payload, AgentCash handles wallet/auth/payment on the agent’s side, and your endpoint appears in their discoverable catalog. The x402scan.com explorer provides ecosystem-level transaction visibility — useful for monitoring the broader x402 economy. Listing on AgentCash is the difference between an endpoint that exists and an endpoint that agents actually use.


Stretch: Charge for an MCP Tool, Not Just an HTTP Route

The same payment middleware wraps MCP tool calls, not just HTTP routes — turning model-context-protocol tools into revenue generators. The x402 SDK includes @x402/mcp for this purpose (GitHub x402 README), and Alchemy’s guide to adding x402 payments to an MCP server provides the recipe. Coinbase’s seller quickstart includes a “Charge over MCP” variant as a first-class pattern.

The shape is the same — wrap the tool handler with payment middleware (illustrative shape; see the Alchemy guide and @x402/mcp docs for the current signature):

npm install @x402/mcp @x402/core @x402/evm
import { mcpPaymentMiddleware } from '@x402/mcp';

const server = new McpServer({ name: 'wallet-analytics' });

server.tool(
  'get_wallet_portfolio',
  { address: z.string() },
  mcpPaymentMiddleware(
    { accepts: ['exact'], description: '$0.01 USDC per call on Base' },
    async ({ address }) => {
      const portfolio = await fetchWalletData(address);
      return { content: [{ type: 'text', text: JSON.stringify(portfolio) }] };
    }
  )
);

This is a natural extension if you already ship MCP servers — see our analysis of MCP attack surfaces for the security context around agent-facing MCP tools. The monetization layer is orthogonal to the transport.


Seller-Side Security and Limits (Docs-Verified Only)

The x402 trust model keeps seller private keys isolated: the facilitator verifies payments and settles to any address you specify — CDP custodial, Coinbase Business, Prime, or self-custody — without your key ever touching the facilitator (Coinbase x402 overview). Per the GitHub README, the payment schemes themselves provide safety controls: upto caps overpayment (the agent pays up to a maximum, never more), and batch-settlement uses EVM escrow with vouchers for high-frequency routes. On the agent side, Agentic Wallets include session spending caps and per-transaction limits, so an agent that goes rogue can only spend within its configured budget. These are the documented controls — no invented vulnerabilities, just the protocol’s built-in guardrails.


Resources

All links verified HTTP 200 on 2026-09-03:


FAQ

What does an agent see when it hits a paywalled x402 endpoint? The server responds 402 Payment Required with a base64 PAYMENT-REQUIRED header containing payment terms (amount, asset, chain, payTo address, facilitator URL). The agent decodes the terms, pays USDC on-chain, and retries with a PAYMENT-SIGNATURE header (GitHub x402 README).

Do I need a facilitator, and what does it do? A facilitator’s /verify endpoint checks that a payment is valid before the server releases data; /settle finalizes on-chain settlement. CDP offers a production facilitator that has processed 100M+ payments; a public testnet facilitator exists for development; self-facilitation is also documented (Coinbase x402 overview).

What’s the difference between exact, upto, and batch-settlement schemes? exact requires the precise amount per call. upto caps overpayment — the agent pays up to a maximum, never more. batch-settlement uses EVM escrow with vouchers for high-frequency routes, settling in batches rather than per call (GitHub x402 README).

Can I charge for an MCP tool instead of a plain HTTP route? Yes — the @x402/mcp package wraps MCP tool calls with the same payment middleware used for HTTP routes. Coinbase’s seller quickstart includes a “Charge over MCP” variant, and Alchemy published a full integration guide (CDP seller quickstart).

How does x402 relate to Visa’s Trusted Agent Protocol or Mastercard Agent Pay? x402 is an open, HTTP-native protocol using stablecoins on public chains; Visa TAP and Mastercard Agent Pay are card-network rails for agentic commerce. They are complementary approaches to the same problem — not competitors (x402.org).


The Bottom Line

The x402 pay-per-call pattern is production-ready today: three major platforms adopted it in August 2026, Coinbase’s facilitator has processed 100M+ payments, and Zerion proves the $0.01/call model works with live agents. The implementation cost is one middleware line per endpoint plus a facilitator choice — no API-key infrastructure, no subscription billing, no signup flow. If you serve data to AI agents, wrapping your endpoints in x402 gives you a metered revenue line per route — one that agents discover and pay automatically. Start with the CDP seller quickstart, mirror Zerion’s pricing, and list on AgentCash.

For broader context on the agent-economy infrastructure shift, see our coverage of AI agent trading platforms and the security implications of agent-facing MCP servers.

← Back to all posts