aibank
API ReferencePayments

x402 Payments

HTTP-native payment protocol. Pay for API calls with on-chain USDC instead of API keys.

x402 Payments

The x402 protocol allows agents to pay for API calls using on-chain USDC transfers instead of traditional API keys. It works on all /v1/gateway/* endpoints.

Flow

Step 1: Request without API key

Send a request to any gateway endpoint without an X-API-Key header:

curl -X POST http://localhost:4000/v1/gateway/anthropic/v1/messages \
  -H "Content-Type: application/json" \
  -d '{"model": "claude-sonnet-4-20250514", "max_tokens": 100, "messages": []}'

Step 2: Receive 402 with payment instructions

{
  "error": "Payment required",
  "code": "PAYMENT_REQUIRED",
  "payment": {
    "amount": "0.01",
    "currency": "USDC",
    "recipient": "0xRecipientAddress",
    "chain": "base-sepolia",
    "network": "base-sepolia",
    "description": "API call: POST /v1/gateway/anthropic/v1/messages",
    "instructions": "Send USDC on Base Sepolia to the recipient address, then retry with X-Payment: <txHash>"
  }
}

Response headers

HeaderValue
X-Payment-Requiredtrue
X-Payment-AmountAmount in USDC
X-Payment-CurrencyUSDC
X-Payment-RecipientRecipient wallet address
X-Payment-ChainChain to pay on
X-Payment-DescriptionWhat the payment is for

Step 3: Send USDC on-chain

Transfer the specified amount to the recipient address on the specified chain.

Step 4: Retry with proof

curl -X POST http://localhost:4000/v1/gateway/anthropic/v1/messages \
  -H "Content-Type: application/json" \
  -H "X-Payment: 0xYourTransactionHash" \
  -H "X-Payment-Chain: base-sepolia" \
  -d '{"model": "claude-sonnet-4-20250514", "max_tokens": 100, "messages": []}'

The server verifies the on-chain payment and processes the request.

Verification

The server performs the following checks:

  1. Transaction exists on the specified chain
  2. Recipient matches the required payment address
  3. Amount meets or exceeds the required amount
  4. Not already used (double-spend protection)

Error codes

StatusCodeDescription
402PAYMENT_REQUIREDNo API key or payment provided
402PAYMENT_ALREADY_USEDTransaction hash already consumed
402PAYMENT_INVALIDOn-chain verification failed

Automatic payment with SDK

const wallet = aibank.getWallet("wallet-uuid");

// Automatically handles 402 → pay → retry
const response = await wallet.x402Fetch(
  "http://localhost:4000/v1/gateway/anthropic/v1/messages",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "claude-sonnet-4-20250514",
      max_tokens: 100,
      messages: [{ role: "user", content: "Hello" }],
    }),
  }
);

On this page