How the 402 payment flow works

Traditional API access relies on keys and subscriptions. You get a token, and the server checks it against a database. If the key is valid, you proceed. This model works for monthly plans, but it breaks down for micropayments because the overhead of authentication is too high for fractions of a cent.

HTTP 402 changes this by making payment part of the protocol itself. The server responds with a 402 Payment Required status code instead of granting access. This status code is reserved for payments, distinguishing it from standard client errors like 401 (Unauthorized) or 403 (Forbidden).

In an x402 implementation, this flow is explicit. The server sends the 402 response along with a payment instruction. The client—whether a human app or an AI agent—processes the payment via a crypto wallet and then retries the request. No API keys, no monthly subscriptions, and no minimum transaction amounts. It is a programmable, low-cost system that works as naturally for an HTTP request as it does for a payment.

This approach removes the friction of account creation and billing cycles. You pay only for what you use, and the payment happens at the exact moment the resource is requested.

Set up the payment gateway

Integrating a payment provider that supports x402 or similar micropayment protocols requires linking your API logic to a crypto wallet. The goal is to handle the HTTP 402 challenge: when a client requests a paid endpoint, the server returns a 402 status with a payment request, the client pays via a crypto transaction, and the server verifies the payment before granting access.

1. Choose an x402-compatible payment processor

Start by selecting a payment gateway that natively supports the x402 protocol. Unlike traditional processors that rely on API keys and monthly subscriptions, x402 gateways handle on-chain verification. Look for providers that offer SDKs for your preferred language (Node.js, Python, Go) and support common cryptocurrencies like USDC or ETH for low-fee microtransactions.

2. Configure your API endpoints

Modify your API routes to check for payment before executing logic. For unprotected endpoints, keep them public. For paid endpoints, implement middleware that intercepts the request. If the request does not include a valid payment proof, return an HTTP 402 status code. Include the payment challenge in the response headers or body, specifying the amount, currency, and wallet address required for settlement.

3. Integrate wallet verification logic

When the client retries the request, they will include a payment proof (usually a transaction hash or signature). Your server must verify this proof. Connect to the relevant blockchain network to confirm the transaction was received by your wallet and matches the amount requested. Ensure you handle edge cases like pending transactions or insufficient gas fees to prevent false negatives.

4. Handle retries and error states

Micropayments can fail due to network congestion or user error. Implement a robust retry mechanism that allows clients to resend the payment proof after a short delay. If verification fails, return a clear 402 error with instructions on how to proceed. Avoid rate-limiting the 402 responses too aggressively, as this can block legitimate payment retries.

5. Test with a sandbox environment

Before going live, use a testnet or sandbox environment provided by your payment gateway. Simulate various scenarios: successful payments, failed transactions, and expired challenges. Verify that your API correctly transitions between locked and unlocked states. This step ensures that your infrastructure can handle real-world traffic without losing revenue or exposing data.

Pay-Per-API 402
1
Select a payment processor

Choose a gateway that supports x402 and offers SDKs for your stack.

2
Configure API endpoints

Add middleware to return 402 status codes for unpaid requests.

3
Integrate verification logic

Verify blockchain transactions against your wallet address.

4
Handle retries and errors

Implement robust retry mechanisms for failed or pending payments.

5
Test with sandbox

Simulate success, failure, and edge cases on testnet.

Comparing x402 and L402 protocols

Choosing between x402 and L402 comes down to whether you want a protocol that focuses on payment mechanics or one that focuses on access control. Both use the HTTP 402 status code, but they solve different problems in your infrastructure.

x402 is an open protocol designed to make payments native to HTTP. It leverages the long-dormant 402 "Payment Required" status code to create a simple, direct flow: the server requests payment, the client pays via a crypto wallet, and the request proceeds. This approach is ideal for straightforward micropayments where the primary goal is collecting fees for each call without complex subscription logic [src-serp-8].

L402, by contrast, is often deployed as a paid rail around authority decisions. Tools like SatGate use L402 to enforce scope, budget, and payment limits before an API endpoint is even reached. This makes it better suited for enterprise scenarios where you need to manage usage quotas, prevent overages, and integrate payment enforcement into your existing identity and access management systems [src-serp-5].

Feature Comparison

The table below breaks down the key differences to help you decide which fits your use case.

Featurex402L402
Primary FocusNative HTTP paymentsAuthority & access control
Payment FlowDirect client-to-serverEnforced via gateway/proxy
Best ForMicropayments & simple feesQuota management & enterprise
ComplexityLow (protocol-level)Medium (infrastructure-level)

