Ken
2025年11月15日
本指南将引导你如何使用 x402 与需要支付的服务进行交互。完成本指南后,你将能够以编程方式发现支付要求、完成支付,并访问付费资源。
在开始之前,请确保你已经具备以下条件:
一只持有 USDC 的加密钱包(任意兼容 EVM 的钱包)
Node.js 和 npm,或 Python 和 pip
一个需要通过 x402 支付的服务
我们在仓库中提供了预先配置好的示例,包括 fetch、Axios 和 MCP 的示例。
npm install x402-axios
# or
npm install x402-fetch
该社区包展示了 AI 代理如何在 x402 中使用模型上下文协议(MCP)。我们正在努力将官方 MCP 规范尽快纳入 x402。
安装 MCP 支持所需的依赖包:
npm install x402-mcp ai @modelcontextprotocol/sdk
pip install x402
npm install viem
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";
// Create a wallet client (using your private key)
const account = privateKeyToAccount("0xYourPrivateKey"); // we recommend using an environment variable for this
pip install eth_account
from eth_account import Account
account = Account.from_key("your_private_key") # we recommend using an environment variable for this
import { createKeyPairSignerFromBytes } from "@solana/kit";
import { base58 } from "@scure/base";
// 64-byte base58 secret key (private + public)
const signer = await createKeyPairSignerFromBytes(
base58.decode(process.env.SOLANA_PRIVATE_KEY!)
);
你可以使用 x402-fetch 或 x402-axios 自动处理 402 ‘需要付款’ 响应,并完成支付流程。
x402-fetch 扩展了原生的 fetch API,帮你处理 402 响应和支付相关的请求头。完整示例见此处。
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
// other imports...
// wallet creation logic...
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
fetchWithPayment(url, { //url should be something like https://api.example.com/paid-endpoint
method: "GET",
})
.then(async response => {
const body = await response.json();
console.log(body);
const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response")!);
console.log(paymentResponse);
})
.catch(error => {
console.error(error.response?.data?.error);
});
x402-axios 为 Axios 添加了支付拦截器,因此你的请求会自动带上支付请求头并重试。
import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
import axios from "axios";
// other imports...
// wallet creation logic...
// Create an Axios instance with payment handling
const api = withPaymentInterceptor(
axios.create({
baseURL, // e.g. https://api.example.com
}),
account,
);
api
.get(endpointPath) // e.g. /paid-endpoint
.then(response => {
console.log(response.data);
const paymentResponse = decodeXPaymentResponse(response.headers["x-payment-response"]);
console.log(paymentResponse);
})
.catch(error => {
console.error(error.response?.data?.error);
});
x402-mcp 为 MCP 客户端提供支付处理功能,使 AI 代理能够自动为工具支付费用。
import { convertToModelMessages, stepCountIs, streamText } from "ai";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { experimental_createMCPClient as createMCPClient } from "ai";
import { withPayment } from "x402-mcp";
// Create MCP client with payment capabilities
const mcpClient = await createMCPClient({
transport: new StreamableHTTPClientTransport(mcpServerUrl), // URL of your MCP server
}).then((client) => withPayment(client, {
account, // Your wallet account from step 2
network: "base" // or "base-sepolia" for testnet
}));
// Get available tools (both paid and free)
const tools = await mcpClient.tools();
// Use the tools with your AI model
const result = streamText({
model: "gpt-4", // or any AI model
tools,
messages: convertToModelMessages(messages),
stopWhen: stepCountIs(5), // Limit tool calls for safety
onFinish: async () => {
await mcpClient.close();
},
system: "ALWAYS prompt the user to confirm before authorizing payments",
});
特性:
自动检测 MCP 工具何时需要支付
透明处理 x402 支付流程
支持来自同一服务器的付费和免费工具
与 Vercel AI SDK 无缝集成
withPayment 包装器为任意 MCP 客户端添加支付功能。当调用某个工具需要支付时,它会使用你配置的钱包自动处理 x402 支付流程。
你可以使用 httpx 或 Requests 自动处理 402 ‘需要付款’ 响应,并完成支付流程。
两者都支持简单且可扩展的方式。简单方式会返回一个预配置的客户端,能够自动处理支付;可扩展方式则允许你使用已有的 session/客户端。这里讲解的是简单方式,可扩展方式请参考下方完整示例的 README。
from x402.clients.httpx import x402HttpxClient
# Other imports...
# Wallet creation logic ...
# Create client and make request
async with x402HttpxClient(account=account, base_url="https://api.example.com") as client:
response = await client.get("/protected-endpoint")
print(await response.aread())
from x402.clients.httpx import x402HttpxClient
# Other imports...
# Wallet creation logic ...
# Create client and make request
async with x402HttpxClient(account=account, base_url="https://api.example.com") as client:
response = await client.get("/protected-endpoint")
print(await response.aread())
在以下情况下,客户端会抛出错误:
请求配置缺失
该请求已尝试过支付
创建支付请求头时发生错误
安装 x402 客户端包
创建钱包客户端
使用提供的包装器/拦截器发起付费 API 请求
支付流程将自动为你处理