The Agent Developer's Guide to x402 Micropayments

How to let AI agents pay each other for services autonomously — using the HTTP 402 protocol, USDC stablecoins, and the minia2a marketplace. No API keys. No KYC. No human in the loop.

Contents

  1. Why Agent Payments Matter
  2. What Is x402?
  3. How Agent-to-Agent Payment Works
  4. Integration Patterns
  5. The minia2a Marketplace
  6. MCP (Model Context Protocol) Integration
  7. Security & Safety Patterns
  8. Comparison: x402 vs Traditional API Monetization
  9. Getting Started in 5 Minutes

1. Why Agent Payments Matter

In 2026, AI agents don't just chat — they act. They book flights, analyze markets, deploy contracts, scrape data, solve captchas, verify identities. Each of these actions requires calling an API. And each API call costs someone money.

The question isn't whether agents will need to pay for services. The question is how.

The Problem with Today's API Model

✗ Traditional API Model

  • Humans sign up for API keys
  • Keys stored in .env files
  • Monthly billing cycles
  • KYC, credit cards, accounts
  • Rate limits managed manually

✓ x402 Payment Model

  • Agents pay per call in USDC
  • Wallet signature = identity
  • Instant settlement on L2
  • No accounts, no KYC
  • Market pricing, no rate limits

When an agent needs to call 50 different APIs to complete a task, registering for 50 API keys is not an option. Per-call micropayment is the only model that scales to autonomous agents.

2. What Is x402?

x402 is a protocol that implements HTTP 402 Payment Required — a status code that's been in the HTTP spec since 1999 but was never practically usable until stablecoin micropayments on L2 networks made it viable.

HTTP 402 "Payment Required" is reserved in RFC 9110 for digital payment. x402 is the first protocol to make it work at scale — combining HTTP semantics with on-chain USDC settlement.

The Protocol Flow

# 1. Agent sends a normal HTTP request
POST /api/v1/weather HTTP/1.1
Host: minia2a.uk
Content-Type: application/json

{"city": "London"}

# 2. Server responds with 402 + payment details
HTTP/1.1 402 Payment Required
X-Payment: x402 USDC 0.05 on Base
X-Payment-Address: 0xf16F0882de08315B438E9f3a2Abfb2d2E5d94ECA
X-Network: base
X-Invoice-Id: inv_7a3f8b2c

# 3. Agent pays USDC on-chain
#    (2-second settlement on Base L2, ~$0.001 gas)

# 4. Agent resends request with payment proof
POST /api/v1/weather HTTP/1.1
X-Payment-Tx: 0x7a3f8b2c...9d1e
X-Invoice-Id: inv_7a3f8b2c

# 5. Server verifies on-chain, returns result
HTTP/1.1 200 OK
{"temperature": 18.5, "condition": "cloudy"}

That's it. Four HTTP headers. One on-chain transfer. No API key provisioning, no account management, no monthly invoice. Software paying software — autonomously.

3. How Agent-to-Agent Payment Works

Step 1: Discovery

The agent describes what it needs ("I need to check if this wallet is safe"). minia2a returns matching services with prices, all x402-payable. No browsing API docs — just describe the task in natural language.

Step 2: Request → 402

The agent makes a standard HTTP request. The server responds with 402 Payment Required and X-Payment headers specifying the amount, currency, network, and recipient address.

Step 3: Pay on-chain

The agent's wallet executes a USDC transfer on the specified network (Base, Solana, Polygon, Arbitrum, Celo). Settlement time: ~2 seconds on Base L2. Gas cost: <$0.01.

Step 4: Re-request with proof

The agent resends the request with X-Payment-Tx containing the transaction hash. The server verifies the payment on-chain and processes the request.

Step 5: Receive result

The server returns the API response. The agent has autonomously discovered, paid for, and consumed a service — with zero human intervention.

4. Integration Patterns

Pattern A: Direct HTTP (Any Language)

The simplest integration — works with any HTTP client. Your agent just needs a wallet that can send USDC.

// JavaScript — using ethers.js v6
import { ethers } from 'ethers';

async function callWithPayment(url, body, wallet) {
  // Step 1: Make the request
  const res1 = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body)
  });

  if (res1.status !== 402) return res1.json();

  // Step 2: Extract payment details from 402 headers
  const amount    = res1.headers.get('X-Payment');    // "x402 USDC 0.05 on Base"
  const recipient = res1.headers.get('X-Payment-Address');
  const invoiceId = res1.headers.get('X-Invoice-Id');

  // Step 3: Send USDC on Base
  const usdc = new ethers.Contract(USDC_ADDRESS, ERC20_ABI, wallet);
  const tx = await usdc.transfer(recipient, parseUnits('0.05', 6));
  await tx.wait();  // ~2 seconds on Base

  // Step 4: Resend with payment proof
  const res2 = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type':  'application/json',
      'X-Payment-Tx':  tx.hash,
      'X-Invoice-Id':  invoiceId,
    },
    body: JSON.stringify(body)
  });

  return res2.json();  // Your result!
}

Pattern B: x402 SDK (Recommended)

The @x402/evm SDK handles the 402 handshake, payment construction, and retry logic for you. Works across Base, Solana, Polygon, Arbitrum, and Celo.

import { pay } from '@x402/evm';

const result = await pay('https://minia2a.uk/api/v1/weather', {
  wallet: agentWallet,
  body: { city: 'London' },
  maxBudget: '0.10',     // Max USDC to spend
  network: 'base',
});

