DEV Community

goldbean
goldbean

Posted on

x402 Micropayments for AI Agents: A Step-by-Step Tutorial (2026)

What is x402 and Why Should You Care?

You've probably seen HTTP 402 Payment Required in old HTTP spec docs and wondered what it's for. Turns out, it was waiting for AI agents.

x402 is a protocol where an API returns 402 Payment Required with a price instead of denying access. Your AI agent reads the price, attaches a USDC payment (one microtransaction on Base network), and gets the data. No API keys, no monthly subscriptions, no signup flow.

But the real magic? AI agents can discover and pay for APIs autonomously — no human in the loop.

How x402 Works in Practice

Here's the flow:

1. Agent → API:    GET /data
2. API → Agent:    402 Payment Required — $0.01
3. Agent → Chain:  Signed USDC transfer (Base network)
4. Agent → API:    GET /data (with x402-payment header)
5. API → Agent:    200 OK + response data
Enter fullscreen mode Exit fullscreen mode

The whole round trip takes about 2 seconds.

Step 1: Discover x402 Endpoints

Before your agent can call APIs, it needs to find them. The x402 ecosystem has several discovery services:

Circle Agent Marketplace (42 services, 644 endpoints):

https://agents.circle.com/services
Enter fullscreen mode Exit fullscreen mode

402 Index (protocol-agnostic directory):

https://402index.io
Enter fullscreen mode Exit fullscreen mode

BlockRun (600+ indexed x402 services):

https://blockrun.ai/marketplace
Enter fullscreen mode Exit fullscreen mode

Most x402 services also expose a /.well-known/x402-bazaar endpoint listing supported currencies, pricing, and wallet addresses:

curl -s https://goldbean-api.xyz/.well-known/x402-bazaar | jq
Enter fullscreen mode Exit fullscreen mode

Which returns:

{
  "name": "GoldBean API",
  "version": "8.0.0",
  "currencies": [
    {
      "id": "USDC",
      "network": "base",
      "decimals": 6,
      "contract": "0x833589fcd6edb6e08f4c7c32d4f71b54bdA02913"
    }
  ],
  "pricing": {
    "standard": { "price": 0.99, "currency": "USDC", "unit": "per request" },
    "bulk_100": { "price": 49, "currency": "USDC", "unit": "100 requests", "valid_days": 30 },
    "bulk_500": { "price": 199, "currency": "USDC", "unit": "500 requests", "valid_days": 90 }
  },
  "payment_methods": ["x402", "paypal", "alipay"],
  "wallet": "0x7484b0bca25d2ee56e9b0535572d4cf44a047d98",
  "network": "eip155:8453",
  "endpoint": "https://goldbean-api.xyz"
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Pay with x402 via curl

First, check the price by sending a request without payment:

curl -v -X POST "https://goldbean-api.xyz/paid/baidu-ocr-accurate" \
  -F "image=@test.jpg"
Enter fullscreen mode Exit fullscreen mode

You'll get a 402 Payment Required with the exact price.

To pay, sign a USDC transfer on Base network using your wallet. Here's the x402 header format:

x402-payment: <signed-transaction-hex>
Enter fullscreen mode Exit fullscreen mode

For automated payments, use the Circle SDK:

npm i @circle-fin/x402-batching
Enter fullscreen mode Exit fullscreen mode
import { createClientMiddleware } from "@circle-fin/x402-batching/client";

const client = createClientMiddleware({
  signer: myWalletSigner,
});

const response = await fetch("https://goldbean-api.xyz/paid/baidu-ocr-accurate", {
  method: "POST",
  body: formData,
  ...client,
});

const result = await response.json();
Enter fullscreen mode Exit fullscreen mode

No API keys. No signup. Just a wallet and USDC.

Step 3: Build an x402 Agent in Python

Here's a complete AI agent that calls Baidu OCR via x402, running in a loop to process documents:

import requests
from web3 import Web3
import json

# Connect to Base
w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))
account = w3.eth.account.from_key("YOUR_PRIVATE_KEY")

# USDC contract on Base
USDC = "0x833589fcd6edb6e08f4c7c32d4f71b54bdA02913"
usdc = w3.eth.contract(
    address=USDC,
    abi=[{"constant": False, "inputs": [
        {"name": "_to", "type": "address"},
        {"name": "_value", "type": "uint256"}
    ], "name": "transfer", "type": "function"}]
)

def call_with_x402(url, data, amount_usdc):
    """Make an x402 payment and call the API."""

    # Build USDC transfer (6 decimals)
    tx = usdc.functions.transfer(
        "0x7484b0bca25d2ee56e9b0535572d4cf44a047d98",
        int(amount_usdc * 10**6)
    ).build_transaction({
        "chainId": 8453,
        "gas": 65000,
        "gasPrice": w3.eth.gas_price,
        "nonce": w3.eth.get_transaction_count(account.address),
    })

    # Sign and send
    signed = account.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

    # Call API with payment proof
    response = requests.post(url, data=data, headers={
        "x402-payment": receipt.transactionHash.hex()
    })
    return response.json()

# OCR a batch of documents
documents = ["invoice_1.jpg", "invoice_2.jpg", "receipt_3.jpg"]
for doc in documents:
    result = call_with_x402(
        "https://goldbean-api.xyz/paid/baidu-ocr-accurate",
        {"image": open(doc, "rb")},
        0.01  # $0.01 per call
    )
    print(f"{doc}: {result.get('words_result', [])[:3]}")
Enter fullscreen mode Exit fullscreen mode

Step 4: Let AI Agents Discover Your API

If you have an API, you can turn it into an x402 storefront in minutes. Here's what you need:

  1. A wallet on Base network with USDC
  2. Add x402 middleware (Circle SDK or custom implementation)
  3. Serve a /.well-known/x402-bazaar discovery endpoint
// Minimal x402 middleware for Express
import { createGatewayMiddleware } from "@circle-fin/x402-batching/server";

const gateway = createGatewayMiddleware({
  sellerAddress: "0xYOUR_WALLET",
});

app.get("/data",
  gateway.require("$0.01"),  // Price: $0.01 per call
  handler
);
Enter fullscreen mode Exit fullscreen mode

That's it. Three lines and your API becomes discoverable by every x402-aware AI agent in the ecosystem.

Why x402 Matters for AI Agents

The Circle Agent Marketplace already lists 42 services with 644 endpoints. BlockRun indexes 600+ services. Every one of them is pay-per-call via x402.

This is the emerging payment standard for AI agent-to-API communication:

  • No signup friction: Agents don't fill out forms
  • No minimums: Pay $0.01 for a single call
  • No API key management: The wallet is the credential
  • Cross-platform: Works across Base, Solana, and Stripe/Tempo (MPP)

Try It Now

The easiest way to experience x402 is to make a single call to an x402-enabled API:

# Step 1: Check the price (expect 402)
curl -s -o /dev/null -w "%{http_code}" \
  "https://goldbean-api.xyz/.well-known/x402-bazaar"
# → 200 (bazaar endpoint is free)

# Step 2: Pick your stack
# - curl + Circle SDK for quick testing
# - Python + web3.py for automation
# - Node.js + x402-batching for production
Enter fullscreen mode Exit fullscreen mode

GoldBean API supports x402 alongside PayPal and Alipay — one of the few marketplaces with all three payment rails. Try it at goldbean-api.xyz.


GoldBean is a pay-per-call API marketplace supporting x402 (USDC on Base), PayPal, and Alipay. Pricing starts at $0.01/call with bulk discounts available. Companion MCP server: npx goldbean-mcp.

Top comments (0)