x402 Explained: HTTP-Native Micropayments for AI Agents (With Real Code)
x402 Explained: HTTP‑Native Micropayments for AI Agents (With Real Code) Target audience: developers who are building autonomous AI agents and need a lightweight way to charge for individual API calls without introducing a separate billing system. Why look at x402? Autonomous agents often expose fine‑grained services—think “summarize this paragraph”, “classify this image”, or “fetch the latest price for a token”. Traditional approaches (API keys + monthly invoices, subscription tiers, or ad‑hoc invoicing) add operational overhead that doesn’t scale when an agent might make thousands of micro‑calls per day. The x402 specification repurposes the HTTP 402 Payment Required status code to turn every request into a self‑contained payment negotiation. If the client hasn’t paid, the server replies with 402 and includes the exact payment details the client must satisfy. Once the payment is verified, the server processes the request and returns the normal 200 response. Because the payment is expressed as a plain HTTP header, the mechanism works over any transport that supports headers—REST, GraphQL, gRPC‑HTTP/2 bridge, or even WebSockets. No new protocol layers, no side‑channel escrow services, and no need to maintain a separate billing database. Core components of an x402 flow Piece What it does Where it lives Payment Request Server‑generated data describing the required amount, token, chain, and payee address. Sent in the Pay response header on a 402. Server Payment Proof Client‑generated data proving that a transaction meeting the request was included on‑chain. Sent in the X-Payment request header. Client Verifier Server‑side code that checks the proof: validates the transaction hash, confirms the correct token amount was transferred to the payee, and ensures the chain ID matches. Server Wallet/Signer Client‑side library (e.g., ethers.js) that builds, signs, and broadcasts the payment transaction. Client The spec deliberately stays agnostic about the underlying blockchain;