What the 402 status code means

Pay-Per-API 402 works best as a clear sequence: define the constraint, compare the realistic options, test the tradeoff, and choose the path with the fewest hidden costs. That order keeps the advice usable instead of decorative. After each step, pause long enough to check whether the recommendation still fits the reader's actual situation. If it depends on perfect timing, unusual access, or a best-case budget, include a simpler fallback.

The simplest way to use this section is to write down the real constraint first, compare each option against it, and choose the path that still works outside ideal conditions.

Configure your x402 payment server

Setting up an x402 payment server involves configuring your API endpoints to recognize when a client has not yet paid and responding with a specific HTTP 402 status code. Unlike standard APIs that return 400 or 401 errors for invalid requests, x402 uses 402 to signal that payment is required to proceed. This approach enables machine-to-machine micropayments without the friction of traditional API keys or subscription gateways.

The x402 protocol is an HTTP-native micropayment standard that leverages the 402 Payment Required status code to facilitate direct, on-chain transactions. By implementing this, your API can accept payments in stablecoins like USDC directly within the HTTP response cycle. This eliminates the need for complex authentication flows, allowing clients to pay only for the data or services they actually consume.

Pay-Per-API 402
1
Install the x402 middleware

Begin by integrating the x402 middleware into your existing server framework. Whether you are using Node.js, Python, or Go, the library handles the cryptographic verification of payments. This middleware acts as a gatekeeper, intercepting incoming requests before they reach your business logic. It checks for valid payment proofs attached to the request headers.

2
Define payment requirements for endpoints

Next, configure which endpoints require payment and set the corresponding price. You define these rules in your server configuration, mapping specific routes to their costs in your chosen stablecoin. For example, a high-frequency data feed might cost $0.01 per request, while a bulk export could be $0.50. This granularity allows you to monetize different tiers of access precisely.

3
Configure the 402 response logic

When a request arrives without a valid payment, your server must respond with an HTTP 402 status code. This response includes a payment instruction payload, often containing a QR code or a payment link for the client to complete the transaction. The payload also includes the payment proof required for subsequent requests. This ensures that the client can retry the request immediately after paying.

4
Verify payment proofs on retry

After the client pays, they include a cryptographic proof in the header of their next request. Your middleware verifies this proof against the blockchain or the designated payment channel. If the proof is valid, the server processes the request and returns the data with a standard 200 OK status. If the proof is invalid or expired, the server returns 402 again, prompting another payment.

By following these steps, you create a seamless pay-per-use model that aligns costs with usage. This method is particularly effective for high-volume, low-cost API calls where traditional billing systems would be inefficient. The x402 protocol simplifies the financial infrastructure, allowing developers to focus on delivering value rather than managing subscriptions.

Handle payment verification logic

Once the client receives the 402 Payment Required response, the real work begins. You cannot simply trust the client’s word that they have paid; you must verify the transaction on-chain before releasing the resource. In high-stakes finance, a single gap in this logic can lead to unauthorized access or financial loss.

The verification process follows a strict sequence. First, extract the payment proof from the Authorization header or the x-payment-proof header specified in the Paywall header of the 402 response. This proof usually contains the transaction hash, the sender’s address, and the signature.

Next, validate the transaction details against the blockchain state. Check the following:

  • Sender matches: The sender of the transaction must match the client’s wallet address or the identity specified in the request.
  • Amount is correct: The transferred amount must equal or exceed the price quoted in the Paywall header. Remember that API A might charge 5 sats while API B charges 3, so exact matching is critical.
  • Destination is correct: The funds must have been sent to the API provider’s designated wallet address.
  • Confirmations are sufficient: Depending on the blockchain’s finality, ensure the transaction has enough block confirmations to be considered irreversible.

Only after these checks pass should you serve the requested data. If any check fails, return a 402 Payment Required error again, possibly with a more specific reason code.

This logic ensures that only verified payments unlock access, maintaining the integrity of your API’s revenue model.

Avoid common integration mistakes

When building with x402, the margin for error is thin. A single misconfigured header or unchecked signature can leave your API exposed or your users stranded. Below are the most frequent pitfalls and how to sidestep them.

Skipping signature verification

Never trust a payment signature without validation. The core security model of x402 relies on verifying that the payment proof actually belongs to the requester and matches the request parameters. If you skip this step, you’re not building a payment API; you’re building a free service that happens to accept crypto.

Always verify the signature against the expected public key and ensure the payment data aligns with the specific API call being made. This prevents replay attacks where a user reuses an old signature for a new request.

Poor error handling

HTTP 402 is not a standard status code in many legacy frameworks, which can lead to unexpected behavior if not handled explicitly. If your server returns a 402 without a proper JSON body or clear instructions, clients will struggle to understand why the request failed.

Provide a structured error response that includes the required payment fields. This allows the client to seamlessly prompt the user for payment without breaking the flow. Treat the 402 response as a structured instruction, not just an error.

Ignoring idempotency

In high-stakes financial contexts, network retries are common. If your API processes the same payment multiple times because it doesn’t check for duplicate transactions, you risk double-charging users or processing the same action twice.

Implement idempotency keys to ensure that each unique payment proof is processed only once. Store these keys and check them against incoming requests to maintain data integrity and user trust.

Frequently asked questions about 402

Understanding the 402 status code is essential for building reliable payment-gated APIs. Below are the most common questions developers ask when implementing x402 and Pay-Per-API models.