What HTTP 402 Means for API Billing

The HTTP 402 Payment Required status code was originally reserved for future use in early web protocol drafts. For decades, it sat dormant while the web relied on 200 OK for successful requests and 401/403 for authentication failures. That has changed. Today, 402 is the standard signal for machine-to-machine micropayments, specifically designed for agentic workflows where human billing interfaces are irrelevant.

Unlike human-facing billing, which typically involves subscriptions or invoice-based accounting, agentic payment flows require instant, programmatic settlement. When an AI agent or automated script requests data, it doesn't fill out a credit card form. It expects a protocol-level response that indicates payment is needed before content delivery. This is where 402 shifts from a theoretical placeholder to a functional payment gateway signal.

Current implementations, such as the x402 protocol, treat 402 as a direct request for cryptographic or fiat payment to use the API response. This distinction is critical for infrastructure engineers: 402 is not an error in the traditional sense. It is a payment prompt. Clients must be built to recognize this status code, process the required payment, and retry the request automatically, creating a seamless pay-per-API loop without human intervention.

Configure the 402 payment endpoint

To build agentic payment flows, your API server must return an HTTP 402 status code instead of the standard 401 or 403 when a request lacks payment. This status code is specifically reserved for payment scenarios, signaling to the client that access is granted only after the required transaction is completed.

The configuration involves two main steps: defining the pricing logic and embedding metadata in the response headers. This allows agents to read the price before initiating a payment, ensuring they don't spend funds on unknown or excessive costs.

Pay-Per-API 402 in
1
Define your pricing structure

Before handling requests, establish how you will calculate the cost per call. This could be a fixed rate per API invocation or a dynamic rate based on resource usage. The x402 protocol requires the current price to be included in every 402 response, so your server must have a reliable source for this data. For example, if you are using a pay-per-call model, ensure your backend can accurately track and bill each request.

2
Return the 402 status code

When an unauthenticated or unpaid request hits your payment-gated endpoint, respond with HTTP/1.1 402 Payment Required. Unlike a 401, which prompts for credentials, a 402 explicitly requests payment. This distinction is critical for agentic workflows, as agents are programmed to recognize 402 as a payment barrier rather than an authentication failure.

3
Embed pricing metadata in headers

Include the price and currency information in the response headers. A common practice is to use a custom header like X-Price or Paywall-Price to specify the amount and currency (e.g., 100 sats). This allows the agent to parse the cost programmatically before deciding whether to proceed with the transaction. The protocol documentation suggests that this metadata enables agents to compare costs across different services dynamically.

4
Implement payment verification logic

Once the payment is made, your server must verify the transaction and grant access. This typically involves checking the blockchain for the incoming payment or querying your payment gateway. After verification, you should issue a token or session ID that the agent can use for subsequent requests, avoiding repeated payment checks for the same session.

Compare pricing models for API calls

Choosing a billing structure for agentic payments isn't just about accounting; it's about matching the cost to the agent's behavior. Agents don't read invoices. They react to HTTP responses. If your pricing model forces an agent to fetch a dashboard to check its balance, you've created friction that breaks automation.

The three dominant models for API billing—pay-per-call, subscription, and seat-based—serve different architectural needs. Pay-per-call aligns cost directly with usage, making it ideal for variable workloads. Subscription models provide predictable costs for steady-state operations but can become expensive during spikes. Seat-based pricing is less common for pure API access but useful when the "seat" represents a unique agent identity or workspace.

Use the comparison below to decide which model fits your API's latency and volume requirements.

ModelCost StructureBest ForAgent Friction
Seat-BasedFee per unique agent IDMulti-tenant platformsHigh (requires identity management)

Pay-per-call is the most natural fit for the 402 protocol. Each request triggers a payment check, and the agent proceeds only after the transaction clears. This creates a tight coupling between action and cost, ensuring you never pay for unused capacity. However, it requires robust rate limiting to prevent cost explosions during loops.

