Set up the x402 protocol

The x402 protocol activates the dormant HTTP 402 status code as a live payment rail. Instead of guessing costs, your agent sees the exact price in every response before it pays. This setup gives you a Pay-Per-API 402 infrastructure where value moves instantly via USDC micropayments.

Install the middleware

Start by adding the x402 middleware to your existing API gateway. This layer intercepts requests and manages the payment handshake. You can use official libraries like x402-js or x402-go depending on your backend language.

The middleware acts as a gatekeeper. It checks for a valid payment signature before passing the request to your business logic. If the payment fails, it returns a 402 status with the current price, allowing the agent to retry with funds.

Configure the payment gateway

Connect your middleware to a USDC-compatible wallet. The protocol requires a wallet address to receive payments and a signing key to verify transactions. You can use any EVM-compatible wallet, but ensure it has enough gas for the transaction.

Set your pricing strategy in the configuration file. You can define a fixed rate per request or a dynamic rate based on compute usage. The x402 protocol includes the current price in every 402 response, so your agent always sees the updated cost before paying.

Verify the integration

Test the setup with a simple curl request or a basic agent script. Send a request to your API endpoint and observe the 402 response. If the middleware is working, you should see a payment request with the specified price.

Once the payment is confirmed on-chain, the middleware grants access to the API. You can monitor transactions on a block explorer to ensure payments are flowing correctly. This verification step is crucial for debugging any payment failures early in the development cycle.

Key takeaways

  • Install the x402 middleware to intercept requests and manage payments.
  • Connect to a USDC wallet to receive micropayments.
  • Define your pricing strategy in the configuration file.
  • Test with a simple request to verify the 402 handshake.

Define endpoint pricing logic

To build a working Pay-Per-API 402 system, you must attach specific costs to your endpoints. The x402 protocol requires that every 402 response includes the current price, allowing agents to see the cost before they pay. Without this metadata, agents cannot make informed decisions about whether to proceed.

1. Set base rates in your router

Start by defining the cost for each endpoint in your server configuration. Whether you use a flat rate per call or a dynamic model based on token usage, the price must be explicit. For example, a simple /translate endpoint might cost 0.01 USD per request, while a heavy /generate-image endpoint could cost 0.50 USD. Store these values in a central configuration file or database so they are easy to update without redeploying your entire service.

2. Embed price in the 402 response

When an unauthenticated or unpaid request hits your server, return a 402 Payment Required status code. Crucially, you must include the price in the response headers or body. The x402 standard suggests using a x-payment-required header or a JSON body with a price field. This allows the agent to parse the cost and prepare the transaction. If you omit this data, the agent will receive a generic error and cannot proceed with payment.

3. Validate payment before execution

Once the agent sends payment, your server must verify the transaction on-chain. Use a payment verification library to check that the required amount has been sent to your specified wallet address. If the payment is confirmed, return a 200 OK status with the requested data. If the payment is missing or insufficient, return the 402 again with the updated price metadata. This loop ensures that only paid requests are processed.

4. Handle edge cases and retries

Agents may retry requests if they receive a 402. Ensure your pricing logic is idempotent, meaning the price doesn’t change drastically between retries unless market conditions shift. If you are using dynamic pricing, update the price in the 402 response to reflect the current rate. This prevents agents from paying a lower price for a service that has since become more expensive. Always log these interactions for auditing purposes.

Handle payment verification flows

When your client sends a request to a pay-per-API endpoint, the server doesn't just return data; it returns a gate. The HTTP 402 status code serves as a clear signal that access is restricted until payment is settled. For agentic workflows, this isn't an error to suppress—it's a transaction trigger.

Handling this flow requires a structured client-side wrapper. You need to detect the 402, pause execution, process the payment, and then retry the original request without the user noticing the friction. This approach keeps your API logic clean and your billing accurate.

1
Detect the 402 Payment Required status

Start by wrapping your standard fetch or axios calls in a retry handler. When the response status is 402, do not throw an error immediately. Instead, flag the request as paymentRequired. This allows your application to distinguish between a network failure (5xx/4xx) and a billing block (402). As noted by MDN, this code is specifically reserved for payment scenarios, making it a reliable signal for your logic.

2
Execute the payment transaction

Once the 402 is caught, pause the request queue and initiate your payment gateway. This step varies based on your infrastructure (Stripe, PayPal, or on-chain smart contracts). The goal is to tokenize the transaction for the specific API resource or credit bundle requested. Ensure you capture the payment receipt or transaction hash, as this will be needed for the retry header or authorization token.

3
Retry the original request

With payment confirmed, you must re-send the exact request that triggered the 402. Do not make a new request; the original payload contains the necessary context. Attach the payment confirmation token to the request headers (e.g., X-Payment-Receipt). Most pay-per-API gateways will validate this token and return the 200 OK response with the data you originally sought.

Here is a conceptual wrapper demonstrating this flow in a standard JavaScript environment:

