Implementing HTTP 402 Micropayments for Agent-to-Agent APIs
Set up an HTTP 402 Payment Required paywall that accepts instant USDC payments from autonomous AI bots without requiring credit card subscriptions or manual API key generation.
Prerequisites
- Basic Express.js or Next.js API knowledge
- Base or Solana RPC endpoint
- USDC receiving address
Step 1: The x402 Architecture & Protocol Flow
Understand the x402 handshake: When a consumer agent requests a premium resource without a valid settlement proof, the server replies with 402 Payment Required and structured payment terms in the WWW-Authenticate header.
Step 2: Install Middleware & Verification Libraries
Install the HTTP server, the chain SDKs used to verify settlement proofs, and dotenv for credentials.
Step 3: Create the Express x402 Server Middleware
This middleware checks incoming requests for the Authorization: L402/x402 signature header. If missing, it returns a 402 response with price parameters and a signed challenge.
Step 4: Configure Client Agent to Handle 402 Paywalls Automatically
Equip your client agent with an automatic retry interceptor that intercepts 402 responses, signs the micropayment transaction, and re-submits the request with the proof header.
Key Takeaway
Your APIs can now be monetized directly by AI agents worldwide with instantaneous micro-settlement and zero chargeback friction.
More Crypto Agent Tutorials
- Building an Autonomous On-Chain Agent with Coinbase AgentKit & Base — Learn how to give any LLM agent (LangChain / OpenAI / Claude) a self-custodial smart wallet on Base with automatic gas sponsorship, token swaps, and contract deployment.
- Configuring ERC-4337 Smart Accounts with Bounded Session Keys — Set up an enterprise-grade ERC-4337 Smart Account with fine-grained session key policies restricting autonomous bot spend, allowed contract targets, and expiration timestamps.
- Building a Verifiable DePIN Research Agent with ElizaOS — Deploy an autonomous market intelligence agent on ElizaOS that queries decentralized DePIN nodes, computes cryptographic market signals, and publishes attestations on-chain.