x402 支付協議
x402 透過 402 Payment Required 狀態碼,實現即時穩定幣支付,直接在 HTTP 上完成。非常適合 AI 代理按需支付 API、數據或計算資源。
快速開始
安裝 SDK
npm install x402
# 或
pnpm add x402
環境設定
# 安全儲存錢包私鑰
export WALLET_PRIVATE_KEY="0x..."
# 可選:指定網路 RPC
export BASE_RPC_URL="https://mainnet.base.org"
x402 運作方式
- 請求 → 客戶端呼叫付費 API
- 402 回應 → 伺服器在
PAYMENT-REQUIRED標頭中返回付款詳細資訊 - 付款並重試 → 客戶端簽署付款,並以
PAYMENT-SIGNATURE標頭重試 - 存取 → 伺服器驗證、結算,然後返回資源
使用 x402 客戶端
TypeScript/Node.js
import { x402Client } from 'x402';
const client = x402Client({
privateKey: process.env.WALLET_PRIVATE_KEY,
network: 'base', // 或 'ethereum', 'arbitrum' 等
});
// 自動處理 402
const response = await client.fetch('https://api.example.com/paid-endpoint');
const data = await response.json();
使用 Fetch 封裝
import { wrapFetch } from 'x402';
const fetch402 = wrapFetch(fetch, {
privateKey: process.env.WALLET_PRIVATE_KEY,
});
// 像正常 fetch 一樣使用 - 402 會自動處理
const res = await fetch402('https://paid-api.com/data');
手動流程 (curl)
步驟 1:發現付款需求
curl -i https://api.example.com/paid-resource
# 返回 402 狀態碼,並帶有 PAYMENT-REQUIRED 標頭(base64 編碼的 JSON)
步驟 2:解碼付款詳細資訊
# PAYMENT-REQUIRED 標頭包含 base64 編碼的 JSON:
# {
# "amount": "1000000", # 1 USDC(6 位小數)
# "currency": "USDC",
# "network": "base",
# "recipient": "0x...",
# "scheme": "exact"
# }
步驟 3:簽署並付款
# 使用 x402 CLI 或 SDK 建立付款簽章
npx x402 pay \
--amount 1000000 \
--recipient 0x... \
--network base
步驟 4:帶上證明重試
curl -H "PAYMENT-SIGNATURE: <base64_payload>" \
https://api.example.com/paid-resource
常見模式
支付 API 調用
// 每次調用花費 0.001 USDC 的天氣 API
const weather = await client.fetch('https://weather-api.x402.org/forecast?city=NYC');
支付 AI 推理
// 按 token 計價的 LLM API
const completion = await client.fetch('https://llm.example.com/v1/chat', {
method: 'POST',
body: JSON.stringify({ prompt: 'Hello' }),
});
付款前檢查餘額
import { getBalance } from 'x402';
const balance = await getBalance({
address: walletAddress,
network: 'base',
token: 'USDC',
});
if (balance < requiredAmount) {
console.log('USDC 餘額不足');
}
支援的網路
| 網路 | 鏈 ID | 狀態 |
|---|---|---|
| Base | 8453 | ✅ 主要 |
| Ethereum | 1 | ✅ 支援 |
| Arbitrum | 42161 | ✅ 支援 |
| Optimism | 10 | ✅ 支援 |
| Polygon | 137 | ✅ 支援 |
付款方案
- exact:支付固定金額(例如每次 API 調用 $0.01)
- upto:根據使用量支付不超過最大值(例如 LLM tokens)
- subscription:基於錢包的存取,使用會話(V2)
錯誤處理
try {
const res = await client.fetch(url);
} catch (err) {
if (err.code === 'INSUFFICIENT_BALANCE') {
// 需要為錢包充值
} else if (err.code === 'PAYMENT_FAILED') {
// 鏈上交易失敗
} else if (err.code === 'INVALID_PAYMENT_REQUIREMENTS') {
// 伺服器發送了格式錯誤的 402 回應
}
}
安全注意事項
- 切勿在日誌或聊天中暴露私鑰
- 使用環境變數儲存錢包憑證
- 優先使用
op run或類似工具進行秘密注入 - 在確認大額交易前,務必檢查付款金額
V2 功能(2025 年 12 月)
- 基於錢包的身份:每次呼叫無需重複付款,使用會話
- 自動發現:API 在
/.well-known/x402揭露付款中繼資料 - 多促進者:在支付處理器之間選擇
- CAIP 標準:統一的鏈/資產識別碼