What HTTP 402 Enables for Agentic Commerce

For decades, the HTTP 402 status code was a placeholder—a reserved slot in the protocol waiting for digital cash to become mainstream. Today, that wait is over. As AI agents begin transacting autonomously, HTTP 402 has emerged from obscurity to become the foundational standard for machine-to-machine micropayments.

This shift marks a structural change in how we build APIs. Instead of relying on bulky subscription models or manual checkout flows, your infrastructure can now respond with a 402 code that includes a precise price and a payment request. The agent receives this response, verifies the cost, and pays the required amount via a digital wallet to use the data or compute power it needs.

The mechanics are straightforward but powerful. When an agent requests an endpoint, the server evaluates the request. If the resource requires payment, the server returns a 402 status code containing the cost metadata. The agent’s payment handler then executes the transaction. Once confirmed, the agent retries the request, and the server delivers the payload. This cycle enables true pay-per-use economics for AI, where every token, image, or data point has a clear, immediate cost.

Unlike traditional billing, which often requires upfront credit card details or complex account setups, 402-based payments are frictionless for agents. They operate on a per-call basis, allowing for granular pricing strategies that align perfectly with the value delivered. This is not just a payment method; it is a new architectural pattern for the agentic web.

Set up the x402 payment gateway

To accept crypto payments via HTTP 402 responses, you need a server-side gateway that intercepts requests, evaluates them, and returns the correct status codes. This setup turns standard API endpoints into pay-per-call services without requiring traditional subscription models or API keys.

The x402 protocol extends the HTTP 402 status code, which was reserved in the HTTP/1.1 specification for digital payment systems. While rarely used historically, modern frameworks now support it for microtransactions and pay-per-use APIs.

The Pay-Per-API 402
1
Choose your payment gateway

Select a gateway that supports x402. Nansen API provides a clear implementation for agentic payments, allowing you to define priced endpoints that return 402 responses when unpaid. Other options include custom middleware using libraries like @x402/core or http-402-middleware.

The Pay-Per-API 402
2
Define your pricing structure

Map your API endpoints to specific prices. For example, a simple data query might cost $0.01, while a complex analysis could be $0.50. Store these prices in a configuration file or database. Ensure your pricing model aligns with the value provided, as noted in Stripe's API pricing guidelines.

3
Implement request interception

Create middleware that checks for payment proof on every request. If no proof is found, return an HTTP 402 status code with a Payment-Required header. This header should include instructions on how to pay, such as a payment URI or a link to a payment gateway.

4
Handle payment verification

Once a user pays, verify the transaction on the blockchain. Update your system to mark the request as paid. You can use webhooks to listen for payment confirmations and automatically grant access to the requested resource. Ensure your verification process is robust to prevent fraud.

5
Test the flow

Simulate unpaid and paid requests. Verify that unpaid requests return 402 with correct headers. Confirm that paid requests proceed to the endpoint. Test edge cases, such as expired payments or failed transactions, to ensure your gateway handles them gracefully.

This setup provides a foundation for pay-per-API services. For more detailed implementation steps, refer to the official Nansen API documentation or the YouTube walkthrough by providers who have implemented this pattern.

Structure Your Pricing Model for Agents

AI agents need to make decisions, and they make them based on data. If your API endpoint returns a 402 Payment Required status, it should also include the current price in the response headers. This allows the agent to evaluate the cost before committing to a transaction.

You have two primary ways to handle this: fixed pricing or dynamic pricing. Fixed pricing is simple but rigid. Dynamic pricing adapts to demand or compute costs but requires more infrastructure. The choice depends on how much control you want over your revenue streams versus how much complexity you want to manage.

Fixed vs. Dynamic Pricing Models

FeatureFixed PricingDynamic Pricing
Cost PredictabilityHigh for the agentVariable; depends on load
Implementation ComplexityLow; simple integer valueHigh; requires real-time calculation
Revenue OptimizationLow; static marginsHigh; captures peak demand value
Agent Decision LogicSimple threshold checkNeeds budgeting algorithms
Best ForSimple data lookupsCompute-heavy AI tasks

Implementing the Price Header

When you return a 402 status, include a X-Price header. This header should contain the amount in your chosen currency or token standard. For example, X-Price: 0.001 ETH. If the price changes based on server load, update this header in real time.

Agents will read this header and compare it against their internal budget. If the price exceeds their threshold, they will abort the request. This prevents unexpected charges and ensures your API is used efficiently. Always document these headers clearly in your API reference so developers know how to integrate them.

Calculating Costs

