What the 402 status code means

The HTTP 402 Payment Required status code is the server’s way of saying, "Pay before you proceed." Unlike the common 404 (Not Found) or 401 (Unauthorized) errors that most developers encounter, 402 is specifically reserved for billing. It acts as a gatekeeper, ensuring that the client has settled the micropayment before the API endpoint returns the requested data.

In traditional web development, 402 was largely ignored in favor of session tokens or pre-paid credits managed by application logic. However, the x402 protocol revives this code to enable direct, HTTP-native micropayments. Instead of relying on third-party payment processors for every single API call, the request and the payment happen in the same round-trip.

This distinction is critical for building pay-per-api systems. When a client receives a 402, it knows the issue is financial, not authentication-based. This allows the client application to trigger a payment flow—such as opening a wallet or processing a crypto transaction—and then retry the request seamlessly. By treating payment as a standard HTTP status, developers can build billing into the core of their API infrastructure rather than layering it on top.

How x402 handles machine payments

The x402 protocol turns the HTTP 402 status code into a functional payment gateway. Instead of a simple error, this response carries a signed payment request that tells the client exactly what to pay and where. This mechanism allows servers to accept micropayments directly over standard HTTP requests, enabling a pay-per-API model where machines can settle transactions without human intervention or complex API key systems.

The interaction follows a strict challenge-response cycle. Below is the step-by-step sequence that occurs during a typical pay-per-API request.

1
Client sends request

The process starts when a client application sends a standard HTTP GET or POST request to the server endpoint. At this stage, no payment has been made, and the server does not yet know if the client is authorized to access the resource.

2
Server returns 402 Challenge

If the resource requires payment, the server responds with a 402 Payment Required status code. Crucially, the response body contains a signed payment request. This request includes the amount due, the cryptocurrency or stablecoin type (like USDC), and the wallet address for payment. The signature ensures the request hasn't been tampered with.

3
Client settles payment on-chain

The client parses the challenge and initiates a transaction on the specified blockchain. It sends the required amount to the provided address. Once the transaction is broadcast, the client captures the transaction hash (TXID) to prove payment was made. This step is where the machine-to-machine payment actually occurs, leveraging blockchain immutability for trust.

4
Resource delivery

After the client resends the request, it includes the payment proof (usually the TXID or a signed receipt) in the headers or body. The server verifies the transaction on-chain or via a trusted oracle. If the payment is confirmed, the server grants access and returns the requested data with a 200 OK status code.

This cycle ensures that payment and access are tightly coupled. The server never exposes the resource until the cryptographic proof of payment is validated, and the client never pays until it receives a verifiable challenge. This structure eliminates the need for pre-funded wallets or subscription management for one-off API calls.

The elegance of x402 lies in its simplicity. It reuses existing HTTP infrastructure, meaning you don't need to build a separate payment processor or learn a new protocol. The 402 status code acts as both a gatekeeper and a payment instruction, streamlining the path from request to revenue.

Setting up your payment infrastructure

Before you can gate your API behind HTTP 402 responses, you need a working payment rail. This means choosing a wallet provider that your users already trust, handling gas fees so your users don’t hit unexpected costs, and managing token conversions so you get paid in the currency you prefer.

Think of this like setting up a cash register. You need the hardware (wallet), the float (gas), and the ability to count change (conversion). If any of these are missing, the transaction fails, and your API call returns an error.

Here is how to build that infrastructure step by step.

1
Choose a wallet provider

Pick a wallet provider that supports the chains you are using. Most developers start with MetaMask or WalletConnect because they are widely supported. Ensure your provider can handle the specific token standards (like ERC-20) you plan to accept. If you are targeting non-technical users, consider integrating a wallet abstraction service to hide the complexity.

2
Estimate and handle gas fees

Gas fees can vary wildly depending on network congestion. You need to estimate the gas cost for each API call and include it in your pricing model. Some protocols allow you to sponsor gas fees, meaning you pay for the transaction on behalf of the user. This removes friction for the user, making the API feel more like a traditional service.

