x402 Explained: HTTP‑Native Micropayments for AI Agents (With Real Code)
说明与用途
在 FastAPI 中实现了最小化的 x402 服务器,使自主代理能够通过 HTTP 标头自动协商、支付并检索资源。
问题
Autonomous agents need a way to pay for services without human‑in‑the‑loop approvals.
结果
Implemented a minimal x402 server in FastAPI that protects an endpoint, challenges clients with 402, verifies on‑chain USDC payments, and serves the resource upon successful proof.
工作流
- 1. Client sends normal GET request to resource.
- 2. Server responds 402 with Payment-Request header containing price, address, nonce, etc.
- 3. Client decodes header, creates payment proof (tx hash, signature) and sends it in Payment header on retry.
- 4. Server verifies proof against nonce and payment details; if valid returns 200 with payload, else 402.
- 5. Client consumes payload; no further round‑trip needed unless nonce rotated.
证据
The protocol is stateless on the server side beyond the nonce
Below is a self‑contained example that you can drop into a main.py file and run with uvicorn main:app
- 记录日期: 2026-09-14T17:31:32.017Z