What HTTP 402 means for agents

HTTP 402 (Payment Required) is a reserved status code that signals a server needs payment before fulfilling a request. For AI agents, it replaces traditional API keys with a direct payment flow. Agents pay first, then access the data.

The x402 protocol extends this standard for machine-to-machine transactions. Instead of managing secret keys, agents handle micropayments via crypto. This shift supports agentic workflows by enabling instant, per-request billing. You pay only for what you use, with no upfront subscriptions.

This model is essential for high-stakes infrastructure. It enforces strict budget caps and improves security by removing shared secrets. Agents can execute tasks without waiting for human approval, provided they have sufficient funds. The protocol ensures that payment and access are tightly coupled.

Set up the x402 payment server

Before you can charge for AI agent calls, you need a server that intercepts requests and responds with a 402 status code. This isn't just an error; it's a price tag. The x402 protocol requires your server to return the current price in the response headers so the agent knows exactly what it costs to proceed.

This setup involves installing the middleware, configuring your wallet, and defining which endpoints are paid. We will walk through these steps in order. If you skip the security checks, you risk draining your wallet or exposing your API to free-riders.

The Pay-Per-API 402
1
Install the x402 middleware

Start by adding the x402 package to your project. This middleware handles the heavy lifting of validating payments and injecting the required 402 headers. Run npm install x402 in your terminal. This ensures your server can speak the protocol that AI agents are already built to understand.

2
Configure your payment wallet

Next, connect a wallet that can receive payments. The x402 protocol typically uses blockchain-based wallets for micro-transactions. Set your private key or API credentials in your environment variables. Never hardcode these secrets. Ensure the wallet has enough balance to cover any gas fees if you are acting as a relay, though typically you just receive the funds.

The Pay-Per-API 402
3
Define priced endpoints

Now, attach the middleware to your specific API routes. You must define the price for each endpoint. This can be a fixed amount or a dynamic value based on token usage. For example, a simple text generation call might cost $0.01, while a complex reasoning task costs $0.10. The server will return a 402 status with the price in the Pay header if the user hasn't paid yet.

4
Test with a dummy agent

Finally, verify your setup using a test agent or a simple HTTP client. Send a request to your new endpoint. You should receive a 402 response with a Pay header containing the price and payment instructions. If you send the required payment in the next request, the server should return 200 OK with the actual data. This confirms the loop is closed.

Configure agent payment logic

When your AI agent requests an API endpoint, the server doesn't just return data—it returns a bill. The x402 protocol embeds pricing directly into the HTTP 402 response. Your agent must parse this response, approve the transaction, and resend the request to use the content.

This process happens in milliseconds, but it requires precise configuration. If the logic fails, the agent stalls. If it’s too loose, your budget drains. Here is how to wire the detection, payment, and retry loop securely.

The Pay-Per-API 402
1
Detect the 402 status code

Standard HTTP clients ignore 402 responses by default. You must configure your agent’s fetch wrapper to treat 402 as a valid, actionable state rather than an error. When the response arrives, check for the x-api-requirement header. This header contains the signed price request and the payment instructions. If this header is missing, the API likely does not support x402.

The Pay-Per-API 402
2
Parse the price and validate budget

Extract the price and currency fields from the header. Before signing anything, compare this against your agent’s configured budget cap. If the price exceeds your limit, abort the request immediately. Never allow an agent to pay without a hard stop; a single runaway loop can drain a wallet in seconds.

3
Sign and send the USDC transaction

Use your configured wallet library (such as AgentCash) to sign the payment transaction. The transaction must include the exact payment hash provided in the 402 response. Once signed, broadcast the transaction to the blockchain. Wait for a single block confirmation to ensure the payment is valid before proceeding. Speed matters, but finality is mandatory.

4
Resend the original request

The payment alone does not deliver the data. You must resend the exact original HTTP request. This time, include the x-payment-hash header with the transaction ID from the previous step. The API server verifies the hash against the blockchain. If it matches, the server returns the actual data in a standard 200 OK response.

Always implement a maximum payment threshold in your agent’s configuration. Without a cap, a compromised agent or a malicious API provider can drain funds. Treat every 402 response as untrusted input until verified.

Subscription vs. pay-per-request: which fits your budget?

Traditional API pricing usually locks you into a monthly subscription or a seat-based license. This model works well for predictable, steady traffic, but it becomes expensive when your AI agents are idle or usage is irregular. You pay for the capacity you might need, not the work you actually do.

Pay-per-request (402) flips this logic. You only pay when an agent successfully completes a task. This is critical for budget control in high-stakes environments where unpredictable spikes can blow through fixed monthly caps. As noted by Tangle, pay-per-request is the better choice when usage is irregular and each request has a clear value.

Use the table below to see how the models compare across cost, predictability, and suitability for autonomous agents.

ModelCost StructurePredictabilityBest For Agents
Monthly SubscriptionFixed fee regardless of usageHigh (known monthly bill)Low (waste during idle times)
Seat-Based LicensePer user/team memberMedium (depends on team size)Very Low (agents are not humans)
Pay-Per-Request (402)Per successful transactionVariable (scales with demand)High (aligns cost with value)

Test your implementation safely

Before you let agents loose, verify the payment flow doesn't drain your wallet or hang on infinite loops. A broken payment loop is the fastest way to lose your budget.

1
Set a hard budget cap

Configure your agent's wallet with a strict daily or per-session limit. This is your safety net. If the payment logic fails, the agent stops spending once it hits the cap rather than running up an unlimited bill.

2
Simulate with micro-transactions

Run a test cycle using the smallest possible unit (e.g., satoshis or wei). Verify that the API returns a 200 OK only after the payment is confirmed. If it returns 200 without payment, your gate is broken.

3
Check for infinite retry loops

Force a payment failure (e.g., insufficient funds) and watch the agent's behavior. It should back off and retry later, not hammer the API repeatedly. Monitor your logs to ensure the retry logic respects exponential backoff.

Common x402 integration: what to check next

When building AI agents that rely on the HTTP 402 protocol, developers often hit the same snags. Here are the answers to the most frequent technical questions about latency, currency, and errors.