x402-proxy 模板是位于任意 HTTP 后端前方的 Cloudflare Worker。当请求命中受保护路由时,proxy 返回带支付说明的 402 响应。客户端支付后,proxy 验证支付并将请求转发到 origin。
将 x402-proxy 模板部署到你的 Cloudflare 账户:
- Cloudflare 账户 ↗
- 需要设门禁的 HTTP 后端
- 用于收款的 wallet 地址
在 wrangler.jsonc 中定义受保护路由:
{
"vars": {
"PAY_TO": "0xYourWalletAddress",
"NETWORK": "base-sepolia",
"PROTECTED_PATTERNS": [
{
"pattern": "/api/premium/*",
"price": "$0.10",
"description": "Premium API access"
}
]
}
}配合 Bot Management,proxy 可对 crawler 收费,同时让人类用户免费访问:
{
"pattern": "/content/*",
"price": "$0.10",
"description": "Content access",
"bot_score_threshold": 30,
"except_detection_ids": [117479730]
}bot score 低于或等于 bot_score_threshold 的请求会被导向 paywall。使用 except_detection_ids 按 detection ID 将特定 crawler 加入 allowlist。
克隆模板,编辑 wrangler.jsonc 并部署:
git clone https://github.com/cloudflare/templates
cd templates/x402-proxy-template
npm install
npx wrangler deploy完整配置选项与 Bot Management 示例请参阅 template README ↗。
如需更多控制,使用 Hono 将 x402 中间件直接加入 Worker:
import { Hono } from "hono";
import { paymentMiddleware } from "x402-hono";
const app = new Hono<{ Bindings: Env }>();
app.use(
paymentMiddleware(
"0xYourWalletAddress" as `0x${string}`,
{
"/premium": {
price: "$0.10",
network: "base-sepolia",
config: { description: "Premium content" },
},
},
{ url: "https://x402.org/facilitator" },
),
);
app.get("/premium", (c) => c.json({ message: "Thanks for paying!" }));
export default app;完整实现请参阅 x402 Workers 示例 ↗。
- Pay Per Crawl — 无需自定义代码的 Cloudflare 原生 monetization
- 对 MCP 工具收费 — 按工具调用而非按请求收费
- x402.org ↗ — 协议规范