For fixed pricing, multiply the base rate by the number of calls. For dynamic pricing, factor in compute time, memory usage, and network latency. Use official documentation from the HTTP specification to ensure your status codes are valid. The MDN Web Docs provide a clear guide on the 402 status code, which is reserved for exactly this purpose.

Integrate Agent Wallets and Payment Flow

The Pay-Per-API 402 works best as a clear sequence: define the constraint, compare the realistic options, test the tradeoff, and choose the path with the fewest hidden costs. That order keeps the advice usable instead of decorative. After each step, pause long enough to check whether the recommendation still fits the reader's actual situation. If it depends on perfect timing, unusual access, or a best-case budget, include a simpler fallback.

1
Define the constraint
Name the space, budget, timing, or skill limit that shapes the The Pay-Per-API 402 decision.
2
Compare realistic options
Use the same criteria for each option so the tradeoff is visible.
3
Choose the practical path
Pick the option that still works after cost, maintenance, and fallback needs are included.

Troubleshoot Common Integration Errors

Even with a working wallet, API calls often fail before they reach the payment gateway. The most frequent culprits are signature mismatches, wallet connection timeouts, and quota limits. Here is how to diagnose and fix the three most common 402 Payment Required errors.

Signature Verification Failures

Most 402 errors occur because the client fails to prove ownership of the wallet address. If your signature verification fails, the server assumes you are trying to access paid content without authorization.

  1. Ensure your library (like ethers.js or viem) signs the exact payload the API expects.
  2. Verify the v, r, and s values are formatted correctly in the request headers.
  3. Check that the signing address matches the from address in your transaction.

A mismatched signature is like trying to open a door with a key that looks right but isn't cut correctly. Double-check your encoding logic against the provider's documentation.

Wallet Connectivity Issues

If the wallet connection drops or times out, the API cannot associate the request with a user account. This often happens when the user switches networks or refreshes the page unexpectedly.

  • Implement a reconnection handler to detect when the user switches networks.
  • Validate the connected wallet address before sending the API request.
  • Provide clear UI feedback if the wallet is disconnected or unsupported.

Exceeded Monthly Quotas

Some APIs return a 402 status when you hit your monthly limit, even if you have a valid payment method. This is a billing state error, not a technical one.

  • Check your provider's dashboard for usage limits.
  • Verify that your payment method is up to date.
  • Contact support if you believe this is a false positive.

As noted in discussions on Hugging Face, hitting a quota limit often triggers a 402 response rather than a 429 Too Many Requests, which can be confusing for developers expecting rate-limit errors. Always check your billing status first.

Verify Payments Before Serving Data

Never serve sensitive API data or execute high-value logic until the payment is confirmed on-chain. The HTTP 402 status code is essentially a promise: the server holds the data hostage until the client proves they paid. If you return the payload before the transaction is settled, you are giving away your product for free.

Validation is not just about checking the transaction ID. You need to verify the signature, the amount, and the network confirmations. Different protocols handle this differently. For example, the x402 protocol embeds the current price directly in the 402 response, allowing the client to see the cost before initiating the payment [1]. This transparency helps prevent disputes, but it doesn't replace the need for rigorous server-side verification.

Security Checklist

Before deploying your 402 endpoints, ensure these critical checks are in place:

  • Validate the cryptographic signature of the payment proof to ensure it originated from the claimed wallet.
  • Verify the transaction amount matches or exceeds the price specified in the 402 response headers.
  • Confirm the transaction has reached the required number of block confirmations for the specific blockchain.
  • Implement strict timeout handling to prevent hanging requests if the payment proof is invalid or missing.

[1] https://agentcash.dev/learn/pay-per-call-apis

Frequently Asked Questions About 402 Payments

The 402 status code was originally reserved for future digital payment systems MDN. Today, the x402 protocol uses it to signal that an API endpoint requires payment before returning data. This mechanism allows agents to verify the cost and complete the transaction automatically.

What is 402 payment required?

HTTP 402 Payment Required is a nonstandard status code reserved for future use. It indicates that the requested content is not available until the client makes a payment. This status code was created to enable digital cash or (micro) payment systems.

How to calculate API pricing?

Most pay-per-API models charge based on a fixed rate per request. To calculate the total cost, multiply the number of API calls by the fixed price per call. The x402 protocol simplifies this by including the current price in every 402 response, so your agent sees the updated rate before paying AgentCash.

Do I need a crypto wallet for API payments?

Yes, most 402 implementations require a compatible crypto wallet. The wallet signs the payment transaction and sends it to the API provider. This ensures secure, automated payments without manual intervention from the user.

Can I use 402 for subscription APIs?

While 402 is designed for microtransactions, it can support subscription models. However, most subscription APIs use standard authentication tokens. Use 402 for pay-per-use or metered billing where costs vary per request.