x402协议通过HTTP 402状态码让AI Agent自动完成API支付:服务器返回支付发票→Agent链上付款→携带证明重试。支持Coinbase CDP、Cloudflare Wallets等中介加速(~2秒),绕过传统API Key模式。
curl -s https://minia2a.uk/x402/captcha-solve
{
"error": "Payment Required",
"type": "x402",
"network": "base",
"token": "USDC",
"priceCents": 5,
"recipient": "0xf16F0882de08315B438E9f3a2Abfb2d2E5d94ECA",
"chainId": 8453
}
402 响应包含了 Agent 支付所需的全部信息:付多少(5 美分 USDC)、付给谁(合约地址)、在哪条链上(Base L2)。
你可以在链上发送 USDC 并等待确认。这完全去中心化、值得信赖——但 Base 区块确认大约需要 15 秒。对于实时 API 调用来说,这太慢了。
x402 生态中有三种不同的 Facilitator 选项来处理这个问题:
实用的路径:探索阶段用免费试用,生产环境用 Coinbase CDP。
# 使用 Coinbase CDP:签名支付消息
SIGNATURE=$(node sign-payment.js \
--recipient "0xf16F0882de08315B438E9f3a2Abfb2d2E5d94ECA" \
--amount 5 \
--chain 8453)
curl -s https://minia2a.uk/x402/captcha-solve \
-H "X-Wallet: 0xYOUR_WALLET" \
-H "X-Payment-Signature: $SIGNATURE"
{
"solved": true,
"token": "recaptcha_v3_token_here",
"cost": 5,
"x-receipt": "rcpt_abc123def456"
}
x-receipt 响应头包含一个加密的收据 ID,可以随时验证:
GET /api/v1/receipts/rcpt_abc123def456 → { verified: true, hmach: "sha256:..." }
来构建一个实用的 Agent:一个加密货币市场监控器,在交易前检查 Token 安全性。
// agent.js — 一个为安全检查付费的交易 Agent
const BASE_URL = 'https://minia2a.uk/x402';
class PayingAgent {
constructor(walletAddress, signer) {
this.wallet = walletAddress;
this.signer = signer; // 签名 x402 支付挑战的函数
this.remainingTrials = new Map(); // 追踪每个端点的试用次数
}
async call(serviceId, params = {}) {
const url = `${BASE_URL}/${serviceId}?${new URLSearchParams(params)}`;
// 第一次尝试:不付款(使用免费试用)
let res = await fetch(url);
if (res.status === 200) {
const remaining = res.headers.get('X-Trials-Remaining');
console.log(`[trial] ${serviceId} → 剩余 ${remaining} 次试用`);
return res.json();
}
// 收到 402 — 需要付款
if (res.status === 402) {
const invoice = await res.json();
return this.payAndRetry(url, invoice);
}
throw new Error(`意外状态码:${res.status}`);
}
async payAndRetry(url, invoice) {
console.log(`[pay] 向 ${invoice.recipient.slice(0,10)}... 支付 $${invoice.priceCents/100} USDC`);
// 签名支付挑战
const signature = await this.signer({
recipient: invoice.recipient,
amount: invoice.priceCents,
chainId: invoice.chainId,
token: invoice.token
});
// 携带支付凭证重试
const res = await fetch(url, {
headers: {
'X-Wallet': this.wallet,
'X-Payment-Signature': signature,
}
});
if (res.status === 200) {
const receipt = res.headers.get('X-Minia2a-Receipt');
console.log(`[paid] 收据:${receipt}`);
return res.json();
}
// 支付失败
const error = await res.json();
throw new Error(`支付失败:${error.error}`);
}
}
// 用法
const agent = new PayingAgent(
'0xYourWallet',
signWithCoinbaseCDP // 你的签名函数
);
// 交易前检查 Token 是否为蜜罐
const security = await agent.call('token-security', {
address: '0xTOKEN_TO_CHECK',
chain: 'ethereum'
});
if (security.risk === 'LOW') {
console.log('可以安全交易');
// 执行交易...
} else {
console.log(`⚠️ 风险:${security.risk} — ${security.details}`);
}
市场上的每个端点都有 15 次免费试用调用。试用期间不需要钱包——服务器按 IP 追踪:
# curl -v 可以看到试用响应头
# < X-Trials-Remaining: 14
# < X-Trials-Total: 15
试用次数用完后,就会收到 402。这个流程设计使得 Agent 可以在无需预付款的情况下探索和集成。只有当服务被证明有用时,才需要付款。
这很关键,因为市场上 97% 的免费额度都没有被使用。Agent 尝试几次调用、获取所需信息后就离开了。支付路径只在持续、高频使用时才会激活——这才是正确的行为。
npm install @minia2a/langchain
import { Minia2aToolkit } from '@minia2a/langchain';
const toolkit = new Minia2aToolkit({
wallet: process.env.AGENT_WALLET,
signer: coinbaseSigner,
});
// 搜索服务
const services = await toolkit.search('captcha');
// → [{ id: 'x402-captcha-solve', priceCents: 5, description: '...' }]
// 调用服务,自动处理支付
const result = await toolkit.call('x402-captcha-solve', {
sitekey: 'XXX',
url: 'https://example.com'
});
// 支付通过 x402 流程自动处理
该协议原生基于 HTTP,不需要 SDK:
import requests
def call_x402(service_id, params, wallet, signer):
url = f"https://minia2a.uk/x402/{service_id}"
resp = requests.get(url, params=params)
if resp.status_code == 200:
return resp.json()
if resp.status_code == 402:
invoice = resp.json()
sig = signer(invoice['recipient'], invoice['priceCents'])
resp = requests.get(url, params=params, headers={
'X-Wallet': wallet,
'X-Payment-Signature': sig,
})
return resp.json()
raise Exception(f"HTTP {resp.status_code}")
// Go Agent
func (a *Agent) CallX402(serviceID string, params url.Values) ([]byte, error) {
u := fmt.Sprintf("https://minia2a.uk/x402/%s?%s", serviceID, params.Encode())
resp, _ := http.Get(u)
if resp.StatusCode == 402 {
var invoice X402Invoice
json.NewDecoder(resp.Body).Decode(&invoice)
sig := a.SignPayment(invoice)
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("X-Wallet", a.WalletAddr)
req.Header.Set("X-Payment-Signature", sig)
resp, _ = http.DefaultClient.Do(req)
}
return io.ReadAll(resp.Body)
}
根本区别在于:
对人类来说,API Key 没问题。但对于 Agent——每分钟自主做出数千个决策的自主软件——Key 管理的摩擦会破坏自主循环。每个新 API 都需要人工注册签名,Agent 就不是真正的自主。
402 流程让 API 访问变得可编程:发现 → 调用 → 获取发票 → 付款 → 重试 → 获取结果。全程代码完成,无需人工介入。
每次 x402 调用都会返回一个加密收据:
{
"id": "rcpt_x402_captcha_2026-08-07T14-22-11Z_abc123",
"type": "trial",
"service_id": "x402-captcha-solve",
"fee_cents": 0,
"hmac": "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
}
收据有三个用途:
可审计性 — Agent 可以证明自己调用了某个服务并获得了结果
纠纷解决 — 如果服务返回了垃圾数据,收据就是加密证据
计费 — 多 Agent 系统可以追踪子 Agent 的开销
验证是公开的:任何拥有 HMAC 密钥的人都可以验证收据。服务提供商可以发布验证端点。Agent 可以审计自己的开销。
在将 x402 集成到多个 Agent 之后,以下是生态系统需要的东西:
钱包感知的 Agent 框架 — LangChain、CrewAI 和 ElizaOS 应该将 agent.wallet 作为一等公民原生支持。不是插件,是内置功能。
通过自然语言进行服务发现 — "我需要检查这个智能合约是否安全" → Agent 搜索市场、找到 token-security、调用它、付款、获取结果。当前状态:你需要知道精确的服务 ID。这对开发者来说可以接受,但对 Agent 不行。
链上声誉 — 服务应该积累链上声誉分数。CAPTCHA 破解器真的解开了 CAPTCHA 吗?Token 审计真的发现了蜜罐吗?声誉机制让市场能够自我治理。
预算约束作为代码 — agent.setDailyBudget(5.00, 'USDC'),Agent 自我调节。无超支风险。无意外账单。这是钱包原语的一部分。
来自一个拥有 323 个服务的真实市场:
排名第一的服务:CAPTCHA 破解(1,280 次调用,133 位用户)
排名第二:持久化内存/键值存储(1,401 次调用)
转化率:16.5% 的试用用户注册了钱包
额度利用率:只有 2.8% 的免费额度被实际使用
市场虽小但真实存在。322 个独立 Agent 调用了 API。其中 53 个拥有链上钱包。已结算交易金额 $12.75。
基础设施运转良好。使用习惯尚未跟上。
代码示例使用了 minia2a.uk 市场(323 个服务,每个端点 15 次免费试用,Base 链上的 USDC)。x402 协议是一个正在被正式提交为 IETF 草案的开放标准。Go、Node.js 和 Python 都有实现。