Documentation Index
Fetch the complete documentation index at: https://docs.x402x.ai/llms.txt
Use this file to discover all available pages before exploring further.
客户端示例
最简集成
完整示例(Node + viem)
React示例(wagmi + viem)
import { wrapFetchWithPayment } from "x402x-fetch";
import { parseEther } from "viem";
const fetchWithPay = wrapFetchWithPayment(fetch, walletClient, parseEther("0.01")); // 设置最大支付额度
const res = await fetchWithPay("https://api.example.com/premium", { method: "POST" });
创建 client.ts,核心逻辑如下:// 1. 创建钱包客户端
const client = createWalletClient({
account,
transport: http(),
chain: bsc,
});
// 2. 包装 fetch 以支持自动支付
const fetchWithPay = wrapFetchWithPayment(
fetch,
walletClient.extend(publicActions),
parseEther("0.01")
);
// 3. 发起请求(自动处理支付)
const response = await fetchWithPay('http://localhost:3939/api/data', {
method: "POST",
});
import { createWalletClient, http, parseEther, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { wrapFetchWithPayment } from "x402x-fetch";
import { bsc } from "viem/chains";
const PRIVATE_KEY='' // 持有 USD1 Token 的私钥钱包
const SERVER_URL='http://localhost:3939/api/data'
async function main() {
// 创建钱包
const account = privateKeyToAccount(PRIVATE_KEY);
const client = createWalletClient({
account,
transport: http(),
chain: bsc,
});
// 创建支付 fetch
const fetchWithPay = wrapFetchWithPayment(
fetch,
client.extend(publicActions),
parseEther("0.01")
);
// 请求付费 API
const response = await fetchWithPay(SERVER_URL, {
method: "POST",
});
if (!response.ok) {
const error = await response.json();
console.error("❌ Error:", error);
return;
}
const data = await response.json();
console.log("✅ Received:", data);
}
main();
import { useX402Payment } from 'x402x-react';
import { useWalletClient } from 'wagmi';
function PaymentComponent() {
const { data: walletClient } = useWalletClient();
const { mutate, isPending, error, data } = useX402Payment({
targetUrl: 'https://api.example.com/resource',
walletClient,
});
return (
<button onClick={() => mutate()}>
{isPending ? 'Processing...' : 'Pay'}
</button>
);
}
工作流程
- 调用受保护资源 → 收到 402
- 解析
accepts → 选择一个 requirements
- 生成支付签名(Permit/EIP-3009/Permit2)
- 设置
X-Payment 重试请求 → 返回 200
最佳实践
- 始终设置
maxValue,避免过额支付
- 对多选项资源可传入 selector 优先 Token
- 失败时打印 payload 与 402 体,便于定位
常见问题
- 余额不足/过期/nonce 错误 → 按错误提示重新签名
- 网络切换后失败 → 确保
network 与 requirements 匹配