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.
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.
| Protocol | Settlement Layer | Primary Token | Finality | Agent Support |
|---|---|---|---|---|
| x402 | Base / Ethereum | USDC | Near-instant (L2) | CoinGecko, AgentCash |
| L402 | Bitcoin Lightning | BTC | Seconds (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.
As an Amazon Associate, we may earn from qualifying purchases.
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.




No comments yet. Be the first to share your thoughts!