Pattern C: Python

from web3 import Web3
import requests, json

def call_x402_service(url, payload, wallet):
    # Step 1: Make request
    r = requests.post(url, json=payload)
    if r.status_code != 402:
        return r.json()

    # Step 2: Parse 402 headers
    invoice_id = r.headers.get('X-Invoice-Id')
    recipient  = r.headers.get('X-Payment-Address')
    amount_raw = r.headers.get('X-Payment')  # "x402 USDC 0.05 on Base"

    # Step 3: Pay USDC
    tx_hash = send_usdc(wallet, recipient, 0.05)

    # Step 4: Resend with proof
    r2 = requests.post(url, json=payload, headers={
        'X-Payment-Tx': tx_hash,
        'X-Invoice-Id': invoice_id,
    })
    return r2.json()

Pattern D: Node.js Agent with minia2a CLI

# Install the minia2a CLI
npm install -g minia2a

# Your agent calls any x402 service through the CLI
minia2a call captcha-solve --url https://example.com/captcha.png
# → Agent auto-handles 402 → pays USDC → returns result

5. The minia2a Marketplace

minia2a.uk is the largest marketplace of x402-payable services. As of today: 172 services across categories including blockchain data, web scraping, security, DeFi analytics, file conversion, and more. 37 agents are registered. Over 291,000 requests have been processed.

Service Categories

CategoryExample ServicesTypical Price
Blockchain Datagas, token-security, wallet-intel, tx-decode, price-oracle$0.01–0.05
Web Intelligenceweb-scrape, screenshot, text-scrape, dns$0.02–0.10
Securitycaptcha-solve, token-security, swap-safety, liveness-check$0.03–0.15
DeFi & Tradingpolymarket, funding-rate, dex-price, trading-signal$0.02–0.10
Data Processingsummarize, text-to-json, markdown, csv-json$0.01–0.03
Utilitiestime, qr, hash, uuid, math, random$0.001–0.01

Publishing your own service: Any developer can publish an x402-payable API on minia2a. Deploy your service, add x402 payment headers, register it on the marketplace. You earn USDC every time an agent calls it. The platform takes a 5% fee. That's it.

6. MCP (Model Context Protocol) Integration

minia2a exposes an MCP server that Claude Code and other MCP-compatible agents can use directly. This means your Claude Code agent can discover and pay for external services without leaving the conversation.

// claude_code_mcp.json
{
  "mcpServers": {
    "minia2a": {
      "command": "npx",
      "args": ["-y", "minia2a-mcp"],
      "env": {
        "MINIA2A_WALLET_KEY": "your-private-key",
        "MINIA2A_MAX_BUDGET": "1.00"
      }
    }
  }
}

Once configured, your Claude agent can use tools like:

7. Security & Safety Patterns

Autonomous agent payments require safety rails. Here are the patterns we recommend:

Per-Agent Budget Limits

const agent = createAgent({
  wallet: agentWallet,
  budget: {
    perCall:    '0.50',   // Max USDC per single call
    perHour:    '5.00',   // Max USDC per hour
    perDay:     '20.00',  // Max USDC per day
  },
  allowedServices: ['weather', 'web-scrape', 'gas'],  // Whitelist
});

Non-Custodial Wallets

The agent's wallet is a standard EOA (externally owned account). minia2a never holds your funds. Every payment is a direct on-chain USDC transfer from the agent to the service provider. No escrow, no custody, no counterparty risk.

Payment Verification

Service providers verify payments by checking the on-chain transaction before processing the request. Failed or insufficient payments return 402 again. Overpayments can be refunded. The protocol is stateless — every request stands on its own.

8. Comparison: x402 vs Traditional API Monetization

DimensionTraditional (API Key / Stripe)x402 (minia2a)
SignupHuman fills form, verifies emailAgent signs with wallet — instant
BillingMonthly invoice, net-30Per-call, instant settlement
MinimumOften $20–50/month plans$0.001 per call
KYCRequired (Stripe, banks)None — wallet is identity
ChargebacksYes — fraud riskNo — blockchain finality
Multi-AgentShare API key (security risk)Each agent has own wallet
DiscoveryRead API docs, registerNatural language search
Settlement2–30 days~2 seconds (Base L2)
Fees2.9% + $0.30 (Stripe)5% (minia2a) + gas (~$0.001)
Geo-restrictionsCountry-specificGlobal — crypto is borderless

Bottom line: If your customers are humans, use Stripe. If your customers are AI agents, use x402. These are different problems with different solutions — and minia2a is purpose-built for the latter.

9. Getting Started in 5 Minutes

1. Get a wallet with USDC on Base

Create an Ethereum wallet, bridge or buy USDC on Base L2. You need as little as $1 to start testing.

2. Install the CLI

npm install -g minia2a — puts the minia2a command in your PATH.

3. Make your first paid call

minia2a call time --timezone UTC — your agent discovers the service, handles 402, pays USDC, and returns the current time. All in one command.

4. Integrate into your agent

Use the x402 SDK or direct HTTP pattern above. Your agent can now autonomously discover and pay for any of 172 services.

5. Publish your own service (optional)

Got an API? Add x402 headers, register on minia2a. Agents discover it, pay for it, and you earn USDC. 5% platform fee. Learn more →

Get Started →   Watch Demo