x402 Payments: How AI Agents & APIs Settle
x402 is a payment protocol that lets AI agents and APIs pay each other for small, automated services—like requesting an API call, buying a model inference, or renting compute—without a human in the loop. You define a payment condition (e.g., a price and a wallet address), the agent sends a signed request, and the payment settles automatically. This guide walks through the flow from both sides: the payer (agent) and the payee (API).
What You’ll Need
- A wallet that supports signing (e.g., an EVM wallet with a private key or a signing service).
- Access to the x402 protocol specification (the HTTP headers and signing rules).
- A way to send HTTP requests (curl, a script, or your agent’s code).
- For the payee: a server endpoint that can parse headers and verify signatures.
- Some test funds (on a testnet like Sepolia) if you’re trying it out.
Step-by-Step
- Understand the payment model. x402 uses a “pay-per-request” model. The payer sends a request with a signed header that commits to a payment amount. The payee verifies the signature, processes the request, and then claims the funds (often via a smart contract). The protocol is designed for microtransactions, so the payment is typically in a stablecoin or native token.
- Set up your wallet and signing. The payer needs a private key. In your agent code, import a signing library (e.g., ethers.js for EVM). You’ll sign a message that includes the request details: the URL, method, body hash, and the payment amount.
- Construct the payment header. The x402 protocol defines a header (commonly
X-Payor similar) that carries the signed payload. The payload usually contains: the recipient address, the amount, the token address (or native), a nonce (to prevent replay), and the expiration time. Sign this payload with your private key. - Send the request. When your agent calls the API, include the signed header. For example, using curl:
curl -X POST https://api.example.com/data \ -H "Content-Type: application/json" \ -H "X-Pay:
" \ -d '{"query":"latest"}' The payee’s server will read this header.
- Verify on the payee side. The API server must verify the signature. It recovers the signer address from the signed payload and checks that it matches the payer’s address. It also checks the nonce hasn’t been used, the expiration hasn’t passed, and the amount is correct.
- Process the request. Once verified, the API processes the request normally and returns the response. The payment is not yet settled—it’s just a promise.
- Settle the payment. After the response is sent, the payee calls a smart contract function (e.g.,
claim()) with the signed payload. The contract transfers the funds from the payer’s wallet (if approved) or via a pull payment. This is where the actual transfer happens. - Handle errors and retries. If the signature is invalid or the nonce is stale, the API returns a 402 Payment Required error with a challenge. The agent can then fix the issue and retry. If the payment is too low, the API might respond with a required amount.
Common Mistakes
- Signing the wrong payload. Make sure you sign exactly the fields the protocol expects. Adding or omitting a field changes the signature and causes verification failure.
- Reusing nonces. Each request must have a unique nonce. Reusing a nonce allows replay attacks and will be rejected by the payee.
- Forgetting to check expiration. If your signed payload expires, the payee will reject it. Keep the expiration window short (e.g., 1 minute) to reduce risk.
- Mixing up token addresses. If you’re paying in a stablecoin, ensure you use the correct contract address for the network. Using a wrong address means the payment won’t be recognized.
- Not handling the 402 response. A 402 is not a failure—it’s a signal. Your agent should parse the challenge and adjust (e.g., increase amount, fix signature) rather than crashing.
Tips
- Use a local signing service (like a hardware wallet or a key management system) to keep private keys secure—don’t hardcode them in your agent.
- Set a sane expiration. A 30-60 second window is usually enough for a request. Too long increases the chance of replay.
- Test on a testnet first. Deploy a test contract and use test tokens to verify your flow before going live.
- Log the signed payloads for debugging. Include the nonce, amount, and timestamp so you can trace what went wrong.
- Consider batching. If your agent makes many small payments, look for a batching mechanism in x402 to reduce gas costs.
Troubleshooting
- Signature verification fails. Check that you’re using the same signing scheme (e.g., EIP-712 or personal_sign) as the protocol. Also verify the payload is byte-for-byte identical to what you signed.
- Payment is rejected as “insufficient”. The payee may require a minimum amount. Read the 402 response body—it often includes the required amount. Adjust your signed amount accordingly.
- Nonce already used. If you’re retrying a request, generate a new nonce. Don’t reuse the old one.
- Expired payload. If the request takes too long, the signature may expire. Increase the expiration time or regenerate the payload.
- Token not accepted. The payee might only accept a specific token (e.g., USDC). Check the API’s documentation for the accepted token address.
- Smart contract reverts. If the claim transaction fails, it could be due to insufficient allowance. The payer must approve the contract to spend the token. Use
approve()before sending the request.
Frequently Asked Questions
- What does x402 stand for? It’s a reference to HTTP 402 Payment Required, the status code that signals a payment is needed. The protocol uses that code as a challenge-response mechanism.
- Do I need a smart contract to use x402? Yes, typically. The protocol relies on a contract to hold and transfer funds. However, some implementations may use a simpler pull-payment model without a custom contract.
- Can I use x402 with any blockchain? The protocol is EVM-compatible, so it works with Ethereum, Polygon, and other EVM chains. For non-EVM chains, you’d need a bridge or a different implementation.
- How do I prevent double-spending? The nonce and expiration in the signed payload prevent replay. The payee checks both before processing.
- What happens if the API fails after I’ve paid? The payment is only settled after the API responds. If the API fails, the payee doesn’t claim the funds, so you’re not charged. If the API claims but returns an error, that’s a dispute—check the protocol’s dispute resolution.
- Is x402 only for AI agents? No, but it’s designed for machine-to-machine payments. Any automated client that needs to pay for API access can use it.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.