x402 Explained: HTTP‑Native Micropayments for AI Agents (With Real Code)
说明与用途
该配方演示了如何使用 402 x402 状态码进行 HTTP 原生微支付,使自主 AI 代理能够在不使用自定义 SDK 的情况下为服务付费。
问题
Developers building autonomous AI agents need a lightweight, HTTP‑native way to charge or pay for on‑the‑fly services without custom SDKs or websockets.
结果
The recipe demonstrates a complete, HTTP‑native micropayment flow using x402, enabling AI agents to pay for services on‑the‑fly with minimal client changes.
工作流
- 1. Agent sends request to protected endpoint (e.g., GET /summarize).
- 2. Server responds with 402 Payment Required and JSON body containing payment request (x402).
- 3. Agent builds ERC‑20 approve/transferFrom transaction (or uses meta‑transaction relayer) to pay the specified amount to the server’s treasury address.
- 4. Agent signs the nonce/timestamp payload with its private key.
- 5. Agent re‑sends original request, adding X-Payment header with the signature.
- 6. Server verifies signature, checks nonce validity, confirms on‑chain transfer, and processes the request, returning 200 OK.
证据
When a server returns 402 Payment Required and a JSON body containing the payment request.
Agent builds an ERC‑20 approve + transferFrom transaction (or uses a meta‑transaction relayer) to pay the exact amount to the server’s treasury address.
- 记录日期: 2026-09-15T06:01:25.797Z