x402-payments
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesex402 Protocol Skill
x402协议技能
Protocol Overview
协议概述
x402 embeds stablecoin payments into HTTP by using the 402 "Payment Required" status code. A server responds with payment requirements; the client signs a payment authorization, resubmits the request, and gets the resource after verification and settlement.
Payment flow:
- Client sends HTTP request → Server returns +
402header (base64 JSON)PAYMENT-REQUIRED - Client reads requirements, creates signed payment payload
- Client resubmits request with header (base64 JSON)
PAYMENT-SIGNATURE - Server verifies payment via facilitator
POST /verify - Server performs work, settles via facilitator
POST /settle - Server returns + resource +
200header (contains txHash)PAYMENT-RESPONSE
Key concepts:
- Facilitators verify and settle payments without holding funds. Use for testnet, CDP facilitator for mainnet.
https://x402.org/facilitator - Schemes: (fixed price per request) is the production scheme.
exactanduptoare proposed.deferred - Networks: Identified by CAIP-2 format — (Base Sepolia),
eip155:84532(Base Mainnet),eip155:8453(Solana Devnet).solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 - EVM uses EIP-3009 gasless . Solana uses SPL token transfers.
TransferWithAuthorization
x402通过使用402 "Payment Required"状态码,将稳定币支付嵌入HTTP协议中。服务器会返回支付要求;客户端签署支付授权后重新提交请求,在验证和结算完成后即可获取资源。
支付流程:
- 客户端发送HTTP请求 → 服务器返回+
402请求头(base64格式JSON)PAYMENT-REQUIRED - 客户端读取要求,创建已签名的支付负载
- 客户端通过请求头(base64格式JSON)重新提交请求
PAYMENT-SIGNATURE - 服务器通过支付服务商的接口验证支付
POST /verify - 服务器执行任务,通过支付服务商的接口完成结算
POST /settle - 服务器返回+ 资源 +
200请求头(包含txHash)PAYMENT-RESPONSE
核心概念:
- 支付服务商(Facilitators):无需持有资金即可验证和结算支付。测试网使用,主网使用CDP支付服务商。
https://x402.org/facilitator - 支付方案(Schemes):(每请求固定价格)为生产环境方案,
exact和upto为提案方案。deferred - 网络:以CAIP-2格式标识——(Base Sepolia测试网)、
eip155:84532(Base主网)、eip155:8453(Solana Devnet测试网)。solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 - EVM使用EIP-3009无Gas的,Solana使用SPL代币转账。
TransferWithAuthorization
Quick-Start: Protect an API Endpoint (Seller)
快速入门:保护API端点(卖家端)
bash
npm install @x402/express @x402/core @x402/evmtypescript
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
const app = express();
const payTo = process.env.PAY_TO!;
const facilitatorClient = new HTTPFacilitatorClient({
url: "https://x402.org/facilitator",
});
const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);
app.use(
paymentMiddleware(
{
"GET /weather": {
accepts: [
{ scheme: "exact", price: "$0.001", network: "eip155:84532", payTo },
],
description: "Get current weather data",
mimeType: "application/json",
},
},
server,
),
);
app.get("/weather", (req, res) => {
res.json({ weather: "sunny", temperature: 70 });
});
app.listen(4021, () => console.log("Server on :4021"));bash
npm install @x402/express @x402/core @x402/evmtypescript
import express from "express";
import { paymentMiddleware } from "@x402/express";
import { x402ResourceServer, HTTPFacilitatorClient } from "@x402/core/server";
import { registerExactEvmScheme } from "@x402/evm/exact/server";
const app = express();
const payTo = process.env.PAY_TO!;
const facilitatorClient = new HTTPFacilitatorClient({
url: "https://x402.org/facilitator",
});
const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);
app.use(
paymentMiddleware(
{
"GET /weather": {
accepts: [
{ scheme: "exact", price: "$0.001", network: "eip155:84532", payTo },
],
description: "Get current weather data",
mimeType: "application/json",
},
},
server,
),
);
app.get("/weather", (req, res) => {
res.json({ weather: "sunny", temperature: 70 });
});
app.listen(4021, () => console.log("Server on :4021"));Quick-Start: Pay for x402 Resources (Buyer/Agent)
快速入门:为x402资源付费(买家/Agent端)
bash
npm install @x402/fetch @x402/core @x402/evm viemtypescript
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const response = await fetchWithPayment("http://localhost:4021/weather");
const data = await response.json();
console.log(data);
// Read payment receipt
const httpClient = new x402HTTPClient(client);
const receipt = httpClient.getPaymentSettleResponse(
(name) => response.headers.get(name),
);
console.log("Tx:", receipt?.txHash);bash
npm install @x402/fetch @x402/core @x402/evm viemtypescript
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const fetchWithPayment = wrapFetchWithPayment(fetch, client);
const response = await fetchWithPayment("http://localhost:4021/weather");
const data = await response.json();
console.log(data);
// Read payment receipt
const httpClient = new x402HTTPClient(client);
const receipt = httpClient.getPaymentSettleResponse(
(name) => response.headers.get(name),
);
console.log("Tx:", receipt?.txHash);Decision Tree
决策树
| Decision | Choice | Packages |
|---|---|---|
| Server: Express | | |
| Server: Next.js | | |
| Server: Hono | | |
| Client: fetch | | |
| Client: axios | | |
| Client: manual | | |
| Chain: EVM | | |
| Chain: Solana | | |
| Chain: both | Register both schemes on same client/server | All chain deps |
| Env: testing | Facilitator | Base Sepolia / Solana Devnet |
| Env: production | CDP facilitator + API keys | Base Mainnet / Solana Mainnet |
| Agent: MCP | MCP server with | See |
| Agent: Anthropic | Tool-use with | See |
| 决策 | 选项 | 依赖包 |
|---|---|---|
| 服务器:Express | 使用 | |
| 服务器:Next.js | 使用 | |
| 服务器:Hono | 使用 | |
| 客户端:fetch | 使用 | |
| 客户端:axios | 使用 | |
| 客户端:手动实现 | 使用 | |
| 链:EVM | 使用 | |
| 链:Solana | 使用 | |
| 链:同时支持两者 | 在同一客户端/服务器上注册两种方案 | 所有链相关依赖 |
| 环境:测试 | 使用支付服务商 | Base Sepolia / Solana Devnet |
| 环境:生产 | 使用CDP支付服务商 + API密钥 | Base Mainnet / Solana Mainnet |
| Agent:MCP | 结合 | 详见 |
| Agent:Anthropic | 结合 | 详见 |
Reference File Navigation
参考文件导航
| Task | Read this file |
|---|---|
| Headers, payloads, CAIP-2 IDs, facilitator API, V1→V2 changes | |
| Express / Hono / Next.js middleware, multi-route, dynamic pricing | |
| Fetch / axios client, wallet setup, lifecycle hooks, error handling | |
| AI agent payments, MCP server, tool discovery, budget controls | |
| Testnet→mainnet migration, CDP keys, faucets, security, sessions | |
| 任务 | 参考文件 |
|---|---|
| 请求头、负载、CAIP-2 ID、支付服务商API、V1→V2变更 | |
| Express / Hono / Next.js中间件、多路由、动态定价 | |
| Fetch / axios客户端、钱包设置、生命周期钩子、错误处理 | |
| AI Agent支付、MCP服务器、工具发现、预算控制 | |
| 测试网→主网迁移、CDP密钥、水龙头、安全、会话 | |
Critical Implementation Notes
关键实现注意事项
- Register schemes before wrapping fetch/axios — order matters.
- Two equivalent registration APIs:
- Function: /
registerExactEvmScheme(server)registerExactEvmScheme(client, { signer }) - Method:
server.register("eip155:84532", new ExactEvmScheme())
- Function:
- V2 headers (current): ,
PAYMENT-REQUIRED,PAYMENT-SIGNATURE. V1 headers (legacy):PAYMENT-RESPONSE,X-PAYMENT. SDK is backward-compatible.X-PAYMENT-RESPONSE - Price format: (dollar string) — SDK converts to atomic units (6 decimals for USDC).
"$0.001" - Python SDK uses V1 patterns only. Use TypeScript or Go for V2.
- Node.js v24+ required for the TypeScript SDK.
- Repo: — canonical examples in
https://github.com/coinbase/x402.examples/typescript/ - Docs: and
https://docs.cdp.coinbase.com/x402/welcome.https://x402.gitbook.io/x402
- 注册方案需在包装fetch/axios之前完成——顺序很重要。
- 两种等效的注册API:
- 函数式:/
registerExactEvmScheme(server)registerExactEvmScheme(client, { signer }) - 方法式:
server.register("eip155:84532", new ExactEvmScheme())
- 函数式:
- V2请求头(当前版本):、
PAYMENT-REQUIRED、PAYMENT-SIGNATURE。 V1请求头(旧版):PAYMENT-RESPONSE、X-PAYMENT。SDK向后兼容。X-PAYMENT-RESPONSE - 价格格式:(美元字符串)——SDK会转换为原子单位(USDC为6位小数)。
"$0.001" - Python SDK仅支持V1模式,如需使用V2请选择TypeScript或Go。
- TypeScript SDK要求Node.js v24+。
- 代码仓库:——标准示例位于
https://github.com/coinbase/x402目录下。examples/typescript/ - 文档:和
https://docs.cdp.coinbase.com/x402/welcome。https://x402.gitbook.io/x402