What the 402 status code means for agents

For decades, HTTP 402 "Payment Required" sat idle in the RFC specifications as a placeholder for future payment systems. Developers treated it like a ghost code—never implemented, never seen in production. That changed with the rise of agent-driven APIs. The code is no longer theoretical; it is the operational backbone of machine-to-machine micropayments.

The shift began when protocols like x402 standardized how agents handle these responses. Instead of returning a generic 403 Forbidden error when a credit card fails or an account is empty, an API gateway can now return a 402. This signal tells the agent exactly what is missing: payment. The agent can then process the transaction via Lightning Network or stablecoin and retry the request automatically.

This functionality is critical for agent-ready architectures. When an AI agent requests data, it expects a deterministic response. A 402 provides that clarity. It allows the agent to integrate payment logic directly into its workflow, enabling seamless micropayments without human intervention. This is not just a status code update; it is a fundamental change in how software negotiates value.

While major platforms like Stripe and Shopify have experimented with 402 for specific integrations, the true power lies in the decentralized ecosystem. Protocols built on top of x402 leverage this status code to create frictionless payment loops for autonomous agents.

Set up the x402 payment protocol

The x402 protocol transforms the HTTP 402 "Payment Required" status code into a functional bridge between your API and crypto wallets. Instead of relying on slow bank transfers or complex Stripe integrations, x402 enables instant, on-chain stablecoin payments directly over standard HTTP requests.

Coinbase developed this open standard to make APIs "agent-ready," allowing AI bots and automated scripts to pay for data or compute resources without human intervention. The flow is straightforward: the client requests a resource, the server responds with a 402 status containing payment details, and the client signs a USDC transaction to access the data.

To implement this, you will need a backend that can generate payment requirements and a client-side mechanism to sign and submit those payments. We will walk through the provider-side setup, which is where the core logic lives.

Pay-Per-API 402
1
Install the x402 SDK

Start by installing the official x402 library in your project. For Node.js environments, run npm install @coinbase/x402. This SDK provides the necessary utilities to parse payment requirements and construct valid transaction payloads. It abstracts the complex blockchain interactions, letting you focus on your API logic.

The Pay-Per-API 402
2
Configure the Payment Middleware

Wrap your API routes with the x402 middleware. This middleware intercepts incoming requests and checks for a valid payment signature. If no payment is present, it automatically generates a 402 response containing the price, the required USDC amount, and the wallet address for payment. This ensures that only paying clients can access your protected endpoints.

3
Define Pricing Logic

Inside your middleware configuration, define the cost per request or per token. You can set fixed rates or dynamic pricing based on usage. The middleware uses these values to calculate the exact USDC amount the client must send. Ensure your pricing logic accounts for network fees and slippage to avoid undercharging for resources.

4
Verify On-Chain Payments

Once the client signs the payment, the middleware verifies the transaction on the blockchain. It checks that the USDC was sent to your designated wallet and that the amount matches the requirement. If verification succeeds, the middleware allows the request to proceed; otherwise, it returns an error. This step is critical for security and prevents unauthorized access.

The Pay-Per-API 402
5
Test with a Sandbox Wallet

Before going live, test your integration using a sandbox wallet and testnet USDC. Use tools like the Coinbase Developer Platform to simulate transactions. This allows you to verify the entire flow—from request to payment to response—without risking real funds. Once confirmed, switch to mainnet for production use.

Price endpoints for machine consumption

When an AI agent requests an endpoint protected by the x402 protocol, the server responds with a 402 Payment Required status code. This isn't just an error; it's a structured offer. The server includes the current price in the response headers, allowing the agent to evaluate the cost before executing the transaction.

The goal is to structure this pricing data so it is machine-readable. Agents parse the headers to determine if the cost fits their budget and if the service value justifies the payment. If the agent accepts, it signs a payment proof (often a Lightning Network invoice or on-chain transaction) and retries the request with the proof attached.

To make this work reliably, you need to decide how your pricing model is structured. Static pricing is simple but inflexible. Dynamic pricing allows for real-time adjustments based on demand, latency, or resource usage. The choice between these models dictates how you format the 402 response headers and how your agent's logic handles price changes.

Static vs. Dynamic Pricing Models

Choosing the right pricing model affects how your API behaves under load and how agents interact with your endpoint. Static pricing is predictable and easy to implement, while dynamic pricing requires more complex logic but can optimize revenue and resource allocation.

ModelFlexibilityImplementationBest Use Case
StaticLowSimple header valueFixed-rate tools or subscriptions
TieredMediumRange-based headersVolume discounts for heavy users
DynamicHighReal-time calculationHigh-demand or scarce resources
Token-basedMediumCredit balance checkInternal platform economies

Verify signed USDC payments and handle errors

Once the client signs a USDC payment, your server must validate the signature before granting access. This verification step is the gatekeeper of your Pay-Per-API 402 flow. If the signature is invalid or the transaction is stuck in pending state, you must reject the request immediately.

1. Validate the transaction signature

Use a cryptographic library to verify the signature against the provided public key and the transaction hash. The signature proves that the client authorized the specific payment amount and endpoint access. If verification fails, return a 402 Payment Required with a clear error message explaining the signature mismatch.

Pay-Per-API 402
1
Extract signature and transaction data

Parse the request headers to extract the X-Payment-Signature and X-Transaction-Hash fields. Ensure these headers are present before proceeding to cryptographic verification.

2
Verify the cryptographic signature

Use your preferred crypto library (e.g., ethers.js or viem) to verify the signature. Confirm the signer address matches the expected payer and that the message hash corresponds to the payment details.

3
Check transaction status on-chain

Query the blockchain via your RPC provider to check the transaction status. For USDC payments, ensure the transaction is confirmed (e.g., 1-3 confirmations depending on your risk tolerance) and the amount matches the required fee.

2. Handle insufficient funds and failures

Not every payment will succeed. The client might have insufficient USDC balance, or the transaction might fail due to network congestion. In these cases, your API should return a 402 Payment Required with a specific error code indicating the failure reason.

  • Insufficient funds: Return 402 with a message like "Insufficient USDC balance. Please top up and retry."
  • Transaction failed: Return 402 with "Payment transaction failed. Please check your wallet and retry."
  • Network timeout: Return 504 Gateway Timeout if the blockchain query takes too long, allowing the client to retry without penalty.

This approach ensures that your API remains robust and provides clear feedback to developers integrating with your service.

Common integration mistakes to avoid

The easiest mistake with Pay-Per-API 402 is comparing options on the most visible detail while ignoring the day-to-day constraint. A choice can look strong on paper and still fail because it is too hard to maintain, too expensive to repeat, or awkward in the actual setting. Use the same checklist for every option: fit, cost, durability, timing, upkeep, and fallback plan. That keeps the comparison practical instead of drifting into preference alone.

The simplest way to use this section is to write down the real constraint first, compare each option against it, and choose the path that still works outside ideal conditions.

Frequently asked questions about 402 payments