mcpField
X
x402

x402

github.com/tenequm开发3979 次安装1 天前更新
代码仓库

关于 x402

x402 是用于开发基于 HTTP 的链上支付的工具包,为买卖双方提供多种语言的 SDK 和中间件。它支持 API、网页内容和 Agent 可访问资源的支付流程,并包含 MCP 集成。

主要功能

  1. 01基于 HTTP 402 的支付流程
  2. 02买方和卖方 SDK
  3. 03中间件与 HTTP 客户端封装
  4. 04支持多个区块链网络
  5. 05提供 MCP 客户端和服务端包
  6. 06支持定额与按用量计费方案

适用场景

  1. 01为 API 接收加密货币小额支付
  2. 02为网页内容添加付费墙
  3. 03让 Agent 为资源自动付款
  4. 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.md
LICENSE.txt
references/
aptos-scheme.md
core-concepts.md
evm-scheme.md
extensions.md
go-sdk.md
lifecycle-hooks.md
near-scheme.md
protocol-spec.md
python-sdk.md
stellar-scheme.md
svm-scheme.md
transports.md
typescript-sdk.md
upto-scheme.md
xrpl-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 支付都包含三个角色:

  1. 资源服务 - 保护端点,并返回包含支付要求的 402 响应
  2. 客户端 - 签署支付授权,并在支付标头中携带付款信息重试请求
  3. 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 Sepoliaeip155:84532测试网
MegaETH 主网eip155:4326主网(默认使用 MegaUSD,18 位小数)
Solana 主网solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp主网
Solana Devnetsolana: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 Amoyeip155:80002测试网
Stable 主网eip155:988主网
Stable 测试网eip155:2201测试网
Arbitrum Oneeip155:42161主网
Arbitrum Sepoliaeip155: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)
Avalancheeip155:43114仅支持运行时注册(无默认资产;由社区提供 facilitator)
Radius 主网eip155:723487主网(默认使用 SBC)
Radius 测试网eip155:72344测试网(默认使用 SBC)
ADI Chaineip155:36900主网(默认使用 USDC.e)
HPP 主网eip155:190415主网(默认使用桥接 USDC)
HPP Sepoliaeip155: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 Devnetxrpl:2Devnet

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.org facilitator 面向开发和测试网工作流 — 不要假设它是生产主网路由的默认方案。生产环境可选方案请参阅 facilitator 目录。

SDK 包

TypeScript v2.20.0(npm,GitHub)
包用途
@x402/core核心类型、客户端、服务端、facilitator
@x402/evmEVM exact + upto 方案(EIP-3009、Permit2)。upto 可通过 @x402/evm/upto/* 子路径使用
@x402/svmSolana 方案(SPL TransferChecked)
@x402/stellarStellar 方案(SEP-41 Soroban 代币转账)
@x402/aptosAptos 方案(Fungible Asset 转账)
@x402/avmAlgorand(AVM)方案
@x402/hederaHedera 方案(HBAR + HTS 同质化资产转账)
@x402/tvmTON 方案(jetton 转账)
@x402/keetaKeeta 方案(exact)
@x402/concordiumConcordium 方案(原生 CCD、exact)
@x402/nearNEAR 方案(NEP-366 SignedDelegate + NEP-141 ft_transfer,由中继方赞助)
@x402/xrplXRPL 方案(付款方签名的 Payment,不提供手续费赞助)。标记为 2.20.0,但尚未发布到 npm——需从源代码构建
@x402/expressExpress 中间件
@x402/fastifyFastify 中间件
@x402/honoHono 边缘中间件
@x402/nextNext.js 中间件
@x402/axiosAxios 拦截器
@x402/fetchFetch 封装
@x402/paywall浏览器付费墙 UI
@x402/mcpMCP 客户端 + 服务端
@x402/extensionsBazaar、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.mdHTTP 402 基础、客户端/服务端/协调器角色、钱包身份、网络、代币、自定义代币配置、动态注册、可自托管的协调器、主网部署
references/protocol-spec.mdv2 协议类型、支付流程、协调器 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.mdEVM 精确方案:EIP-3009、Permit2、默认资产解析、registerMoneyParser、自定义代币
references/svm-scheme.mdSolana 精确方案:SPL TransferChecked、验证规则、重复结算缓解措施
references/stellar-scheme.mdStellar 精确方案:SEP-41 Soroban 代币转账、基于账本的过期机制、费用赞助,仅支持 TypeScript SDK
references/upto-scheme.mdUpto(基于用量)方案:授权最大金额,结算实际用量。EVM 仅支持 Permit2
references/aptos-scheme.mdAptos 精确方案:同质化资产转账、费用付款方赞助,仅支持 TypeScript SDK
references/near-scheme.mdNEAR 精确方案:NEP-366 SignedDelegate、NEP-141 ft_transfer、中继器 Gas 赞助、需要完全访问权限密钥、NEP-145 存储注册
references/xrpl-scheme.mdXRPL 精确方案:付款方签名的 Payment、不支持费用赞助、显式 AssetAmount 定价、sequence 与 ticketSequence
references/transports.mdHTTP、MCP、A2A 传输实现
references/extensions.mdBazaar、payment-identifier、sign-in-with-x、Gas 赞助(eip2612 + erc20)扩展
references/lifecycle-hooks.md客户端/服务端/协调器钩子(TypeScript、Python、Go)、钩子链式调用、MCP 钩子

官方资源

评论

支持 Markdown