What is the x402 payment standard

x402 is an open payment standard that operationalizes the HTTP 402 status code for machine-to-machine micropayments. It allows AI agents and software clients to pay for API access on a per-request basis using USDC stablecoins, removing the friction of subscriptions and manual billing.

Historically, the HTTP 402 Payment Required status code was defined in RFC 7231 as a nonstandard response reserved for future use src-serp-2. For decades, it sat dormant, occasionally surfacing as a billing error in legacy systems but never seeing widespread adoption as a protocol.

x402 changes this by turning the 402 status code into a structured payment instruction. Instead of a generic error, the response includes a payment request that the client agent can automatically settle. This enables true pay-per-use models where AI agents can autonomously purchase tokens, data, or compute power without human intervention src-serp-5.

This approach distinguishes x402 from legacy billing errors. While traditional 402s often indicate a failed transaction or subscription lapse, x402 is a proactive mechanism for initiating micro-transactions. It transforms the HTTP protocol into a payment rail, allowing software to negotiate and settle payments in real-time.

1
Agent receives API response

The client sends a request to the API endpoint. If the resource requires payment, the server responds with an HTTP 402 status code instead of 200 OK or 401 Unauthorized.

2
Parse payment instructions

The agent parses the 402 response body, which contains structured data specifying the amount, currency (usually USDC), and the destination wallet address.

3
Execute smart contract payment

The agent signs and broadcasts a transaction to settle the payment using a connected wallet, often via a relayer or gasless meta-transaction.

4
Access granted

Once the transaction is confirmed on-chain, the agent retries the request or receives a token in the response, granting immediate access to the data or service.

Set up the payment gateway infrastructure

To implement a Pay-Per-API 402 guide effectively, you need a backend that acts as both a service provider and a payment processor. Instead of relying on traditional payment gateways, the x402 protocol allows your API to return an HTTP 402 status code with embedded payment instructions. This approach lets AI agents and clients pay directly in cryptocurrency—typically stablecoins like USDC—without leaving your server infrastructure.

The setup involves configuring your API endpoints to detect unpaid requests and respond with the necessary blockchain transaction data. Below is the step-by-step process to build this infrastructure.

1
Define your pricing model and token

Before writing code, decide which token your API will accept. USDC on Base is the current standard for x402 due to its low fees and speed. Determine your pricing structure, whether it is per-request, per-token, or based on compute time. You will need to hardcode these values into your payment response logic so the client knows exactly how much to pay.

2
Create the payment response handler

Your API must return a specific JSON structure in the body of the 402 response. This payload includes the amount to be paid, the destination wallet address, and the chainId for the network. For example, if using Base, the chainId is 8453. This data allows the client’s wallet or agent to construct a valid transaction without needing to query external block explorers.

3
Implement signature verification

To prevent fraud, you should sign the payment instructions using a private key associated with your payment wallet. The client verifies this signature to ensure the payment request is legitimate and hasn’t been tampered with. This step is critical for security, as it proves that the payment details originated from your server, not a third-party interceptor.

4
Verify on-chain transactions

Once the client submits the transaction hash, your backend must verify that the payment was actually received. You can use a lightweight blockchain indexer or a direct RPC call to check the balance of your destination wallet. Only after confirming the transaction is confirmed on-chain should you grant the client access to the API endpoint.

5
Handle edge cases and retries

Network congestion or failed transactions are common. Your infrastructure should handle timeouts and retry logic gracefully. If a payment fails verification, return the 402 response again with the same instructions. Consider adding a short expiration time to your payment requests to prevent stale transactions from being used later.

By following these steps, you create a robust infrastructure for monetizing your API. The key is keeping the payment logic simple and relying on the transparency of the blockchain for verification. This setup reduces friction for users and opens up new revenue streams for your services.

Integrate agents with x402 clients

Integrating AI agents with x402 clients transforms how models access data. Instead of manual API keys or static subscriptions, agents handle payments automatically. This process relies on a specific sequence: the agent sends a request, receives a 402 response, executes a payment, and retries to access the content.

The standard is built on the HTTP 402 Payment Required status code. When an agent encounters this response, it triggers a payment workflow. The agent then uses the payment proof to retry the request. This cycle allows for precise, per-request billing.

1
Agent sends initial request

The agent begins by sending a standard HTTP request to the API endpoint. This request includes the necessary headers and payload. The agent does not yet know if payment is required. It acts as a standard client, expecting a 200 OK response or a standard error like 404 or 500.

2
Server returns 402 Payment Required

The API server evaluates the request. If the agent lacks a subscription or payment proof, the server responds with a 402 status code. This response includes a Pay-To header. This header specifies the payment details: the recipient address, the chain ID, the token contract, and the required amount. The body may also contain instructions for the payment proof.

3
Agent executes on-chain payment

The agent parses the Pay-To header. It then initiates a transaction on the specified blockchain. The agent sends the required amount of tokens (usually USDC) to the recipient address. This step requires the agent to have a funded wallet and the ability to sign transactions. The transaction must be confirmed on-chain to generate a valid proof.

4
Agent constructs payment proof

After the transaction is confirmed, the agent generates a payment proof. This proof typically includes the transaction hash, the block number, and the recipient address. The agent formats this proof according to the API's requirements. The proof serves as cryptographic evidence that the payment was made. It ensures the server can verify the transaction without trusting the agent's claim.

5
Agent retries request with proof

