Why HTTP 402 matters for agents
For decades, the web has treated API access as a binary choice: you either have permission, or you don't. When a request hits a paywall, the server responds with a 403 Forbidden. This works for human users browsing behind a login, but it breaks down for autonomous agents. An AI agent doesn't have a credit card on file or a recurring subscription dashboard to manage. It needs to pay, get the data, and move on, all within a single transaction.
This is where the HTTP 402 Payment Required status code becomes essential. Reserved for future use in the original HTTP specifications, it has found a second life as the standard for micropayments. Unlike the 403, which signals a hard stop, 402 signals a transaction opportunity. It tells the client, "Access is possible, but only after payment."
This shift enables a truly transactional economy for APIs. Instead of forcing developers into rigid monthly subscriptions, services can charge per call, per kilobyte, or per token. This model aligns perfectly with how AI agents operate: they consume resources in discrete, measurable bursts. By implementing 402, you allow agents to pay for exactly what they use, removing the friction of long-term commitments and enabling micro-transaction workflows at scale.
Set up the x402 payment flow
The x402 protocol turns the HTTP 402 status code into a functional payment gateway. Instead of relying on subscription keys or third-party payment processors, the server demands a signed cryptocurrency transaction before releasing data. This approach shifts the burden of payment verification to the client, allowing you to build a pay-per-call infrastructure that is both autonomous and permissionless.
Implementing this flow requires coordinating three distinct components: the wallet that signs the payment, the API endpoint that validates the signature, and the blockchain network that settles the transaction. We will walk through the integration using Base, a network optimized for this type of micropayment activity due to its low gas fees and fast finality.
1. Configure the wallet and network
Before writing any code, you need a wallet capable of signing transactions and holding the necessary tokens. Most modern Web3 wallets like MetaMask or Rabby support Base. You will need to fund this wallet with a small amount of ETH (for gas) and the stablecoin you intend to use for payments, typically USDC on Base.
Next, ensure your development environment is set up to interact with the Base network. You will need to configure your RPC provider to point to Base Mainnet or Base Sepolia for testing. This configuration is critical because the signature verification logic depends on the correct chain ID to prevent replay attacks across different networks.
2. Define the payment amount and signature payload
The core of x402 is the paymentSignature header. Your API should define a specific payload that the client must sign. This payload typically includes the resource path, the amount to be paid, and a nonce to ensure uniqueness. For example, if a client wants to call /api/data, the payload might look like:
{
"path": "/api/data",
"amount": "0.01",
"currency": "USDC",
"nonce": "12345"
}
This structure ensures that the signature is bound to a specific action and price. Without the nonce, a malicious actor could replay the same signature to access the API multiple times without paying again. Always validate that the nonce increases with each request.
3. Implement the signature verification logic
On the server side, you need a middleware function that intercepts incoming requests. This function extracts the paymentSignature header and the associated transaction details. You then use a library like ethers.js or viem to recover the signer's address from the signature and verify it matches the expected payment address.
The verification process involves two checks:
- Signature Validity: Does the recovered address match the public key of the sender?
- Transaction Status: Has the blockchain confirmed the transaction for the specified amount?
If either check fails, the server should immediately respond with a 402 Payment Required status. This response should include a link to the payment page or instructions on how to complete the transaction, guiding the user back to the payment flow.
4. Handle the transaction confirmation
Unlike traditional payments, crypto transactions require on-chain confirmation. Your server should not release data the moment it sees the signature; it must wait for the transaction to be mined. You can use a blockchain indexer or a simple polling mechanism to check the transaction status on Base.
For micropayments, speed is essential. Base offers fast block times, but you still need to account for the few seconds it takes for a transaction to be included in a block. Implement a retry logic in your client-side code that waits for the txHash to be confirmed before proceeding with the API call. This prevents race conditions where the client thinks they have paid, but the server has not yet seen the transaction.
5. Test the end-to-end flow
Finally, test the entire flow using a local development server and a testnet wallet. Simulate various failure states, such as insufficient funds, invalid signatures, and expired nonces. Ensure that your API correctly rejects these requests with a 402 status and provides clear error messages.
Once the testnet flow is stable, move to Mainnet with a small amount of real capital. Monitor the gas costs and transaction success rates to ensure the flow is efficient. This step-by-step approach ensures that your x402 implementation is robust, secure, and ready for production use.
Choose your network and token
The foundation of any micropayment system is the underlying blockchain. If your network fees exceed the value of the API call, the business model collapses. For x402 integrations, you need a chain that offers near-zero gas costs and instant finality. Base and USDC have become the standard combination for this reason.
Base is an Ethereum Layer 2 network built on the OP Stack. It was designed specifically to handle high-frequency transactions at a fraction of the cost of Ethereum mainnet. When combined with USDC, an ERC-20 stablecoin pegged to the US dollar, you get predictable pricing for both the developer and the end-user. This pairing removes the volatility risk that plagues native token payments.
Base’s architecture allows for transaction fees that typically cost less than a cent. This makes it viable to charge fractions of a cent for API responses. USDC ensures that the value transferred remains constant, simplifying accounting and revenue recognition. Together, they create a frictionless path for machine-to-machine payments.
Network and Token Comparison
The table below compares the critical metrics for implementing x402 on Base versus other common options.
| Network | Avg. Gas Cost | Settlement Time | x402 Compatibility |
|---|---|---|---|
| Base (L2) | <$0.01 | <2 seconds | Native |
| Ethereum Mainnet | $1.00+ | 12-15 seconds | High (but expensive) |
| Polygon | <$0.01 | <2 seconds | Supported via Bridge |
| Solana | <$0.001 | <1 second | Not Native |
Base offers native support for x402 through its official documentation and tooling. Ethereum mainnet is technically compatible but economically unviable for micropayments due to gas spikes. Polygon is a viable alternative if your users are already on that chain, but it requires additional bridging logic. Solana offers speed but lacks native x402 integration, requiring a custom implementation.
For most developers starting out, Base is the default choice. It provides the best balance of speed, cost, and ecosystem support. The official Base documentation provides clear guides on integrating x402 payments directly into your API endpoints.
Fix common integration errors
Even with a solid protocol design, integration hiccups are inevitable. The most frequent culprits are signature mismatches, expired nonces, and malformed HTTP headers. Treat these not as abstract concepts, but as specific bugs in your request pipeline.
Signature mismatches
A 402 error often stems from a crypto mismatch. Ensure your client signs the payload using the exact same algorithm and key version specified in the API contract. Check for common pitfalls: trailing newlines in the payload, incorrect encoding of binary data, or using the wrong private key for the environment (test vs. production).
Expired nonces
Nonces prevent replay attacks, but they have a short lifespan. If your server clock and client clock are out of sync by more than the allowed window (usually 5-15 minutes), the request will be rejected. Implement a simple clock-sync check during initialization. If drift is detected, log a warning and attempt to adjust the local timestamp before signing.
Incorrect HTTP header formatting
API gateways are strict about header casing and formatting. Ensure your Authorization header follows the exact schema (e.g., Bearer <token> or PayAPI <signature>). Avoid adding extra spaces or using non-standard header names. Validate your request structure against the official API documentation before sending it to production.
Verify payments before serving data
Before your API returns the requested payload, you must confirm the transaction is settled. The HTTP 402 Payment Required response is a gate, not a receipt. Your backend needs to act as the validator, ensuring the blockchain state reflects a completed transfer before unlocking the resource.
Start by extracting the transaction ID from the request headers or body. Use this ID to query the relevant blockchain explorer or RPC node. You are looking for two things: confirmation count and status. A single confirmation is often insufficient for high-value or high-risk data; aim for at least three block confirmations to mitigate double-spend risks.
Only when the transaction is confirmed should you proceed to serve the data. If the payment is missing or pending, return the 402 status with a clear error message and the required payment amount. This logic ensures that every byte of data served has been paid for, maintaining the integrity of your micropayment infrastructure.
-
Extract transaction ID from request headers
-
Query blockchain RPC for transaction status
-
Verify minimum block confirmations (e.g., 3+)
-
Check recipient address matches API wallet
-
Return 402 if payment is pending or invalid

No comments yet. Be the first to share your thoughts!