JavaScript
async function fetchWithPayment(url, options) {
  let response = await fetch(url, options);

  // Step 1: Detect 402
  if (response.status === 402) {
    // Step 2: Execute payment
    const paymentToken = await processPayment();

    // Step 3: Retry with payment token
    const retryOptions = {
      ...options,
      headers: {
        ...options.headers,
        'X-Payment-Token': paymentToken
      }
    };
    response = await fetch(url, retryOptions);
  }

  return response;
}

This pattern ensures that your agentic workflows remain uninterrupted. By treating the 402 as a standard part of the request lifecycle rather than an exception, you build a robust system that handles billing seamlessly in the background.

Choose the right pricing model for your API

Deciding how to charge for API access isn't just about picking a number; it's about aligning your billing structure with how developers actually use your service. Traditional subscription or seat-based models work well when usage is predictable and consistent. However, they often force users to pay for capacity they don't need or hit hard walls when they do.

Pay-per-API 402 shifts this dynamic by charging strictly for what is consumed. This model eliminates the friction of account management and billing infrastructure, making it ideal for sporadic usage or machine-to-machine interactions where volume fluctuates wildly. When you compare the economics, the choice becomes clear based on your user's behavior.

Pricing Model Comparison

The table below breaks down the structural differences between the three dominant approaches. Notice how the cost structure changes from fixed overhead to variable consumption.

ModelCost StructureBest ForUser Risk
SubscriptionFixed monthly feePredictable, high-volume usagePaying for unused capacity
Seat-BasedPer-user monthly feeInternal tools, SaaS dashboardsScaling costs linearly with team size
Pay-Per-API 402Per-request chargeSporadic, M2M, or bursty trafficUnpredictable monthly bills if unmonitored

When Pay-Per-API 402 Wins

The pay-per-call model was once the dominant standard, often priced at fractions of a cent per request. While simple, it has largely been replaced or augmented by more nuanced models for specific use cases. Pay-per-API 402 is superior when your users are agents or scripts that run intermittently. In these scenarios, a subscription feels like wasted money, and seat-based pricing doesn't apply because there are no human users to license.

If your API serves as a backend utility for other applications, the per-request model ensures you get paid exactly when value is delivered. It removes the barrier to entry for small developers who can't commit to a monthly retainer. However, you must implement robust monitoring on your end, as the lack of a cap means users can accidentally generate significant costs if their code enters a loop.

Avoid common integration mistakes

A 402 response is a hard stop. If your retry logic treats it like a transient network glitch, you’ll burn through credits or trigger rate limits unnecessarily. The HTTP 402 status code—"Payment Required"—was originally designed as a placeholder for a micropayment layer that never fully materialized, but today it serves as a precise signal that billing onboarding is incomplete or a subscription limit has been hit. Treat it as a business logic error, not a network error.

1. Don’t Retry Automatically

When you receive a 402, immediate retrying is the most common mistake. Unlike a 500 or 503 error, a 402 will not resolve itself. It means the API provider is explicitly blocking the request until payment or provisioning is resolved. Retrying will only increase your load and potentially flag your account for suspicious activity. Stop the request loop immediately and surface the error to your user or backend workflow.

2. Verify Billing Onboarding First

Before integrating the API, ensure your application has completed the billing onboarding process. Many providers, such as Microsoft Graph API, will return a 402 if the subscription limits aren’t evaluated or if the payment method isn’t linked. Check your provider’s dashboard to confirm that your account status is active and that you have a valid payment method on file. This step prevents the "payment required" error from appearing in production.

3. Handle Errors Gracefully

Build error handling that distinguishes between a 402 and other status codes. Your code should catch the 402 specifically and trigger a payment flow or a user notification, rather than falling back to a generic error handler. This keeps the user experience smooth and ensures that revenue isn’t lost due to poor error management. Always log the specific error code for debugging purposes, but don’t expose raw HTTP codes to the end user.

4. Test with Sandbox Keys

Use sandbox or test keys to simulate payment failures before going live. This allows you to verify that your error handling logic works as expected without risking real money. Test both successful payments and failed attempts to ensure your system can recover gracefully. This practice helps you identify potential issues with your retry logic and billing integration early in the development cycle.

Deploy and monitor transactions

Getting your Pay-Per-API 402 infrastructure live requires balancing immediate revenue capture with long-term stability. You aren't just turning on a switch; you're opening a payment rail that needs constant monitoring to prevent revenue leakage.

1
Configure webhook listeners

Set up endpoints to receive real-time payment confirmations. Your system must acknowledge these signals to grant API access. Without reliable webhooks, you risk granting service before payment settles.

2
Implement retry logic for failed requests

Network glitches happen. Configure your client to retry failed 402 responses with exponential backoff. This ensures legitimate users aren't locked out by temporary infrastructure hiccups.

3
Set up transaction monitoring dashboards

Track success rates and latency in real-time. You need to see drops in payment confirmation immediately. Use these metrics to identify if a specific wallet provider or blockchain is experiencing congestion.

4
Test with micro-transactions

Before going live, run small test transactions across different networks. Verify that your payment proofs are correctly generated and accepted by your API gateways. This step catches edge cases in signature verification.