Set up the x402 payment layer

Building pay-per-api 402 infrastructure starts by replacing traditional API keys with machine-to-machine crypto payments. The x402 standard revives the HTTP 402 "Payment Required" status code, allowing agents to pay for data or compute on demand without manual intervention. This shifts the paradigm from static authentication to dynamic, transactional access.

Follow these steps to integrate the x402 protocol into your Web3 agent stack.

1
Select a compatible wallet provider

Your agent needs a programmable wallet to hold funds and sign transactions. Choose a provider that supports the specific blockchain network your API targets (e.g., Ethereum, Solana, or a Layer 2 like Base). Ensure the wallet can handle small, frequent micro-transactions efficiently. Coinbase is a primary architect behind x402, so their ecosystem tools are a reliable starting point.

2
Configure x402 middleware

Install the x402 middleware package in your API server. This layer intercepts incoming requests. If the request lacks a valid payment signature or sufficient balance, the middleware returns a 402 status code instead of the data. Configure the pricing logic here—whether per-request, per-token, or per-compute-unit—and link it to your wallet’s balance.

3
Test the 402 response flow

Before launching, simulate the payment cycle. Send a request without a signature to verify the 402 response. Then, send a request with a signed payment transaction. Confirm that the agent receives the data only after the transaction is confirmed on-chain. This ensures your pay-per-api 402 infrastructure handles both payment failures and successes gracefully.

Configure per-request billing logic

To build a functional pay-per-api 402 infrastructure, your API endpoints must enforce payment before granting access. The core mechanism is straightforward: if a request lacks a valid payment proof, the server returns a 402 Payment Required status. This forces the client—typically a Web3 agent—to attach a transaction before retrying.

1. Detect missing payment proofs

Every incoming request should first check for a valid cryptographic signature or on-chain transaction hash. If the request header or body does not contain proof of a completed micro-transaction, the endpoint immediately rejects the call. This check happens before any business logic executes, ensuring you never process data for unpaid requests.

2. Return 402 Payment Required

When payment is missing, respond with HTTP 402. While historically reserved for future payment systems, this code is now the standard for API monetization. It signals to the agent that access is blocked until payment is settled. Avoid using 403 Forbidden or 401 Unauthorized, as those imply authentication issues, not billing ones.

3. Process USDC or stablecoin payments

When the agent retries with payment, your backend must verify the transaction on-chain. For USDC, this means checking the ERC-20 transfer event to ensure the exact amount reached your designated wallet address. Once verified, grant access to the requested resource. This flow creates a seamless loop where payment and access are tightly coupled.

4. Handle edge cases and retries

Agents may retry quickly after payment. Implement idempotency keys to prevent double-charging for the same logical request. Additionally, set a short expiration window for the payment proof. If the transaction is confirmed but the request arrives too late, the agent must initiate a new payment cycle. This keeps your billing logic clean and predictable.

Prevent runaway agent loops

Infinite loops are the fastest way to drain a wallet and burn through API credits. When an AI agent enters a retry cycle or fails to parse a response correctly, it can hammer an endpoint thousands of times in seconds. The pay-per-api 402 infrastructure stops this bleed by enforcing hard budget caps at the protocol level.

The mechanism is simple: if no payment is attached, the API returns a 402 Payment Required status on every request. You pay per query in USDC or stablecoins. No API keys to manage, no credit limits to guess at. The transaction itself is the authorization. If the wallet balance hits zero, the loop stops instantly because the next request cannot be settled.

To implement this, you need a wallet that enforces these caps natively. Tools like Ampersend allow you to set maximum spend limits per session or per agent identity. This ensures that even if an agent misbehaves, the damage is contained within a predefined budget. The wallet rejects any transaction exceeding the limit before it even reaches the network, providing a hard stop that software-level retries cannot guarantee.

  • Set a maximum spend limit per agent session
  • Implement strict retry limits with exponential backoff
  • Use a budget-enforcing wallet like Ampersend to lock funds
  • Monitor 402 responses as a signal to pause or terminate the agent

This approach shifts the risk from the developer to the protocol. You are no longer responsible for debugging infinite loops in real-time; the financial constraint does the work for you. By tying execution to payment, you ensure that every API call has a cost, and every cost has a limit.

Choose the right payment tools

Building a pay-per-api 402 infrastructure requires picking components that handle micro-transactions without introducing latency or friction. You need wallets that support smart contract wallets and middleware that can intercept HTTP 402 responses to trigger payments. The goal is to make the payment invisible to the user while ensuring the agent pays exactly what is owed.

Wallets for agent identity

Your agents need a wallet to hold funds and sign transactions. Standard EOAs (Externally Owned Accounts) are often too expensive for micro-payments due to gas costs. Instead, use smart contract wallets like Safe or Privy. These allow for account abstraction, meaning you can batch transactions or pay gas in stablecoins. This reduces the cost per request and simplifies the agent's identity management.

Middleware for payment routing

Middleware sits between your API and the blockchain. It listens for requests and checks for payment. If the payment is missing, it returns a 402 status code. If payment is present, it routes the request to your backend. Tools like SatGate or Edge & Node provide this layer. They handle the complexity of verifying signatures and settling payments in USDC or other stablecoins.

Example Setup

Here is a simple example of how the middleware might look:

JavaScript
if (!isPaid(request)) {
  return new Response('Payment Required', { status: 402 });
}

This ensures that only paid requests are processed. The middleware handles the rest.

Pay-per-api 402 infrastructure: common: what to check next

Before you deploy payment logic, it helps to clarify how the 402 status code functions in modern agent workflows. While HTTP/1.1 reserved 402 for future payment systems, today it serves as the handshake between Web3 agents and monetized data sources.