How to implement HTTP 402 Pay-Per-API
HTTP 402 Payment Required is an HTTP status code indicating that access to a resource is blocked until the client makes a payment. In Web3, it enables pay-per-API models where cryptocurrency is exchanged for data access without traditional subscriptions or API keys. This guide details the integration steps, pricing models, and verification logic required to build a functional 402 endpoint.
1. Set up a crypto wallet for transactions
You cannot use a credit card or Stripe key for native 402 implementation. You need a self-custody wallet capable of holding the specific cryptocurrency your provider accepts (usually ETH, SOL, or USDC). Configure your backend to sign transactions automatically when a payment is required.
2. Implement the payment verification loop
The 402 status code is a signal, not a payment processor. When your API returns 402 Payment Required, it includes a Payment-URI header. Your client must:
- Parse the
Payment-URIfrom the header. - Execute the payment transaction to that address.
- Wait for blockchain confirmation.
- Resend the original API request with the transaction hash or proof of payment.
If you skip the verification step, your client will retry the request indefinitely without ever proving payment.
3. Calculate pricing based on volume
Don't guess your costs. Use one of these four models to set your rates:
- Transaction volume: Charge per API call.
- Data volume: Charge per gigabyte processed.
- User-centric: Charge per active monthly user.
- Revenue share: Take a percentage of the end-user's transaction.
4. Test with a sandbox environment
Never test 402 flows on mainnet first. Use a testnet or a provider's sandbox (like Nansen's x402 testing environment) to verify that your wallet signs correctly and your client handles the retry logic. If the verification fails, your users will face latency and failed requests.
Implementing 402 payment required logic
HTTP 402 Payment Required was originally reserved for future use, but the Web3 developer community has reclaimed it to enable pay-per-API transactions. Instead of managing subscriptions or API keys, your endpoint returns a 402 status with a payment instruction. The client pays the specified amount in cryptocurrency, receives the resource, and proceeds. This shift turns every API call into a direct microtransaction.
1. Define your pricing model
Before writing code, decide how you will charge for access. API pricing generally falls into four buckets: transaction volume, revenue share, data volume, or user-centric models. For a 402 implementation, transaction volume is the most straightforward. You assign a fixed cost per call, such as $0.001 per request. This avoids complex metering and keeps the client-side logic simple. If your API processes heavy data, calculate costs based on gigabytes transferred rather than raw call counts.
2. Configure the 402 response header
When a client hits your endpoint without payment, do not return a standard 404 or 403. Return a 402 status code. The critical component is the header that tells the client where to send funds. According to the x402 specification, this header contains a URI pointing to a payment page or a direct wallet address. For example, Nansen and other agentic payment systems use this header to trigger automatic wallet connections. Ensure your backend dynamically generates this URI based on the requested resource’s price.
3. Integrate a crypto payment gateway
Your server needs a way to verify that the payment was actually made. You cannot rely on the client’s word. Integrate a lightweight crypto payment gateway or a Lightning Network node if you are building for low-latency micropayments. When the client submits proof of payment, your gateway confirms the transaction on-chain or via the Lightning ledger. Only then do you release the data. This step is where most implementations fail; if your verification is slow, the user experience degrades.
4. Handle payment failures and retries
Not every transaction will succeed immediately. Network congestion or insufficient funds can cause failures. Your API must handle these gracefully. If a payment is pending, return a 402 with a new, updated payment URI or a timeout duration. Do not block the client indefinitely. Provide clear error messages that indicate whether the issue is a network delay or a failed transaction. This clarity reduces support tickets and keeps developers confident in your infrastructure.
5. Test with a sandbox environment
Never test 402 logic on mainnet immediately. Use a testnet or sandbox environment that simulates the payment flow without moving real assets. Verify that the 402 header is correctly parsed by common HTTP clients. Check that your payment gateway correctly identifies the transaction hash and releases the data. Once the flow is smooth, you can move to a limited production rollout.
Common mistakes in pay-per-API 402 implementation
Even with clear HTTP 402 standards, developers often stumble on integration details. These errors usually stem from treating 402 like a generic 401 or ignoring the specific requirements of Web3 payment layers like Bitcoin Lightning.
Skipping the 402-specific error handler
Many teams reuse their 401 (Unauthorized) or 403 (Forbidden) logic for 402 responses. This is a critical mistake. While 401 and 403 are about identity and permissions, 402 is about transaction completion. If your client code doesn't explicitly listen for 402, the payment step is never triggered, and the API call fails silently or times out.
Ignoring transaction confirmation delays
In Web3-based 402 flows, such as those using the Lightning Network, the HTTP response may come before the blockchain confirms the payment. If your server treats the 402 response as the final state, you might grant access prematurely or revoke it too late. Always wait for the required number of confirmations before updating your access control list (ACL). Relying on instant finality is risky and leads to race conditions.
Hardcoding static prices
Dynamic pricing models require real-time calculation. Hardcoding prices in your API middleware ignores market volatility and changing operational costs. Instead, fetch the current rate from a reliable oracle or pricing service at the time of the request. This ensures the payment amount matches the actual cost of the resource, preventing revenue leakage or customer disputes.
Neglecting idempotency keys
Network retries are common. Without idempotency keys, a single payment attempt can result in multiple charges if the client retries due to a timeout. Always require a unique idempotency key in the request header. Your server should check for this key before processing the payment, ensuring that duplicate requests are recognized and handled gracefully without double-charging the user.
Pay-per-api 402: what to check next
Before integrating HTTP 402 into your infrastructure, it helps to separate the protocol mechanics from the business logic. The status code is the handshake; the pricing model is the strategy. Here are the practical answers to the most common objections.

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