x402 微支付集成
基于 x402 v2 的按次 API 计费
什么是 x402?
x402 是围绕 HTTP 402 Payment Required 构建的机器对机器支付协议。
AgentWallex 当前采用 x402 v2 头部与 EIP-3009 授权载荷实现。
x402 v2 头部
PAYMENT-REQUIRED:402 支付挑战(资源服务端 -> 客户端)PAYMENT-SIGNATURE:签名后的支付载荷(客户端 -> 资源服务端)PAYMENT-RESPONSE:结算结果(资源服务端 -> 客户端)
高层流程
客户端 Agent 付费 API AgentWallex
│ │ │
│── GET /resource ──────▶│ │
│◀── 402 + PAYMENT-REQUIRED │
│ │ │
│── POST /api/v1/x402/pay ───────────────────────▶ │
│ │ (签名 + 策略校验) │
│◀── payment_info │ │
│ │ │
│── GET /resource + PAYMENT-SIGNATURE ───────────▶ │
│◀── 200 + PAYMENT-RESPONSE │
使用 AgentWallex x402 接口
1. 检查目标 URL 是否支持 x402
POST /api/v1/x402/check{
"url": "https://paid-api.example.com/v1/data"
}2. 可选:创建会话预算
POST /api/v1/x402/sessions{
"agent_id": "agent_uuid",
"budget_limit": "100.00",
"chain": "eip155:84532",
"ttl_seconds": 3600,
"allowed_urls": [
"https://paid-api.example.com/v1/data"
]
}3. 发起支付协商
POST /api/v1/x402/pay{
"agent_id": "agent_uuid",
"target_url": "https://paid-api.example.com/v1/data",
"session_id": "optional_session_uuid",
"chain": "eip155:84532"
}典型返回中 payment_info 包含:
ledger_idamountfee_amountfee_ratetokenchainstatus
服务提供方接入
如果你要开放付费 API,在缺少支付时应返回 x402 v2 challenge。
1. 返回 402 + PAYMENT-REQUIRED
将 challenge JSON(base64)放入 PAYMENT-REQUIRED 头,内容建议包含:
x402Version: 2resourceaccepts[](scheme/network/amount/asset/payTo/maxTimeoutSeconds)
2. 校验 PAYMENT-SIGNATURE
调用 AgentWallex facilitator:
POST /api/v1/x402/facilitator/verify3. 结算支付
POST /api/v1/x402/facilitator/settle4. 查询支持链
GET /api/v1/x402/facilitator/supported公共费率接口
GET /api/v1/x402/fees/tiers建议前端用该接口展示费率,不要硬编码。
当前后端默认参数
- 结算间隔:300 秒
- 结算阈值:
10.0 - 最大延迟:3600 秒
- x402 支持链:
eip155:84532、eip155:8453、eip155:1、eip155:137
错误契约
{
"code": "insufficient_funds",
"type": "invalid_request_error",
"message": "可直接展示的错误信息"
}