关于 x402
x402 是用于开发基于 HTTP 的链上支付的工具包,为买卖双方提供多种语言的 SDK 和中间件。它支持 API、网页内容和 Agent 可访问资源的支付流程,并包含 MCP 集成。
主要功能
- 01基于 HTTP 402 的支付流程
- 02买方和卖方 SDK
- 03中间件与 HTTP 客户端封装
- 04支持多个区块链网络
- 05提供 MCP 客户端和服务端包
- 06支持定额与按用量计费方案
适用场景
- 01为 API 接收加密货币小额支付
- 02为网页内容添加付费墙
- 03让 Agent 为资源自动付款
- 04为 MCP 工具设置付费要求
MCP 相关
SDK 包含面向 MCP 客户端和服务端的 `@x402/mcp`,也提供 Python MCP 集成,可用于 MCP 工具的支付流程。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ tenequm/ skills --skill x402安装后在 Claude Code 中输入/x402确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
CHANGELOG.mdLICENSE.txtreferences/aptos-scheme.mdcore-concepts.mdevm-scheme.mdextensions.mdgo-sdk.mdlifecycle-hooks.mdnear-scheme.mdprotocol-spec.mdpython-sdk.mdstellar-scheme.mdsvm-scheme.mdtransports.mdtypescript-sdk.mdupto-scheme.mdxrpl-scheme.md详细介绍
x402 协议开发
x402 是一项开放标准(Apache-2.0),用于启用 HTTP 402 Payment Required 状态码,以支持程序化链上支付。该标准最初由 Coinbase 创建,现由 x402 Foundation 维护。无需账户、会话或 API 密钥——客户端直接通过 HTTP 使用签名的加密货币交易付款。
适用场景
- 构建接受加密货币微支付的付费 API
- 为网页内容或端点添加付费墙
- 让 AI Agent 能够自主支付资源费用
- 集成需要付费的 MCP 工具
- 构建 Agent 对 Agent(A2A)支付流程
- 使用 EVM(Base、Ethereum、MegaETH、Monad、Polygon、Stable、Arbitrum)、Solana、Stellar、Aptos、NEAR 或 XRPL 进行支付结算
- 使用
upto方案实现按使用量计费(大模型令牌、带宽、计算资源) - 运行进程内 Facilitator(自行处理支付),无需依赖外部 Facilitator
核心架构
每笔 x402 支付都包含三个角色:
- 资源服务 - 保护端点,并返回包含支付要求的 402 响应
- 客户端 - 签署支付授权,并在支付标头中携带付款信息重试请求
- Facilitator - 验证签名,并在链上结算交易
支付流程(HTTP 传输):
Client -> GET /resource -> Server returns 402 + PAYMENT-REQUIRED header
Client -> signs payment -> retries with PAYMENT-SIGNATURE header
Server -> POST /verify to Facilitator -> POST /settle to Facilitator
Server -> returns 200 + PAYMENT-RESPONSE header + resource data
快速入门:卖方(TypeScript + Express)
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { HTTPFacilitatorClient } from "@x402/core/server";
const app = express();
const payTo = "0xYourWalletAddress";
const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const server = new x402ResourceServer(facilitator)
.register("eip155:84532", new ExactEvmScheme());
app.use(
paymentMiddleware(
{
"GET /weather": {
accepts: [
{ scheme: "exact", price: "$0.001", network: "eip155:84532", payTo },
],
description: "Weather data",
mimeType: "application/json",
},
},
server,
),
);
app.get("/weather", (req, res) => {
res.json({ weather: "sunny", temperature: 70 });
});
app.listen(4021);
安装:npm install @x402/express @x402/core @x402/evm
快速入门:买方(TypeScript + Axios)
import { x402Client, wrapAxiosWithPayment } from "@x402/axios";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";
import axios from "axios";
const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });
const api = wrapAxiosWithPayment(axios.create(), client);
const response = await api.get("http://localhost:4021/weather");
// Payment handled automatically on 402 response
安装:npm install @x402/axios @x402/evm viem
快速入门:卖方(Python + FastAPI)
from fastapi import FastAPI
from x402.http import FacilitatorConfig, HTTPFacilitatorClient, PaymentOption
from x402.http.middleware.fastapi import PaymentMiddlewareASGI
from x402.http.types import RouteConfig
from x402.mechanisms.evm.exact import ExactEvmServerScheme
from x402.server import x402ResourceServer
app = FastAPI()
facilitator = HTTPFacilitatorClient(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServer(facilitator)
server.register("eip155:84532", ExactEvmServerScheme())
routes = {
"GET /weather": RouteConfig(
accepts=[PaymentOption(scheme="exact", pay_to="0xYourAddress", price="$0.001", network="eip155:84532")],
mime_type="application/json",
description="Weather data",
),
}
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)
@app.get("/weather")
async def get_weather():
return {"weather": "sunny", "temperature": 70}
安装:pip install "x402[fastapi,evm]"
快速入门:卖方(Go + Gin)
import (
x402http "github.com/x402-foundation/x402/go/v2/http"
ginmw "github.com/x402-foundation/x402/go/v2/http/gin"
evm "github.com/x402-foundation/x402/go/v2/mechanisms/evm/exact/server"
)
facilitator := x402http.NewHTTPFacilitatorClient(&x402http.FacilitatorConfig{URL: facilitatorURL})
routes := x402http.RoutesConfig{
"GET /weather": {
Accepts: x402http.PaymentOptions{
{Scheme: "exact", Price: "$0.001", Network: "eip155:84532", PayTo: evmAddress},
},
Description: "Weather data",
MimeType: "application/json",
},
}
r.Use(ginmw.X402Payment(ginmw.Config{
Routes: routes,
Facilitator: facilitator,
Schemes: []ginmw.SchemeConfig{{Network: "eip155:84532", Server: evm.NewExactEvmScheme()}},
}))
安装:go get github.com/x402-foundation/x402/go/v2
多网络支持(EVM + Solana)
服务端可以同时接受来自多个网络的付款:
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";
const server = new x402ResourceServer(facilitator)
.register("eip155:84532", new ExactEvmScheme())
.register("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", new ExactSvmScheme());
// Route config with both networks
"GET /weather": {
accepts: [
{ scheme: "exact", price: "$0.001", network: "eip155:84532", payTo: evmAddress },
{ scheme: "exact", price: "$0.001", network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", payTo: svmAddress },
],
}
客户端注册这两种方案,并根据服务端的要求自动选择:
const client = new x402Client();
registerExactEvmScheme(client, { signer: evmSigner });
registerExactSvmScheme(client, { signer: svmSigner });
支持的网络
| 网络 | CAIP-2 ID | 状态 |
|---|---|---|
| Base 主网 | eip155:8453 | 主网 |
| Base Sepolia | eip155:84532 | 测试网 |
| MegaETH 主网 | eip155:4326 | 主网(默认使用 MegaUSD,18 位小数) |
| Solana 主网 | solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp | 主网 |
| Solana Devnet | solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 | 测试网 |
| Stellar 主网 | stellar:pubnet | 主网(仅限 TypeScript SDK) |
| Stellar 测试网 | stellar:testnet | 测试网(仅限 TypeScript SDK) |
| Aptos 主网 | aptos:1 | 主网(仅限 TypeScript SDK) |
| Aptos 测试网 | aptos:2 | 测试网(仅限 TypeScript SDK) |
| Monad 主网 | eip155:143 | 主网 |
| Polygon 主网 | eip155:137 | 主网 |
| Polygon Amoy | eip155:80002 | 测试网 |
| Stable 主网 | eip155:988 | 主网 |
| Stable 测试网 | eip155:2201 | 测试网 |
| Arbitrum One | eip155:42161 | 主网 |
| Arbitrum Sepolia | eip155:421614 | 测试网 |
| XDC Network 主网 | eip155:50 | 主网(USDC) |
| XDC Apothem 测试网 | eip155:51 | 测试网(USDC) |
| Mezo 主网 | eip155:31612 | 主网(mUSD,18 位小数,Permit2 + EIP-2612) |
| Mezo 测试网 | eip155:31611 | 测试网(mUSD,Permit2 + EIP-2612) |
| Avalanche | eip155:43114 | 仅支持运行时注册(无默认资产;由社区提供 facilitator) |
| Radius 主网 | eip155:723487 | 主网(默认使用 SBC) |
| Radius 测试网 | eip155:72344 | 测试网(默认使用 SBC) |
| ADI Chain | eip155:36900 | 主网(默认使用 USDC.e) |
| HPP 主网 | eip155:190415 | 主网(默认使用桥接 USDC) |
| HPP Sepolia | eip155:181228 | 测试网(默认使用桥接 USDC) |
| TON 主网 | tvm:-239 | 主网(jetton 转账;Python + TypeScript SDK) |
| TON 测试网 | tvm:-3 | 测试网 |
| Hedera 主网 | hedera:mainnet | 主网(HBAR + HTS 代币) |
| Hedera 测试网 | hedera:testnet | 测试网 |
| Algorand 主网 | algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k | 主网(USDC ASA) |
| Algorand 测试网 | algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDe | 测试网(USDC ASA) |
| Keeta 主网 | keeta:21378 | 主网(TypeScript SDK) |
| Keeta 测试网 | keeta:1413829460 | 测试网(TypeScript SDK) |
| Concordium 主网 | ccd:9dd9ca4d19e9393877d2c44b70f89acb | 主网(原生 CCD,6 位小数;TypeScript SDK) |
| Concordium 测试网 | ccd:4221332d34e1694168c2a0c0b3fd0f27 | 测试网(原生 CCD;TypeScript SDK) |
| Igra 主网 | eip155:38833 | 主网(USDC,仅支持 Permit2 — 不支持 EIP-3009 或 EIP-2612) |
| NEAR 主网 | near:mainnet | 主网(NEP-141 USDC,由 relayer 赞助;TypeScript SDK) |
| NEAR 测试网 | near:testnet | 测试网(TypeScript SDK) |
| XRPL 主网 | xrpl:0 | 主网(XRP + IOU,不支持费用赞助;TypeScript SDK) |
| XRPL 测试网 | xrpl:1 | 测试网 |
| XRPL Devnet | xrpl:2 | Devnet |
Algorand CAIP-2 ID 已更改。 参考值为 URL 安全的 base64 创世哈希,截取前 32 个字符。旧的带填充完整哈希格式(
algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=)已不再匹配;SDK 会在输入时规范化旧版 ID,但输出时会使用截断格式。
默认 facilitator(https://x402.org/facilitator)支持 Base Sepolia、Solana Devnet、Algorand 测试网、Stellar 测试网、Aptos 测试网、Hedera 测试网和 XRPL 测试网。在 Base Sepolia 上,它会公布 exact、upto 以及 batch-settlement,还会公布 builder-code、eip2612GasSponsoring 和 erc20ApprovalGasSponsoring 扩展。
不适用于生产环境的默认选项。 上游现在明确指出,公共
x402.orgfacilitator 面向开发和测试网工作流 — 不要假设它是生产主网路由的默认方案。生产环境可选方案请参阅 facilitator 目录。
SDK 包
TypeScript v2.20.0(npm,GitHub)
| 包 | 用途 |
|---|---|
@x402/core | 核心类型、客户端、服务端、facilitator |
@x402/evm | EVM exact + upto 方案(EIP-3009、Permit2)。upto 可通过 @x402/evm/upto/* 子路径使用 |
@x402/svm | Solana 方案(SPL TransferChecked) |
@x402/stellar | Stellar 方案(SEP-41 Soroban 代币转账) |
@x402/aptos | Aptos 方案(Fungible Asset 转账) |
@x402/avm | Algorand(AVM)方案 |
@x402/hedera | Hedera 方案(HBAR + HTS 同质化资产转账) |
@x402/tvm | TON 方案(jetton 转账) |
@x402/keeta | Keeta 方案(exact) |
@x402/concordium | Concordium 方案(原生 CCD、exact) |
@x402/near | NEAR 方案(NEP-366 SignedDelegate + NEP-141 ft_transfer,由中继方赞助) |
@x402/xrpl | XRPL 方案(付款方签名的 Payment,不提供手续费赞助)。标记为 2.20.0,但尚未发布到 npm——需从源代码构建 |
@x402/express | Express 中间件 |
@x402/fastify | Fastify 中间件 |
@x402/hono | Hono 边缘中间件 |
@x402/next | Next.js 中间件 |
@x402/axios | Axios 拦截器 |
@x402/fetch | Fetch 封装 |
@x402/paywall | 浏览器付费墙 UI |
@x402/mcp | MCP 客户端 + 服务端 |
@x402/extensions | Bazaar、offer-receipt、payment-identifier、sign-in-with-x、燃料费赞助 |
Python v2.17.0(PyPI,GitHub)
pip install "x402[httpx]" # Async HTTP client
pip install "x402[requests]" # Sync HTTP client
pip install "x402[fastapi]" # FastAPI server
pip install "x402[flask]" # Flask server
pip install "x402[evm]" # EVM support
pip install "x402[svm]" # Solana support
pip install "x402[tvm]" # TON support
pip install "x402[mcp]" # MCP integration
pip install "x402[extensions]" # Extensions (bazaar, gas sponsoring, etc.)
pip install "x402[all]" # Everything
便捷套件:clients(httpx + requests)、servers(flask + fastapi)、mechanisms(evm + svm + tvm)。
Go v2.20.0(GitHub)
Go 模块路径带有 /v2 后缀——裸路径 .../x402/go 不再能解析带标签的发行版本。
go get github.com/x402-foundation/x402/go/v2
Java(Java 17+,GitHub)
仓库中包含第四个官方绑定(PaymentFilter、FacilitatorClient、X402HttpClient)。尚未发布到软件包注册表——需从源代码构建。
核心概念
- 客户端/服务端/协调方:每笔支付中的三个角色。客户端签名,服务端执行,协调方在链上结算。请参阅
references/core-concepts.md - 钱包:既是买卖双方的支付机制,也是身份标识。请参阅
references/core-concepts.md - 网络与代币:CAIP-2 标识符、EVM 上的 EIP-3009 代币、Solana 上的 SPL、自定义代币配置。请参阅
references/core-concepts.md - 方案:支付方式。
exact= 转账确切金额;upto= 授权最高金额,按实际用量结算(正在开发的 SDK 仅支持 EVM Permit2;基于 Solana 支付通道的 SVM 绑定草案仍处于规范制定阶段);batch-settlement= 在请求时提交,之后异步结算;auth-capture= 托管/先授权后扣款,并支持作废、退款和收回。请参阅references/evm-scheme.md、references/svm-scheme.md、references/stellar-scheme.md、references/upto-scheme.md、references/aptos-scheme.md、references/near-scheme.md、references/xrpl-scheme.md、references/protocol-spec.md - 自行协调:运行进程内协调方,而不是调用外部 URL。请参阅
references/typescript-sdk.md、references/go-sdk.md - 传输:支付数据的传输方式(HTTP 标头、MCP
_meta、A2A 元数据)。请参阅references/transports.md - 扩展:可选功能(bazaar 发现、offer-receipt 证明、payment-identifier 幂等性、sign-in-with-x 身份验证、Gas 赞助、builder-code 归属、http-message-signatures、auth-hints)。请参阅
references/extensions.md - 钩子:客户端/服务端/协调方的生命周期回调(TS、Python、Go)。请参阅
references/lifecycle-hooks.md - 协议类型:
PaymentRequired、PaymentPayload、SettlementResponse。请参阅references/protocol-spec.md - 自定义代币:对非 USDC 代币使用
registerMoneyParser,对非 EIP-3009 代币使用 Permit2。请参阅references/evm-scheme.md - 主网部署:切换协调方 URL、网络 ID 和钱包地址。请参阅
references/core-concepts.md
参考资料
| 文件 | 内容 |
|---|---|
references/core-concepts.md | HTTP 402 基础、客户端/服务端/协调器角色、钱包身份、网络、代币、自定义代币配置、动态注册、可自托管的协调器、主网部署 |
references/protocol-spec.md | v2 协议类型、支付流程、协调器 API、错误代码 |
references/typescript-sdk.md | 服务端、客户端、MCP、付费墙和协调器的 TypeScript SDK 模式 |
references/python-sdk.md | 服务端、客户端、MCP(服务端 + 客户端)和协调器的 Python SDK 模式 |
references/go-sdk.md | 服务端、客户端、MCP、协调器、签名器和自定义货币解析器的 Go SDK 模式 |
references/evm-scheme.md | EVM 精确方案:EIP-3009、Permit2、默认资产解析、registerMoneyParser、自定义代币 |
references/svm-scheme.md | Solana 精确方案:SPL TransferChecked、验证规则、重复结算缓解措施 |
references/stellar-scheme.md | Stellar 精确方案:SEP-41 Soroban 代币转账、基于账本的过期机制、费用赞助,仅支持 TypeScript SDK |
references/upto-scheme.md | Upto(基于用量)方案:授权最大金额,结算实际用量。EVM 仅支持 Permit2 |
references/aptos-scheme.md | Aptos 精确方案:同质化资产转账、费用付款方赞助,仅支持 TypeScript SDK |
references/near-scheme.md | NEAR 精确方案:NEP-366 SignedDelegate、NEP-141 ft_transfer、中继器 Gas 赞助、需要完全访问权限密钥、NEP-145 存储注册 |
references/xrpl-scheme.md | XRPL 精确方案:付款方签名的 Payment、不支持费用赞助、显式 AssetAmount 定价、sequence 与 ticketSequence |
references/transports.md | HTTP、MCP、A2A 传输实现 |
references/extensions.md | Bazaar、payment-identifier、sign-in-with-x、Gas 赞助(eip2612 + erc20)扩展 |
references/lifecycle-hooks.md | 客户端/服务端/协调器钩子(TypeScript、Python、Go)、钩子链式调用、MCP 钩子 |
官方资源
- GitHub:https://github.com/x402-foundation/x402
- 规范:https://github.com/x402-foundation/x402/tree/main/specs
- 文档:https://docs.x402.org
- 网站:https://x402.org
- 协调器目录 - 列出具名的生产级和社区协调器
- 第三方 SDK - Rust(
x402-rs)、Java(Mogami)、Ruby(x402-rails)以及三种官方绑定之外的其他 SDK - 第三方扩展 - 生态系统扩展包
- 社区:Slack 地址为 http://slack.x402.org/(该项目已从 Discord 迁出)
- 基金会章程:https://github.com/x402-foundation/x402/tree/main/foundation