Recommendation

If you are building a service where users pay per request for specific data or compute power, x402 offers the simplest path to implementation. It removes the need for API keys or monthly billing cycles, making it highly programmable for AI agents and lightweight clients.

However, if you are managing a high-volume API with tiered pricing, usage limits, or need to integrate with existing corporate identity providers, L402 provides the necessary infrastructure to enforce those rules. It acts as a gatekeeper, ensuring that payment and permission checks happen consistently across all endpoints.

Test the pay-per-call endpoint

Before you ship, you need to prove the money moves correctly. A broken payment flow means broken data. Follow this sequence to verify your 402 endpoint handles the challenge, processes the payment, and serves the content.

Pay-Per-API 402
1
Send the initial request

Start with a standard HTTP GET or POST to your protected endpoint. Since the user hasn't paid yet, your server must respond with a 402 Payment Required status code. This response is the handshake. It should include a Payment-Uri header pointing to your payment processor and a Payment-Required header defining the exact amount and currency (usually in wei) needed to use the data.

2
Execute the payment transaction

Use a wallet tool or your frontend script to send the exact amount specified in the headers to the provided Payment-Uri. This is where you verify the crypto transaction logic. Ensure the transaction is broadcasted to the network and that the amount matches the challenge exactly. If the amount is wrong or the URI is invalid, the retry will fail.

3
Retry with the payment proof

Once the transaction is confirmed, your client must retry the original request. This time, include the Authorization header containing the transaction hash or payment proof. Your server needs to validate this proof against the blockchain or payment provider. If the proof is valid, the server should return a 200 OK with the requested data.

4
Verify the response payload

Check the body of the 200 OK response. Does it contain the expected data? If you are testing a JSON API, ensure the JSON structure is valid. This step confirms that the payment gate didn't just process money, but actually unlocked the correct resource. If you get a 200 with empty data, your routing is broken.

A working flow looks like this:

  • Server returns 402 with payment headers
  • Wallet sends exact wei amount
  • Client retries with Authorization header
  • Server returns 200 OK with data

If any step fails, check your server logs. The most common issue is a mismatch between the amount in the Payment-Required header and the actual transaction sent. Keep the amounts precise.

Common implementation mistakes

Building a pay-per-API system requires precise error handling. The 402 Payment Required status code is not a generic failure; it is a specific signal that content is gated behind a payment wall. When you misconfigure this logic, you risk trapping users in loops or leaking data. Here are the most frequent pitfalls developers encounter when integrating micropayment infrastructure.

Infinite retry loops

The most dangerous bug in 402 flows is the retry loop. If your client code treats a 402 response as a transient network error, it will immediately retry the request. The server sees the unpaid request again and returns 402 again. This cycle repeats until the client’s rate limiter kicks in or the user’s device crashes.

To break this cycle, you must treat 402 as a final, terminal state for that specific request. Stop the retry logic immediately and redirect the user to a payment interface. Never retry an unpaid request without a successful payment token.

Incorrect status code handling

Developers often default to 401 (Unauthorized) or 403 (Forbidden) for payment issues. This is a semantic error. A 401 implies the user needs to log in. A 403 implies they are logged in but lack permission. A 402 explicitly states that access is available if the user pays.

Using the wrong code breaks automation. Payment gateways and API clients rely on HTTP standards to trigger specific workflows. If you return 403 for a payment wall, automated bots may attempt to authenticate rather than pay, causing your system to reject valid transactions. Stick to 402 for paywalls, as noted in the HTTP specification.

Missing payment metadata

A 402 response should not just be a status line; it needs context. If you do not include payment instructions in the response body, the client has no way to know how to pay. This is especially critical for programmatic clients like AI agents, which cannot open a browser window to click "Pay."

Include a Link header or a JSON body that specifies the payment URI, the exact amount, and the accepted currencies. Without this metadata, the client receives a 402 but cannot complete the transaction, leading to user frustration and abandoned requests.

Ignoring idempotency

Micropayments often involve small, frequent transactions. If a client retries a payment request due to a timeout, you might charge the user twice. This is a severe bug that damages trust and increases chargeback risks.

Always implement idempotency keys for payment requests. If the client sends the same payment key twice, your server should recognize it and return the original success response without charging the user again. This ensures that network glitches do not result in double billing.

Frequently asked questions about 402