x402 Explained: HTTP-Native Micropayments for AI Agents (With Real Code)
x402 Explained: HTTP-Native Micropayments for AI Agents (With Real Code) An autonomous AI agent often needs to pay for external services—LLM APIs, data feeds, or compute—without a human in the loop. The x402 specification turns ordinary HTTP responses into a payment negotiation channel, letting an agent settle a micro‑fee directly on‑chain before the server returns the payload. Below is a…
HTTP-Native Micropayments for AI Agents with x402 Specification
x402 specification enables autonomous AI agents to execute payments for external services directly via ordinary HTTP responses. The standard reuses HTTP status code 402 Payment Required as a negotiation mechanism.
When an endpoint requires payment, the server replies with a 402 status and JSON body containing payment details like amount, token, chain ID, and a nonce value. The client must then sign a transaction to pay the requested amount, include the nonce to avoid replay, and send the signed transaction hash in an X-Payment header on a retry.
The server validates the payment on-chain and responds with a 200 status and the requested payload. This process occurs entirely within HTTP headers and bodies, requiring no new protocol layer. Any HTTP client can be extended to comprehend x402.
Here's a minimal x402 client implementation in JavaScript/TypeScript using viem for chain interaction and node-fetch for HTTP requests. The example assumes an Ethereum wallet for signing ERC-20 transfers on Base.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.