x402-payments

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

x402 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:
  1. Client sends HTTP request → Server returns
    402
    +
    PAYMENT-REQUIRED
    header (base64 JSON)
  2. Client reads requirements, creates signed payment payload
  3. Client resubmits request with
    PAYMENT-SIGNATURE
    header (base64 JSON)
  4. Server verifies payment via facilitator
    POST /verify
  5. Server performs work, settles via facilitator
    POST /settle
  6. Server returns
    200
    + resource +
    PAYMENT-RESPONSE
    header (contains txHash)
Key concepts:
  • Facilitators verify and settle payments without holding funds. Use
    https://x402.org/facilitator
    for testnet, CDP facilitator for mainnet.
  • Schemes:
    exact
    (fixed price per request) is the production scheme.
    upto
    and
    deferred
    are proposed.
  • Networks: Identified by CAIP-2 format —
    eip155:84532
    (Base Sepolia),
    eip155:8453
    (Base Mainnet),
    solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1
    (Solana Devnet).
  • EVM uses EIP-3009 gasless
    TransferWithAuthorization
    . Solana uses SPL token transfers.
x402通过使用402 "Payment Required"状态码,将稳定币支付嵌入HTTP协议中。服务器会返回支付要求;客户端签署支付授权后重新提交请求,在验证和结算完成后即可获取资源。
支付流程:
  1. 客户端发送HTTP请求 → 服务器返回
    402
    +
    PAYMENT-REQUIRED
    请求头(base64格式JSON)
  2. 客户端读取要求,创建已签名的支付负载
  3. 客户端通过
    PAYMENT-SIGNATURE
    请求头(base64格式JSON)重新提交请求
  4. 服务器通过支付服务商的
    POST /verify
    接口验证支付
  5. 服务器执行任务,通过支付服务商的
    POST /settle
    接口完成结算
  6. 服务器返回
    200
    + 资源 +
    PAYMENT-RESPONSE
    请求头(包含txHash)
核心概念:
  • 支付服务商(Facilitators):无需持有资金即可验证和结算支付。测试网使用
    https://x402.org/facilitator
    ,主网使用CDP支付服务商。
  • 支付方案(Schemes)
    exact
    (每请求固定价格)为生产环境方案,
    upto
    deferred
    为提案方案。
  • 网络:以CAIP-2格式标识——
    eip155:84532
    (Base Sepolia测试网)、
    eip155:8453
    (Base主网)、
    solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1
    (Solana Devnet测试网)。
  • EVM使用EIP-3009无Gas的
    TransferWithAuthorization
    Solana使用SPL代币转账。

Quick-Start: Protect an API Endpoint (Seller)

快速入门:保护API端点(卖家端)

bash
npm install @x402/express @x402/core @x402/evm
typescript
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/evm
typescript
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 viem
typescript
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 viem
typescript
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

决策树

DecisionChoicePackages
Server: Express
paymentMiddleware
from
@x402/express
@x402/express @x402/core @x402/evm
Server: Next.js
paymentProxy
from
@x402/next
@x402/next @x402/core @x402/evm
Server: Hono
paymentMiddleware
from
@x402/hono
@x402/hono @x402/core @x402/evm
Client: fetch
wrapFetchWithPayment
@x402/fetch @x402/core @x402/evm viem
Client: axios
wrapAxiosWithPayment
@x402/axios @x402/core @x402/evm viem axios
Client: manual
x402Client
+
x402HTTPClient
from
@x402/core
@x402/core @x402/evm viem
Chain: EVM
registerExactEvmScheme
@x402/evm
+
viem
Chain: Solana
registerExactSvmScheme
@x402/svm
+
@solana/kit @scure/base
Chain: bothRegister both schemes on same client/serverAll chain deps
Env: testingFacilitator
https://x402.org/facilitator
Base Sepolia / Solana Devnet
Env: productionCDP facilitator + API keysBase Mainnet / Solana Mainnet
Agent: MCPMCP server with
@x402/axios
See
references/agentic-patterns.md
Agent: AnthropicTool-use with
@x402/fetch
See
references/agentic-patterns.md
决策选项依赖包
服务器:Express使用
@x402/express
中的
paymentMiddleware
@x402/express @x402/core @x402/evm
服务器:Next.js使用
@x402/next
中的
paymentProxy
@x402/next @x402/core @x402/evm
服务器:Hono使用
@x402/hono
中的
paymentMiddleware
@x402/hono @x402/core @x402/evm
客户端:fetch使用
wrapFetchWithPayment
@x402/fetch @x402/core @x402/evm viem
客户端:axios使用
wrapAxiosWithPayment
@x402/axios @x402/core @x402/evm viem axios
客户端:手动实现使用
@x402/core
中的
x402Client
+
x402HTTPClient
@x402/core @x402/evm viem
链:EVM使用
registerExactEvmScheme
@x402/evm
+
viem
链:Solana使用
registerExactSvmScheme
@x402/svm
+
@solana/kit @scure/base
链:同时支持两者在同一客户端/服务器上注册两种方案所有链相关依赖
环境:测试使用支付服务商
https://x402.org/facilitator
Base Sepolia / Solana Devnet
环境:生产使用CDP支付服务商 + API密钥Base Mainnet / Solana Mainnet
Agent:MCP结合
@x402/axios
实现MCP服务器
详见
references/agentic-patterns.md
Agent:Anthropic结合
@x402/fetch
实现工具调用
详见
references/agentic-patterns.md

