What the 402 code means for APIs
HTTP 402 is no longer a dormant status code. While the Mozilla Developer Network officially lists it as reserved for "future use," the rise of autonomous agents has turned it into the standard for machine-to-machine micropayments.
In a Pay-Per-API 402 guide context, this distinction matters. Traditional billing relies on credit cards and subscription portals tailored for humans. The 402 status code, however, enables agents to negotiate, pay, and access resources in real-time. This shift supports the x402 protocol, which treats payment as a native part of the HTTP request lifecycle rather than an external accounting step.
By adopting 402, you are building infrastructure that speaks the language of autonomous agents. It moves payment from a friction point to a seamless, automated function.
Set up the x402 payment flow
Implementing the x402 protocol requires building a specific handshake between your API and the client. Unlike standard authentication, this flow uses the HTTP 402 status code to signal that payment is required before the payload is delivered. The process relies on a challenge-response cycle where the server proves its identity and price, and the client proves payment before the request is retried.
1. Configure the Server to Return 402
Your API endpoint must detect when a request arrives without valid payment credentials. Instead of returning a 401 Unauthorized or 403 Forbidden, it should return a 402 Payment Required status. This response must include a Pay header containing a challenge. This challenge typically includes the price, a nonce, and a signature from the server to prove it is the legitimate endpoint. The client reads this header to understand exactly what is owed and to whom.
2. Client Generates a Payment Proof
Upon receiving the 402 response, the client extracts the challenge and the price from the Pay header. It then constructs a payment proof, which usually involves signing the challenge with the client's private key. This signature serves as cryptographic proof that the client has authorized the payment. The client prepares this proof to be sent back in the next request, ensuring that the payment is tied specifically to the resource being requested.
3. Send the Signed Request
The client resends the original API request, this time including the payment proof in the headers. This step is critical because the server needs to verify that the payment corresponds to the exact challenge it issued. By linking the payment to the specific nonce and price, you prevent replay attacks where a user might try to reuse a payment signature for a different request or at a later time.
4. Server Verifies and Delivers
The server receives the retried request and validates the payment proof. It checks the signature against the known public keys or payment addresses to ensure the funds are valid. If the verification passes, the server treats the request as authenticated and returns the 200 OK status with the requested data. If the signature is invalid or the payment has expired, the server rejects the request again, closing the loop.
Subscription vs. Pay-Per-Request (402)
Choosing between a flat monthly subscription and pay-per-request (402) micropayments usually comes down to your usage predictability. Subscriptions offer budget stability for high-volume, steady traffic, but they can become expensive for sporadic or low-volume use. Pay-per-request models, powered by the x402 protocol, charge only for what you actually use, making them economically viable for variable workloads.
The x402 standard introduces a challenge-response mechanism where the API returns a 402 Payment Required status with a payment request. This allows for seamless, machine-to-machine micropayments without the friction of traditional billing cycles. For developers building AI agents or automated services that run intermittently, this granular billing model often aligns better with actual costs than a fixed monthly fee.
To help you decide, compare the core differences below:
| Feature | Subscription | Pay-Per-Request (402) |
|---|---|---|
| Cost Structure | Fixed monthly fee | Per-request micropayment |
| Best For | High, predictable volume | Low or sporadic volume |
| User Friction | Low after setup | Medium (requires wallet) |
| Agent Compatibility | Low (manual billing) | High (automated) |
If your API calls are consistent and high-volume, a subscription might save you money. However, if your usage fluctuates or your agents operate on an on-demand basis, the pay-per-request model eliminates waste. The key is to audit your historical request volume before committing to a long-term contract.
Fix common 402 errors and integration failures
Even with a working x402 wallet, things break. Your API might return a 402 when it should return 200, or your client might fail to attach the payment proof. This section covers the most frequent integration errors and how to resolve them.
Missing or invalid payment proof
The most common cause of a 402 is a malformed or missing Payment header. The x402 protocol expects a specific structure: Payment: macaroon=...; signature=.... If your client sends a standard Authorization header or no header at all, the API correctly rejects it.
Check your request logs. Ensure the Payment header is present and contains valid base64-encoded macaroons. If using a library like x402-js, verify that sign() is called before fetch().
Wallet connectivity issues
If your wallet isn't connected, the client cannot sign the payment proof. This often looks like a generic network error rather than a 402. However, some APIs may return a 402 with a message like "No valid payment proof" if the signature is empty.
Verify your wallet provider is active. For MetaMask or wallet connect integrations, ensure the user has approved the transaction. If testing locally, confirm your local node is syncing with the blockchain.
Incorrect gas limits or fees
x402 relies on on-chain transactions. If the gas limit is too low, the transaction fails, and the payment proof is invalid. This results in a 402 response because the API cannot verify the payment.
Check your gas estimation. Ensure your client calculates the gas limit based on the current network congestion. If using a testnet, verify that you have test tokens to cover the fees.
Pre-launch checklist
Before going live, run through this list to catch issues early:
-
Verify wallet connectivity and user approval flows
-
Test payment proof generation with a mock API
-
Check gas limit calculations for mainnet and testnet
-
Validate signature verification on the server side
-
Monitor logs for malformed Payment headers
-
Verify wallet connectivity and user approval flows
-
Test payment proof generation with a mock API
-
Check gas limit calculations for mainnet and testnet
-
Validate signature verification on the server side
-
Monitor logs for malformed Payment headers
Debugging tips
Use a tool like curl to test your API directly. Send a request with a valid Payment header and check the response. If you get a 402, inspect the server logs for the specific error reason. Common reasons include expired macaroons, invalid signatures, or insufficient funds.
Refer to the x402 protocol documentation for the latest spec on header formats and error codes. For general HTTP status code guidance, consult the MDN Web Docs.

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