How x402 handles payments

Traditional API billing relies on pre-issued keys and backend subscription checks. x402 flips this model. Instead of verifying a token before processing a request, the server responds with an HTTP 402 Payment Required status code. This standard HTTP response tells the client—whether a human or an autonomous AI agent—that access is blocked until payment is settled.

When your endpoint returns a 402, it includes the payment details in the headers. The client must then pay the requested amount, typically in USDC on a low-cost Layer 2 network like Base, and attach the transaction receipt to a retry request. This creates a frictionless, pay-per-use flow that works natively over HTTP without middleware or complex webhook setups.

This mechanism shifts the burden of payment verification to the protocol layer. You no longer need to maintain complex user accounts or subscription states. The server simply states its price, and the client pays to access the data. This is particularly powerful for AI trading signals, where latency and automated execution are critical.

By leveraging standard HTTP status codes, x402 ensures compatibility with existing web infrastructure. Any HTTP client can interact with your endpoint, provided it supports the payment logic. This simplicity reduces integration time and allows you to focus on building high-quality trading signals rather than managing billing systems.

Implement the endpoint logic

You don't need a complex payment gateway to accept crypto. The x402 protocol turns your API endpoint into a self-contained payment processor. The logic is straightforward: check for a receipt, validate it, and serve the data.

Here is how to build the handler.

1
Return 402 with payment details
When an AI agent calls your endpoint without a valid payment receipt, do not return a 404 or 500 error. Return a 402 Payment Required status code. The response body must include the payment details: the amount in USDC, the destination wallet address, and the transaction ID (txid) for the previous successful payment if applicable. This tells the agent exactly what to pay to access the resource. See the x402 documentation for the exact JSON schema.
2
Validate the payment receipt
When the agent retries the request, it attaches a PaymentReceipt header. This is a signed JSON Web Token (JWT) containing the transaction hash, the amount paid, and the recipient address. Use a library like jsonwebtoken to verify the signature against the public key of the blockchain network (e.g., Base). If the signature is invalid or the transaction hasn't been confirmed on-chain, reject the request with a 401 Unauthorized .
3
Serve the trading signal
Once the receipt is verified, extract the signal data from your backend. This could be a JSON object containing buy/sell recommendations, confidence scores, or market indicators. Return a 200 OK status with the signal data in the response body. The agent can now process this data and execute trades. Ensure your endpoint is idempotent; if the agent retries with the same valid receipt, it should return the same signal without charging the agent again.

This structure keeps your code clean and your revenue automated. You handle the HTTP logic, and x402 handles the crypto settlement.

Configure USDC on Base

To make micropayments for AI trading signals economically viable, you need a blockchain network where gas fees don’t eat into the transaction value. The x402 protocol supports various chains, but for high-frequency, low-value signals, Base is the optimal choice. It is an Ethereum Layer 2 network built by Coinbase, offering near-instant finality and negligible costs.

The economics are straightforward: x402 charges zero protocol fees, meaning you only pay the underlying blockchain gas. On Base, gas costs typically sit under $0.001 per transaction. This allows you to charge cents per signal without the transaction cost exceeding the payment itself. Without this layer, standard Ethereum mainnet fees would make per-signal payments impossible.

Set Up Your Wallet and Network

First, ensure your development environment is configured for Base. You can use any Ethereum-compatible wallet, such as MetaMask, and add the Base network manually or via a wallet service like Coinbase Wallet. For production, consider using Circle Wallets for programmable, autonomous payments that integrate seamlessly with x402.

Fund with USDC

USDC is the standard stablecoin for x402 on Base. It provides price stability, which is critical when your API returns data priced in fractions of a cent. You can bridge USDC from Ethereum mainnet or buy it directly on Coinbase and withdraw it to your Base wallet address. Ensure your endpoint’s x402 headers are set to accept USDC specifically, as the protocol will reject payments in other tokens if not configured otherwise.

<$0.001
Typical Base gas fee per transaction

By anchoring your payments on Base with USDC, you remove the friction of high costs and volatility. This setup ensures that every time an AI agent requests a signal, the payment happens instantly and cheaply, keeping the loop between data and revenue tight.

Handle common integration errors

Even with a solid x402 implementation, network latency and malformed responses can disrupt your AI trading signals. The protocol relies on a strict handshake: the agent requests data, receives a 402 with payment details, pays in USDC, and retries with a receipt. If any step fails, the signal delivery stalls.

Timeout handling

AI agents often operate on tight schedules. If your endpoint takes too long to generate a signal, the agent may timeout before completing the payment handshake. Set reasonable timeouts on your server-side processing, but ensure the 402 response itself is immediate. The payment logic should be decoupled from the signal generation to keep the initial response fast.

Malformed receipts

A common pitfall is accepting receipts that don’t match the expected token or chain. Always validate the payment-receipt header against the token and chain specified in your 402 response. If an agent sends a receipt for the wrong network (e.g., Ethereum instead of Base), reject it with a clear 400 error. This prevents your endpoint from accepting invalid payments or getting stuck in a retry loop.

Idempotency

Agents may retry payments due to network congestion. Implement idempotency checks to ensure you don’t process the same payment twice. Track transaction hashes or receipt IDs to deduplicate incoming requests. This is critical for trading signals where duplicate data could trigger erroneous trades.

Validation failures

Ensure your server correctly parses the payment receipt. Use a library like @coinbase/x402 to validate the signature and amount. If validation fails, return a 402 error with a clear message indicating what went wrong. This helps agents debug their integration faster.

Debugging tips

Use Coinbase’s official documentation to verify your implementation. Test with a sandbox environment before going live. Check the payment-receipt header format and ensure your server is correctly interpreting the JSON payload. If issues persist, enable verbose logging to trace the handshake steps.

Verify transaction settlement

Before your AI agent releases a high-value trading signal, you need to be certain the payment has actually cleared. In the x402 protocol, this means confirming the on-chain transaction is settled. Because these endpoints handle sensitive financial data, releasing a signal before payment confirmation is a security risk that can lead to unpaid API calls or data leaks.

The verification process is straightforward. Your endpoint should check the transaction hash provided in the request headers against the blockchain. For x402-enabled services, this often involves checking the Bazaar discovery layer or using the CDP Facilitator to validate that the stablecoin transfer is complete. Since x402 charges zero protocol fees—only blockchain gas costs—you can verify this quickly and cheaply, especially on Layer 2 networks like Base where gas is minimal.

Once you confirm the transaction is settled, you can safely release the signal. If the payment is still pending or fails, the endpoint should return a 402 Payment Required error. This ensures that only paying users access your proprietary data.

Pre-release verification checklist

  • Extract the transaction hash from the request headers.
  • Query the blockchain (or Bazaar discovery layer) for confirmation.
  • Verify the amount matches the expected signal price.
  • Confirm the sender address matches the authenticated user.
  • Release the signal only after settlement is confirmed.

Frequently asked: what to check next