Reference File Navigation

参考文件导航

TaskRead this file
Headers, payloads, CAIP-2 IDs, facilitator API, V1→V2 changes
references/protocol-spec.md
Express / Hono / Next.js middleware, multi-route, dynamic pricing
references/server-patterns.md
Fetch / axios client, wallet setup, lifecycle hooks, error handling
references/client-patterns.md
AI agent payments, MCP server, tool discovery, budget controls
references/agentic-patterns.md
Testnet→mainnet migration, CDP keys, faucets, security, sessions
references/deployment.md
任务参考文件
请求头、负载、CAIP-2 ID、支付服务商API、V1→V2变更
references/protocol-spec.md
Express / Hono / Next.js中间件、多路由、动态定价
references/server-patterns.md
Fetch / axios客户端、钱包设置、生命周期钩子、错误处理
references/client-patterns.md
AI Agent支付、MCP服务器、工具发现、预算控制
references/agentic-patterns.md
测试网→主网迁移、CDP密钥、水龙头、安全、会话
references/deployment.md

Critical Implementation Notes

关键实现注意事项

  1. Register schemes before wrapping fetch/axios — order matters.
  2. Two equivalent registration APIs:
    • Function:
      registerExactEvmScheme(server)
      /
      registerExactEvmScheme(client, { signer })
    • Method:
      server.register("eip155:84532", new ExactEvmScheme())
  3. V2 headers (current):
    PAYMENT-REQUIRED
    ,
    PAYMENT-SIGNATURE
    ,
    PAYMENT-RESPONSE
    . V1 headers (legacy):
    X-PAYMENT
    ,
    X-PAYMENT-RESPONSE
    . SDK is backward-compatible.
  4. Price format:
    "$0.001"
    (dollar string) — SDK converts to atomic units (6 decimals for USDC).
  5. Python SDK uses V1 patterns only. Use TypeScript or Go for V2.
  6. Node.js v24+ required for the TypeScript SDK.
  7. Repo:
    https://github.com/coinbase/x402
    — canonical examples in
    examples/typescript/
    .
  8. Docs:
    https://docs.cdp.coinbase.com/x402/welcome
    and
    https://x402.gitbook.io/x402
    .
  1. 注册方案需在包装fetch/axios之前完成——顺序很重要。
  2. 两种等效的注册API
    • 函数式:
      registerExactEvmScheme(server)
      /
      registerExactEvmScheme(client, { signer })
    • 方法式:
      server.register("eip155:84532", new ExactEvmScheme())
  3. V2请求头(当前版本):
    PAYMENT-REQUIRED
    PAYMENT-SIGNATURE
    PAYMENT-RESPONSE
    。 V1请求头(旧版):
    X-PAYMENT
    X-PAYMENT-RESPONSE
    。SDK向后兼容。
  4. 价格格式
    "$0.001"
    (美元字符串)——SDK会转换为原子单位(USDC为6位小数)。
  5. Python SDK仅支持V1模式,如需使用V2请选择TypeScript或Go。
  6. TypeScript SDK要求Node.js v24+
  7. 代码仓库
    https://github.com/coinbase/x402
    ——标准示例位于
    examples/typescript/
    目录下。
  8. 文档
    https://docs.cdp.coinbase.com/x402/welcome
    https://x402.gitbook.io/x402