3
Manage token conversions

You likely don’t want to accept every token in existence. Set up a conversion layer that accepts stablecoins or major tokens and converts them to your preferred currency or stable asset. This protects your revenue from volatility. Use a reliable oracle or exchange API to get real-time rates and ensure your API charges the correct amount based on the current market price.

4
Implement error handling

Your API must handle payment failures gracefully. If a user’s wallet is empty or they decline the transaction, return a clear 402 response with instructions on how to retry. Avoid generic error messages. Instead, provide specific guidance, such as "Insufficient ETH balance" or "Transaction rejected." This helps users fix the issue quickly without contacting support.

5
Test the full flow

Before going live, test the entire payment flow in a sandbox environment. Simulate successful payments, failed transactions, and edge cases like network congestion. Verify that your API correctly returns 402 responses when payment is required and 200 responses when payment is successful. This ensures your users have a smooth experience from start to finish.

Common integration mistakes to avoid

Even with a clear pay-per-api 402 guide, implementing the standard requires careful attention to detail. The protocol introduces new complexity to the HTTP request lifecycle, and small oversights can break the payment flow entirely. Focus on these three critical pitfalls to ensure your integration works reliably.

Improper nonce handling

Nonces are the backbone of 402 security, preventing replay attacks where a user pays once but uses the same proof repeatedly. If you generate nonces that are predictable or fail to validate them strictly on the server, attackers can reuse old payment proofs. Always generate cryptographically secure random nonces and verify that each one is used exactly once. Store the used nonces in a fast-access cache, such as Redis, to ensure your system can reject duplicates instantly without slowing down legitimate requests.

Failing to cache payment proofs

Once a client presents a valid payment proof, you shouldn't force them to pay for every single subsequent request in a short window. Caching proofs allows you to grant temporary access without re-evaluating the cryptographic signature for every call. However, this cache must have a strict expiration time tied to the nonce's validity period. If you cache indefinitely, you risk granting free access long after the payment should have expired. Conversely, if you don't cache at all, you create unnecessary latency and computational overhead for both the client and your server.

Ignoring network latency during the challenge phase

The 402 challenge-response cycle adds round-trip time to your API calls. If your client or server is slow to generate or verify the cryptographic challenge, the user experience will suffer. Don't treat the payment step as an afterthought; integrate it into your existing timeout and retry logic. Ensure your client libraries handle network failures gracefully, allowing users to retry the payment challenge without losing their place in the workflow. Test your implementation under high-latency conditions to identify bottlenecks before they impact your users.

Pricing strategies for API calls

Setting a price for your API is less about guessing a number and more about choosing a billing rhythm. With HTTP 402, you can move beyond the traditional monthly invoice and offer granular, real-time micropayments. This shift allows you to charge exactly what is used, eliminating the friction of account setup and billing reconciliation.

Subscription vs. Pay-Per-Request

The choice between a subscription model and pay-per-request often comes down to predictability versus flexibility. Subscriptions offer steady revenue but can alienate users with low volume. Pay-per-request scales with usage, ensuring users only pay for value received. HTTP 402 enables the latter by handling payment verification at the protocol level, allowing for seamless, per-call billing without complex backend infrastructure.

MetricSubscriptionPay-Per-Request (402)
Upfront CostHigh (monthly/annual fee)None (pay only when used)
ScalabilityLimited by tier capsInfinite (scales with demand)
Billing ComplexityHigh (invoices, reconciliation)Low (automatic, real-time)
User FrictionHigh (account creation)Low (instant access)

Determining the cost per call

To set a competitive price, calculate your marginal cost per request, including server time, bandwidth, and any third-party fees. Add a margin for profit and infrastructure overhead. With HTTP 402, you can adjust this price dynamically based on demand or usage patterns, offering a fair rate that reflects the actual resources consumed. This transparency builds trust and encourages higher adoption among developers who prefer transparent, usage-based pricing.

Frequently asked questions about 402