What is pay-per-api 402

Pay-per-api 402 (x402) is an open payment standard that enables direct, per-request micropayments for API access. It repurposes the HTTP 402 Payment Required status code to create a seamless handshake between clients and servers, allowing agents to pay with USDC stablecoins on-chain before receiving a response.

Historically, the 402 status code was reserved for future use MDN. x402 activates this reserved slot, turning it into a functional payment gateway. Instead of complex OAuth flows or subscription gateways, the protocol uses the standard HTTP response cycle to enforce payment.

This model is particularly effective for AI agents and automated services that need to execute high-volume, low-cost transactions without human intervention. By integrating x402, developers can build systems where every API call is a self-contained financial transaction, ensuring immediate settlement and reducing friction for agent-to-agent interactions.

Set up the x402 payment flow

Implementing the x402 protocol requires coordinating three distinct actions: the server rejecting the request with a price, the client signing a transaction, and the server verifying the payment before serving data. This flow ensures that agents only access resources after funding is secured.

Pay-Per-API 402 in
1
Return a 402 with pricing details

When an agent requests a protected endpoint, your server must respond with an HTTP 402 status code instead of a standard 401 or 403. This response body must contain the payment requirements, including the amount due, the currency (typically USDC), and the destination wallet address. The x402 specification dictates that this price is dynamic; you can embed the current market rate or a fixed fee directly in the 402 payload so the agent knows exactly what to pay before initiating the transaction.

Pay-Per-API 402 in
2
Client signs the USDC transaction

The agent, acting as the client, receives the 402 response and parses the payment instructions. It then constructs a USDC transfer transaction to the specified wallet address. Unlike traditional web payments, this step happens on-chain. The agent uses its integrated wallet to sign the transaction, ensuring that the payment is cryptographically verified and irreversible. This signature serves as proof of intent and, once confirmed, proof of payment.

3
Server verifies the signature

Once the agent sends the transaction hash or signature back to the server, your backend must verify its validity. This step involves checking the blockchain to confirm that the USDC transfer was successful and that the amount matches the price requested in the 402 response. You can use a facilitator service or a direct blockchain RPC call to validate the transaction. If the payment is insufficient or unconfirmed, the server continues to reject the request with a new 402.

4
Serve the protected data

Only after the payment is verified should the server return the requested data with a 200 OK status. At this point, the agent has fulfilled its financial obligation, and the resource is unlocked. To prevent repeated payments for the same request, you may implement caching or token-based session management, but the core x402 loop is complete: request, pay, verify, serve.

This sequence creates a trustless payment loop. By embedding the price in the 402 response, you allow agents to make informed decisions, while the on-chain verification ensures you receive payment before delivering value. For more details on the protocol specification, refer to the AgentCash documentation.

Choose your payment rail and token

Your infrastructure choice dictates how agents handle latency, currency volatility, and transaction finality. The two primary open standards for pay-per-API are x402 (Coinbase/AgentCash) and L402 (Abstract). Both use the HTTP 402 status code, but they operate on different settlement layers.

Compare x402 and L402 providers

The table below breaks down the technical differences between the leading implementations. Select the rail that matches your agent's latency requirements and preferred asset class.

ProtocolSettlement LayerPrimary TokenFinalityAgent Support
x402Base / EthereumUSDCNear-instant (L2)CoinGecko, AgentCash
L402Bitcoin LightningBTCSeconds (Lightning)Abstract, Lightning Labs

Select the right token

Your token choice is a trade-off between stability and decentralization. Most enterprise AI agents prefer USDC because it removes price volatility from the pricing equation. Agents can cache prices reliably without worrying that a 5% BTC swing will break their budget.

If you are building a decentralized or censorship-resistant service, BTC via Lightning is the only option. However, you must implement dynamic pricing logic that updates every time the agent requests data, as the dollar value of BTC changes constantly. For most utility APIs, USDC on Base or Ethereum L2s offers the smoothest developer experience.

Handle pricing and agent errors

Even with x402 handling the heavy lifting of signing and verification, your API logic still needs to manage state carefully. If you don't validate the incoming payment context correctly, you risk stale pricing, signature failures, or agents burning through budgets unexpectedly. Here is how to harden your implementation against the most common pitfalls.

Verify signature and nonce integrity

Never trust the payload without validating the signature and ensuring the nonce is fresh. A replay attack is the easiest way to drain an agent's budget or bypass pricing. Check that the x-402-signature matches the payload and that the nonce has not been seen before in your database. If the signature is invalid or the nonce is reused, reject the request immediately with a clear error. This step is non-negotiable for security.

Validate price timestamps

Prices change. If an agent cached a price quote from ten minutes ago but the current rate has spiked, you need to handle that discrepancy. Always check the priceTimestamp in the payment context against your current pricing logic. If the timestamp is too old, reject the request and return a fresh 402 with the updated price. This prevents agents from exploiting stale quotes and ensures you are paid the correct amount for the current market rate.

Enforce agent budget caps

Agents operate on budgets, and those budgets can run out mid-session. If an agent's available balance is insufficient for the requested operation, fail the request early. Do not let the agent complete the work only to find out they can't pay. Check the availableBalance in the payment context before processing the request. If the balance is too low, return a 402 with a specific error message indicating the shortfall, allowing the agent or user to top up.

Ensure idempotency

Network failures happen. If an agent retries a request after a timeout, you might process the same payment twice. Use the nonce as an idempotency key. If you receive a request with a nonce you have already processed, return the previous response without re-executing the logic. This protects both your API from duplicate charges and the agent from double-spending.

Frequently asked questions about pay-per-API 402