The agent resends the original request. This time, it includes the payment proof in the headers (often in a Payment-Proof header). The server verifies the proof against the blockchain. If valid, the server grants access and returns the 200 OK response with the requested data. The agent now has the information it needed.

This workflow ensures that agents only pay for what they use. It removes the need for pre-funded accounts or complex subscription management. The process is transparent and verifiable on-chain.

Handle common integration errors

When integrating x402 for AI agents, the HTTP 402 status code often triggers confusion. Unlike 401 (unauthorized) or 403 (forbidden), 402 signals that payment is required to access the resource. Clients frequently misinterpret this as a permission failure or fail to parse the payment instructions embedded in the response headers. This section outlines how to debug these scenarios and ensure your agent can complete transactions smoothly.

Debugging payment instruction parsing

AI agents must be configured to recognize 402 as a transactional signal, not an error state. If the agent stops execution upon receiving 402, it will never attempt payment. Ensure your client library is set to handle 402 responses by extracting payment details from the Pay header or response body, as defined in the x402 specification. If parsing fails, log the raw response headers to verify the structure matches the expected format.

Distinguishing 402 from 401/403

Many developers assume 402 is a security block. It is not. A 401 error means the client lacks valid credentials, while 403 means the credentials are valid but lack scope. A 402 error means the credentials are valid, but the resource requires a fee. To fix this, verify that your agent is sending the correct API key or session token in the request headers. If the token is valid but the payment is missing, the 402 is correct. If the token is invalid, the server should return 401, not 402.

Handling network and proxy interference

Some intermediaries, such as corporate firewalls or outdated CDNs, may block 402 responses because they are not standard HTTP codes for general web traffic. If your agent receives a timeout or a generic 502 error instead of 402, the request may be dropped before reaching the payment gateway. Test your integration using a direct connection or a proxy that allows 402 status codes. If necessary, configure your agent to retry with a different endpoint or fallback payment method.

Evaluate market research and costs

Before launching a pay-per-API 402 implementation, you need to understand the economic friction. While the HTTP 402 status code is the signal, the actual transaction happens on-chain. This means you are dealing with gas fees, stablecoin volatility, and network congestion. If your API call costs $0.01 but the gas fee is $0.50, the model breaks.

Use this checklist to assess your cost structure before writing code.

  • Estimate per-request gas costs on your target chain (e.g., Base, Ethereum L2)
  • Model stablecoin volatility impact on micro-transactions (USDC vs. DAI)
  • Calculate minimum viable transaction threshold to avoid dust attacks
  • Review market adoption trends for 2026 (Base, Exa, AbstractAPI)

1. Analyze Gas and Network Costs

Gas fees are the silent killer of micropayments. On Ethereum mainnet, a single transaction can cost more than the API fee itself. This is why most modern x402 implementations use Layer 2 solutions like Base or Arbitrum. These networks offer sub-penny transaction fees, making $0.001 payments economically viable. You must test your specific smart contract on the testnet first to get accurate gas estimates.

2. Account for Stablecoin Volatility

Even stablecoins fluctuate. If you accept USDC, a 0.1% drop in value during the transaction window can eat your margin. For high-frequency AI agent interactions, this volatility adds up. Consider using a stablecoin with a tighter peg or implementing a dynamic pricing mechanism that adjusts the API fee based on the current exchange rate. This ensures you receive the intended value regardless of minor market shifts.

The landscape is shifting rapidly. Companies like AbstractAPI are pioneering HTTP 402 as a standard for Bitcoin Lightning micropayments, while others leverage Base for its developer-friendly infrastructure. By 2026, expect a consolidation around L2s that offer the best balance of speed and cost. Researching these trends now helps you avoid building on a chain that will be obsolete in two years.

4. Compare Implementation Options

Choosing the right infrastructure depends on your volume and technical stack. The table below compares the most common approaches for integrating pay-per-API 402.

OptionAvg. CostSpeedBest For
Ethereum Mainnet$1–$10+SlowHigh-value, low-frequency
Base (L2)<$0.01FastAI agents & micropayments
Bitcoin LightningNegligibleInstantReal-time streaming
Solana~$0.00025Very FastHigh-volume data

Pre-launch checklist for x402 APIs

Before exposing your API to agentic clients, ensure the implementation aligns with the x402 standard. This checklist covers the critical path from security to monitoring, ensuring your service is ready for automated, per-request billing.

1
Validate HTTP 402 Responses

Ensure your endpoints return the 402 Payment Required status code when payment is missing or insufficient. According to MDN, this code is reserved for future use, making x402 the de facto standard for this behavior. Verify that the response includes clear error messages and any necessary payment instructions.

2
Configure Payment Verification

Implement server-side verification for USDC payments on supported networks like Base. Use official documentation from Base to ensure your wallet addresses and transaction hashes are correctly validated. Avoid client-side-only checks, as agents can spoof headers.

3
Set Up Rate Limiting and Monitoring

Monitor API usage and payment success rates. Implement rate limiting to prevent abuse from unpaid requests. Use tools like Exa to track x402-specific metrics, such as payment latency and failed verification attempts.

4
Test with Agentic Clients

Simulate requests from AI agents using tools like Exa or custom scripts. Ensure your API handles concurrent payments and retries gracefully. Verify that the agent can successfully pay and receive data in a single flow.

Frequently asked questions about 402

This section addresses common implementation hurdles and error resolution steps for the HTTP 402 Payment Required status code.