Subscription models work well if your agents make a consistent number of calls per month. The challenge is handling overages. If an agent exceeds its quota, you must decide whether to throttle requests or charge additional fees. This decision needs to be encoded in your API logic, not left to manual intervention.

Seat-based pricing is relevant if your API supports multiple distinct agents operating under a single account. Here, the "seat" is the agent's unique identifier. This model simplifies billing for platforms but adds complexity to identity management. You must ensure each agent has a stable, verifiable ID to prevent billing fraud.

Handle payment failures and retries

Even with robust infrastructure, financial flows encounter friction. Insufficient funds, network timeouts, and expired authentication tokens are not bugs; they are expected states in high-stakes agentic payments. Your retry logic must distinguish between a transient glitch and a hard failure to avoid draining user wallets or triggering rate limits.

Distinguish Transient vs. Permanent Errors

Not all failures warrant a retry. A 402 Payment Required error typically indicates a permanent account state (insufficient funds or expired subscription) rather than a network hiccup. Retrying a 402 error immediately will fail again and potentially incur additional costs if your API provider charges per request.

Implement a check for the 402 status code before entering any retry loop. If you receive a 402, stop immediately and prompt the user or agent to update payment methods. Do not waste compute cycles on exponential backoff for these errors.

Implement Exponential Backoff for Network Errors

For transient errors like 503 Service Unavailable or 429 Too Many Requests, use exponential backoff. This strategy waits progressively longer between retries, giving servers time to recover and preventing your agent from overwhelming the API.

Start with a short delay (e.g., 100ms) and double it for each subsequent attempt. Cap the maximum number of retries (e.g., 3-5) and the maximum wait time (e.g., 30 seconds). This ensures your agent remains responsive without hanging indefinitely.

Handle Expired Tokens Gracefully

Authentication tokens expire. When a token expires, the API usually returns a 401 Unauthorized error. Instead of failing the entire transaction, your agent should refresh the token using your preferred OAuth flow and retry the original request once.

If the token refresh fails, or if the second attempt still returns 401, treat this as a permanent failure. Log the error clearly and alert the operator. Never attempt to refresh tokens repeatedly in a tight loop, as this can lock out accounts or trigger security flags.

Log and Alert on Hard Failures

When all retries are exhausted, log the full context: the endpoint, the payload, the error code, and the retry count. This data is critical for debugging and for improving your retry logic over time. Set up alerts for high-frequency failures to detect issues before they impact a large number of users.

Verify transactions before serving data

Never serve content based on an unverified signal. In a pay-per-API flow, the 402 response is a promise, not a payment. Your agent must cryptographically verify the transaction hash or signature before extracting the payload from the response body. If you skip this step, your service becomes an open faucet, draining your resources to bots that never intend to pay.

The x402 protocol standardizes this verification by including the current price and transaction details in the 402 response itself. This allows the client to see exactly what it is paying for before executing the transaction, but the server must still confirm that the payment actually reached the wallet. You are essentially acting as a gatekeeper who checks the ticket stub before letting the guest in.

  1. Extract the transaction hash: The 402 response should include a txHash or similar identifier in the headers or body. This is the unique fingerprint of the payment on the blockchain. If this is missing, the payment is invalid.

  2. Query the blockchain: Use a blockchain explorer or indexer to check the status of that hash. Look for a confirmed status and ensure the amount matches the price listed in the 402 response. Do not trust the client-side claim; trust the chain.

  3. Validate the signature: If using a signature-based approach (like EIP-712), verify that the signature was issued by the wallet address that owns the funds. This prevents replay attacks where a user reuses an old payment signature.

  4. Serve the payload: Only after the transaction is confirmed and the signature is valid should you return the API data. If any step fails, return a 402 with a clear error message and the updated price.

Frequently asked questions about 402 billing

Understanding the mechanics of HTTP 402 is essential for building agentic payment flows. Developers often confuse this status code with standard authentication errors or generic payment gateways. This section clarifies how 402 functions in protocol design and how to calculate costs for automated systems.