Logo

买家快速入门

avatar

Ken

2025年11月15日

17+
买家快速入门

本指南将引导你如何使用 x402 与需要支付的服务进行交互。完成本指南后,你将能够以编程方式发现支付要求、完成支付,并访问付费资源。

准备工作

在开始之前,请确保你已经具备以下条件:

  • 一只持有 USDC 的加密钱包(任意兼容 EVM 的钱包)

  • Node.js 和 npm,或 Python 和 pip

  • 一个需要通过 x402 支付的服务

我们在仓库中提供了预先配置好的示例,包括 fetch、Axios 和 MCP 的示例。

1. 安装依赖

1.1 Node.js

HTTP 客户端(Axios/Fetch)安装 x402-axios 或 x402-fetch:

npm install x402-axios
# or
npm install x402-fetch

MCP(非官方)

该社区包展示了 AI 代理如何在 x402 中使用模型上下文协议(MCP)。我们正在努力将官方 MCP 规范尽快纳入 x402。

安装 MCP 支持所需的依赖包:

npm install x402-mcp ai @modelcontextprotocol/sdk

1.2 Python

安装 x402 包

pip install x402

2. 创建钱包客户端

2.1 Node.js(viem)

安装所需的依赖包:

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

2.2 Python(eth_account)

安装所需的包:

pip install eth_account

然后创建钱包账户实例:

from eth_account import Account


account = Account.from_key("your_private_key") # we recommend using an environment variable for this

2.3 Solana(SVM)

使用 SolanaKit 创建签名者实例:

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!)
);

3. 自动发起付费请求

3.1 Node.js

你可以使用 x402-fetch 或 x402-axios 自动处理 402 ‘需要付款’ 响应,并完成支付流程。

3.1.1 Fetch

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);
  });

3.1.2 Axios

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);
  });

3.1.3 x402-mcp

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 支付流程。

3.2 Python

你可以使用 httpx 或 Requests 自动处理 402 ‘需要付款’ 响应,并完成支付流程。

  • Requests 是一个成熟的同步 HTTP 请求库,使用简单,非常适合直接的顺序工作流程。
  • HTTPX 是一个现代库,支持同步和异步(async)HTTP 请求。如果你需要高并发、HTTP/2 等高级功能,或者想利用 Python 的异步特性,建议使用 HTTPX。

两者都支持简单且可扩展的方式。简单方式会返回一个预配置的客户端,能够自动处理支付;可扩展方式则允许你使用已有的 session/客户端。这里讲解的是简单方式,可扩展方式请参考下方完整示例的 README。

3.2.1 HTTPX

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())

3.2.2 Requests

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())

4. 错误处理

在以下情况下,客户端会抛出错误:

  • 请求配置缺失

  • 该请求已尝试过支付

  • 创建支付请求头时发生错误

总结

  • 安装 x402 客户端包

  • 创建钱包客户端

  • 使用提供的包装器/拦截器发起付费 API 请求

  • 支付流程将自动为你处理