What HTTP 402 Enables for APIs

The HTTP 402 status code was originally reserved for future payment systems. Today, it serves as the foundation for the x402 protocol, allowing APIs to replace traditional subscription models with instant, pay-per-use access. Instead of requiring an API key or a recurring billing cycle, endpoints now return a 402 Payment Required response when a request lacks payment.

This shift eliminates the friction of account creation and long-term commitments. Developers can build keyless endpoints where any wallet can interact with the API. The process is straightforward: a client POSTs to a pass route, receives the 402 response with payment details, and gains access once the transaction is verified. This model aligns costs directly with usage, making it ideal for high-volume or unpredictable API traffic.

Set Up the Payment Gateway

Before you can accept x402 payments, you need a gateway that understands the 402 status code and can process USDC transactions. Unlike traditional payment processors that rely on credit card networks, x402 operates directly on the blockchain. This means your setup is lighter, but it requires specific configuration to handle the "paywall" logic correctly.

The core of this setup is integrating a wallet provider that supports USDC on a compatible chain (like Base or Polygon) and configuring your server to return a 402 Payment Required response when a request is made without a valid payment proof.

1
Choose a USDC-compatible blockchain

x402 is chain-agnostic, but you need to pick one for your payment flow. Most developers choose Base or Polygon for their low fees and fast finality. Ensure your chosen chain supports the USDC token standard you intend to use. This decision dictates where your payment gateway will listen for transactions.

2
Integrate a wallet provider

You need a way to generate wallet addresses for your API users and verify their balances. Services like Privy, Web3Auth, or a direct integration with a provider like Laevitas can handle this. The goal is to get a public address where clients can send their USDC payments. Laevitas API V2 offers a straightforward way to test this flow by POSTing to a pass route, which returns the necessary 402 instructions.

3
Configure your server for 402 responses

Your API endpoints must be programmed to intercept requests that lack a valid x402 payment proof. When such a request arrives, your server should return an HTTP 402 Payment Required status code. This response should include a JSON body with payment instructions, such as the recipient address, the amount due in USDC, and a unique transaction ID or reference. This tells the client exactly what to pay to gain access.

4
Set up payment verification logic

Once a client claims to have paid, your server needs to verify it. This involves listening for the transaction on the blockchain or using a block explorer API to confirm that the USDC transfer has reached your gateway address. Only after verification should you grant access to the requested API data. This step is critical to prevent fraud and ensure you are actually receiving payment.

With the gateway configured, your API is ready to enforce pay-per-use rules. The next step is to test this flow to ensure the 402 responses and payment verifications work as expected before launching to users.

Define Endpoint Pricing and Limits

You need to set clear costs and caps before your API goes live. Without specific numbers, you risk either leaving money on the table or scaring away users with vague charges. The goal is to make the price transparent so clients know exactly what a single request costs.

Set Per-Request Costs

Start by assigning a fixed USDC amount to each endpoint. Simple endpoints like health checks should cost near zero, while data-heavy operations like complex queries need a higher rate. This aligns cost with resource usage. If you are unsure where to start, look at transaction volume and data volume as primary drivers for your pricing tiers.

Configure Rate Limits

Pricing alone doesn't stop abuse. You must pair it with rate limits to prevent a single user from draining your server resources. Set a maximum number of requests per minute or hour. This ensures fair access for everyone and protects your infrastructure from sudden spikes in traffic.

Choose Your Pricing Model

Different APIs benefit from different structures. Use the table below to decide which model fits your use case.

Pricing ModelBest ForSetup ComplexityUser Predictability
Per-RequestVariable usage, sporadic callsLowHigh
Bundled CreditsPredictable, high-volume usersMediumMedium
Tiered SubscriptionSteady, high-frequency accessHighLow

Test the 402 Response Flow

Testing a pay-per-API integration is a loop, not a straight line. You send a request, hit the 402 wall, pay, and retry. If you skip the retry, you get nothing. If you skip the payment, you get a 402.

Here is the exact sequence to verify your x402 implementation works end-to-end.

1
Send the initial API request

Start by sending a standard HTTP GET request to your x402-enabled endpoint. Do not include any payment credentials yet. You are testing the server's ability to recognize the lack of payment and respond with the correct status code. You should receive an HTTP 402 Payment Required response. This confirms the endpoint is active and enforcing the paywall. The response body often contains metadata about the required payment, such as the amount due and the wallet address.

2
Extract payment details

Parse the 402 response to find the payment instructions. Look for the Payment-Required header or the body payload, which typically specifies the amount (e.g., 0.01 USDC) and the destination wallet address. If the server does not provide clear instructions, your client cannot proceed. Ensure your code captures these details accurately before moving to the transaction step.

3
Execute the crypto payment

Use your wallet SDK to sign and broadcast a transaction to the specified address. The amount must match the request exactly. If you are testing on a testnet, use testnet tokens. Wait for the transaction to be confirmed on-chain. This step is the bridge between the API and the blockchain; if the transaction fails or is too slow, the subsequent API call will also fail.

4
Retry the API request with proof

Once the payment is confirmed, send a second request to the same endpoint. This time, include the payment proof in the headers (usually a signature or transaction hash). The server will verify the payment against the blockchain. If valid, it returns HTTP 200 OK with the requested data. If you retry without the proof, you get another 402. If the proof is invalid, you may get a 403 Forbidden or 400 Bad Request.

This loop ensures your client handles failures gracefully. Most bugs happen in the retry logic or in parsing the 402 response. Test both success and failure cases to build a robust integration.

Common Integration Errors

Even with a solid x402 implementation, payment verification can fail. Most issues stem from simple configuration mismatches rather than complex code bugs. Here are the three most frequent errors developers encounter and how to fix them.

Incorrect Wallet Addresses

The most common error is a mismatch between the wallet address the client signs with and the address the server expects. If the addresses differ by even one character, the signature verification fails silently or throws a generic error. Always log the expected address and the signed payload’s recovered address side-by-side during development. This makes mismatches immediately obvious.

Timeout Handling During Payment Verification

Blockchain transactions are not instant. If your server times out while waiting for a transaction confirmation, it may reject a valid payment. Set your verification logic to poll the blockchain for a reasonable window (e.g., 30–60 seconds) before returning a 402 error. This prevents false negatives for slow network conditions. Do not rely on immediate block inclusion as a success signal.

Missing or Malformed Headers

x402 relies on specific HTTP headers to convey payment intent. If the Authorization or Pay headers are missing, malformed, or contain invalid JSON, the server cannot parse the payment proof. Validate header presence and structure before attempting signature verification. Return a clear 400 Bad Request error if headers are invalid, reserving 402 for actual payment failures.

Final checklist before launch

Before you open the gates to public traffic, run through this sequence. A single misconfigured endpoint can drain your wallet or expose sensitive data.

  • Verify the 402 response: Confirm that unauthenticated requests return 402 Payment Required with clear USDC instructions, not a generic 404 or 500 error.
  • Test payment flow: Use a testnet wallet to send a small USDC payment and ensure the endpoint grants access immediately upon confirmation.
  • Check pricing logic: Validate that your pricing tiers match the intended rates. A zero-value price or a decimal error can break your revenue model.
  • Review rate limits: Ensure your server can handle burst traffic without crashing. Start with conservative limits and scale up as you monitor usage.
  • Audit security headers: Verify that your API does not leak internal IP addresses or sensitive headers in error responses.

Once these steps are green, your x402 integration is ready for the real world.

Frequently asked: what to check next