创建 x402 支付保护服务器
使用 FastAPI(异步)或 Flask(同步)为 Algorand 创建 x402 支付保护服务器。当构建需要 USDC 支付的资源服务器时使用,包括设置支付中间件、配置路由定价或使用 x402 保护 API 端点。强触发词包括“创建带有 x402 支付的 FastAPI 服务器”、“向 Flask 添加支付中间件”、“使用 Algorand USDC 保护我的 API 端点”、“在 Python 中设置 x402 资源服务器”、“PaymentMiddlewareASGI 设置”、“Flask PaymentMiddleware”、“我如何在 API 上接受 Algorand 支付?”、“多网络支付服务器”、“x402 路由配置”。
前提条件
在使用此技能之前,请确保:
- 安装了 Python 3.10+
- 一个 Algorand 地址 用于接收支付(
payTo地址) - 一个协调者 URL —— 使用
https://x402.org/facilitator或者运行你自己的 - 了解 FastAPI 或 Flask 基础知识
核心工作流程:基于中间件的支付保护
中间件拦截对受保护路由的请求,检查支付头部,通过协调者验证支付,并在成功时结算。
客户端请求
|
v
x402 中间件(检查路由配置)
|
+-- 未受保护 -> 传递到处理器
|
+-- 受保护,无支付 -> 返回 402 与 PaymentRequirements
|
+-- 受保护,有支付 -> 通过协调者验证
|
+-- 无效 -> 返回 402
|
+-- 有效 -> 调用处理器,然后结算支付
如何进行
第 1 步:安装依赖项
对于 FastAPI(异步):
pip install "x402-avm[fastapi,avm]"
对于 Flask(同步):
pip install "x402-avm[flask,avm]"
第 2 步:选择您的框架模式
FastAPI 使用异步组件:
x402ResourceServer(异步)HTTPFacilitatorClient(异步)PaymentMiddlewareASGI或payment_middleware
Flask 使用同步组件:
x402ResourceServerSync(同步)HTTPFacilitatorClientSync(同步)PaymentMiddleware或payment_middleware
第 3 步:设置资源服务器
创建协调者客户端、资源服务器,并注册 AVM 方案:
FastAPI:
from x402.server import x402ResourceServer
from x402.http import HTTPFacilitatorClient, FacilitatorConfig
from x402.mechanisms.avm.exact import ExactAvmServerScheme
facilitator = HTTPFacilitatorClient(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServer(facilitator)
server.register("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", ExactAvmServerScheme())
Flask:
from x402.server import x402ResourceServerSync
from x402.http import HTTPFacilitatorClientSync, FacilitatorConfig
from x402.mechanisms.avm.exact import ExactAvmServerScheme
facilitator = HTTPFacilitatorClientSync(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServerSync(facilitator)
server.register("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", ExactAvmServerScheme())
第 4 步:定义路由配置
路由将 HTTP 方法 + 路径模式映射到支付要求:
from x402.http import PaymentOption
from x402.http.types import RouteConfig
routes = {
"GET /api/weather": RouteConfig(
accepts=PaymentOption(
scheme="exact",
network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
pay_to="YOUR_ALGORAND_ADDRESS",
price="$0.01",
),
),
}
第 5 步:应用中间件
FastAPI – 选项 A(ASGI 类,推荐):
from x402.http.middleware.fastapi import PaymentMiddlewareASGI
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)
FastAPI – 选项 B(基于函数):
from x402.http.middleware.fastapi import payment_middleware
x402_mw = payment_middleware(routes=routes, server=server)
@app.middleware("http")
async def x402_middleware(request, call_next):
return await x402_mw(request, call_next)
Flask:
from x402.http.middleware.flask import PaymentMiddleware
PaymentMiddleware(app, routes, server)
第 6 步:定义路由处理器
在配置中列出的路由需要支付。未列出的路由自由通过。
FastAPI:
@app.get("/api/weather")
async def get_weather():
return {"temperature": 72, "unit": "F"}
Flask:
@app.route("/api/weather")
def get_weather():
return {"temperature": 72, "unit": "F"}
重要规则 / 指南
- 匹配异步/同步变体 —— FastAPI 使用
x402ResourceServer+HTTPFacilitatorClient,Flask 使用x402ResourceServerSync+HTTPFacilitatorClientSync - 路由格式 —— 键必须是
"METHOD /path"(例如,"GET /api/weather","POST /api/generate/*") - 通配符路径 —— 使用
/*后缀匹配所有子路径(例如,"GET /api/premium/*") - 未列出的路由通过 —— 只有在配置中的路由需要支付
- 在中间件之前注册方案 —— 在添加中间件之前调用
server.register(...) - 价格格式 —— 使用
"$0.01"用于自动转换或AssetAmount(amount="10000", asset="10458941")用于显式控制 - CAIP-2 网络 ID —— 使用完整的 CAIP-2 标识符,如
"algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="
定价选项
简单字符串价格
PaymentOption(
scheme="exact",
network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
pay_to="YOUR_ADDRESS",
price="$0.01", # 自动转换为 10000 微 USDC
)
显式 AssetAmount
from x402.schemas import AssetAmount
PaymentOption(
scheme="exact",
network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
pay_to="YOUR_ADDRESS",
price=AssetAmount(
amount="50000", # 50000 微 USDC = $0.05
asset="10458941", # 测试网上的 USDC ASA ID
extra={"name": "USDC", "decimals": 6},
),
)
多网络(AVM + EVM + SVM)
routes = {
"GET /api/data/*": RouteConfig(
accepts=[
PaymentOption(scheme="exact", pay_to=AVM_ADDRESS, price="$0.01",
network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="),
PaymentOption(scheme="exact", pay_to=EVM_ADDRESS, price="$0.01",
network="eip155:84532"),
PaymentOption(scheme="exact", pay_to=SVM_ADDRESS, price="$0.01",
network="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"),
],
),
}
常见错误 / 故障排除
| 错误 | 原因 | 解决方案 |
|---|---|---|
TypeError: async 错误在 Flask 中 |
使用 Flask 的异步变体 | 使用 x402ResourceServerSync 和 HTTPFacilitatorClientSync |
| 所有请求都返回 402 | 中间件应用但协调者无法访问 | 检查 FACILITATOR_URL 和网络连接 |
| 路由未受保护 | 路径模式不匹配 | 验证路由键格式匹配:"GET /exact/path" 或 "GET /prefix/*" |
| 结算失败 | 协调者无法访问 Algorand 网络 | 检查协调者日志和 algod 端点 |
中间件上的 ImportError |
缺少额外内容 | pip install "x402-avm[fastapi,avm]" 或 "x402-avm[flask,avm]" |
参考资料 / 进一步阅读
- REFERENCE.md - 中间件的详细 API 参考
- EXAMPLES.md - FastAPI 和 Flask 的完整代码示例
- x402-avm 示例存储库
- x402 Algorand 文档