Why HTTP 402 Matters for AI Agents

HTTP 402 Payment Required, originally reserved in 1997, now serves as the foundation for machine-to-machine payments via the x402 initiative. This standard enables automated, pay-per-call APIs where AI agents can verify authority, manage budgets, and enforce policies directly through the HTTP response. Instead of relying on external billing portals, the payment happens at the point of access, allowing agents to operate autonomously.

This shift allows agents to pay for a single API call, receive the response, and move on. This micro-transaction model is essential for scalable AI infrastructure, where every request needs to be accounted for and compensated instantly.

Set up the x402 payment gateway

To build a pay-per-api 402 infrastructure, you need a gateway that intercepts requests and checks for payment before granting access. Unlike traditional APIs that rely on static API keys, x402 uses the HTTP 402 "Payment Required" status code to negotiate payments on the fly. This allows AI agents to pay with stablecoins without creating accounts or managing subscriptions.

We will configure a middleware layer that validates these payments. This approach ensures that every API call is backed by a successful transaction before your server processes the logic.

pay-per-api 402 infrastructure
1
Install the x402 middleware package

Start by adding the x402 library to your project. This package provides the core functions for handling payment verification. Run npm install x402 in your project directory to get the necessary dependencies. This middleware will sit between your incoming requests and your business logic.

2
Configure the payment verification function

Create a verification function that checks the Authorization header for valid payment proofs. x402 expects a specific format where the agent includes proof of payment in the request header. Your middleware must parse this header and call the verification logic to ensure the transaction is valid on the blockchain.

3
Integrate the middleware into your server

Attach the x402 middleware to your API routes. For routes that require payment, the middleware will automatically return a 402 status if no payment is detected. If the payment is valid, it passes the request through to your handler. This creates a seamless pay-per-api 402 infrastructure where access is strictly tied to payment.

4
Test the payment flow locally

Use a local wallet to simulate an AI agent making a request. Send a request without payment to verify you receive a 402 response. Then, send a request with a valid payment proof to ensure your server processes it correctly. This step confirms your gateway is ready for autonomous agents.

Handling the 402 response and nonce

The core of a pay-per-API 402 infrastructure relies on a specific handshake. When an AI agent requests a resource that requires payment, the API doesn't just return an error. It returns a 402 Payment Required status code along with a payment nonce. This nonce is the key that grants access once the payment is settled.

Think of the nonce as a time-limited invoice. The API generates a unique cryptographic proof that specifies the price and the payment method. The client must pay this invoice to retrieve the actual data. This flow ensures that payment happens in real-time, before the agent spends compute on processing the response.

pay-per-api 402 infrastructure
1
1. The API returns a 402 with a nonce

The API endpoint responds with a 402 Payment Required status. Crucially, the response body contains a payment nonce. This nonce is a structured object (often JSON-LD or similar) that includes the price, the currency (usually a stablecoin like USDC), and the destination wallet address. It acts as a signed request for payment.

2
2. The client parses the payment instructions

The AI agent's client library intercepts the 402 response. It parses the nonce to understand exactly what is being asked for. The client validates the nonce's signature to ensure it hasn't been tampered with and checks that the price matches the agent's budget. If the price is too high, the agent can abort the request immediately, saving gas and compute.

pay-per-api 402 infrastructure
3
3. The client executes the payment

Using a wallet integration, the client signs and broadcasts a transaction to pay the specified amount to the destination address. This is typically done via a lightweight payment protocol like x402 or MPP (Micropayment Payment Protocol) to minimize fees. The transaction must be confirmed on-chain or within the payment layer's consensus mechanism.

4
4. The API verifies and releases the resource

Once the payment is verified, the API acknowledges the transaction. It then re-processes the original request, this time granting access. The agent receives the actual data payload in a 200 OK response. This ensures that only paying clients get the final result, creating a closed-loop payment system for AI services.

This flow transforms the HTTP protocol into a payment rail. By embedding payment instructions directly in the 402 response, you eliminate the need for separate billing APIs or subscription management layers. The payment is tied directly to the resource access, making it ideal for high-frequency, low-cost AI agent interactions.

Stop replay attacks with nonce validation

In a pay-per-api 402 infrastructure, security isn't just about encryption; it's about ensuring that a single payment covers exactly one execution. Without strict controls, a malicious agent (or a glitched client) could capture a valid payment response and replay it thousands of times, draining your funds or abusing your compute.

The core defense is the nonce. A nonce is a unique, single-use number included in both the payment request and the API call. When your server receives a request, it checks the nonce against a record of previously used values. If that nonce has already been processed, the request is rejected immediately. This mechanism ensures that even if a payment token is intercepted, it cannot be reused.

Implementing this requires two steps on the server side:

  1. Generate and store the nonce: When issuing a payment instruction, generate a cryptographically random nonce and store its hash in a fast-access database (like Redis) with a TTL (time-to-live).
  2. Verify on execution: Before executing the API logic, check if the nonce from the incoming request exists in your store. If it does, delete it immediately and reject the request. If it doesn't, proceed with the API call and mark the nonce as "used" to prevent future replays.

This approach aligns with modern payment protocols like x402, which treat each payment as a discrete, atomic transaction. By binding the payment strictly to a single, verified execution, you eliminate the risk of infinite loops and ensure your 402 infrastructure remains financially secure.

Validate your pay-per-api 402 infrastructure

Before routing real traffic, run through this checklist to ensure your pay-per-api 402 infrastructure handles payments and data delivery correctly. This validation prevents failed transactions and ensures your agents can seamlessly interact with payment-gated endpoints.

1
Test the 402 Response Loop

Send a request to a known x402 endpoint without payment. Verify the server returns an HTTP 402 status with a valid Paywall header containing the payment URI. This confirms your agent correctly identifies the payment requirement before attempting a transaction.

2
Verify Instant USDC Settlement

Execute a test transaction using a USDC-compatible wallet. Confirm the payment is processed instantly and the API access is granted without manual intervention. Check that the payment proof is correctly attached to subsequent requests, ensuring no duplicate charges occur.

3
Check Error Handling and Fallbacks

Simulate failed payments or insufficient funds. Ensure your infrastructure gracefully handles errors without exposing sensitive wallet data or crashing the agent. Verify that the agent retries or alerts appropriately rather than looping indefinitely on failed payment attempts.

4
Validate Header Compliance

Review the response headers against the x402 specification to ensure full compatibility. Incorrect headers can cause other agents or gateways to reject your API. Confirm that the Paywall header format matches the open standard for internet-native payments.

Frequently asked questions about x402

Here are direct answers to common questions about building a pay-per-API 402 infrastructure for AI agents.