monetize-service
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBuild an x402 Payment Server
构建x402支付服务器
Create an Express server that charges USDC for API access using the x402 payment protocol. Callers pay per-request in USDC on Base — no accounts, API keys, or subscriptions needed.
创建一个基于Express的服务器,通过x402支付协议对API访问收取USDC费用。调用者在Base网络上按请求支付USDC——无需账户、API密钥或订阅。
How It Works
工作原理
x402 is an HTTP-native payment protocol. When a client hits a protected endpoint without paying, the server returns HTTP 402 with payment requirements. The client signs a USDC payment and retries with a payment header. The facilitator verifies and settles the payment, and the server returns the response.
x402是一个原生HTTP支付协议。当客户端未付费就访问受保护的端点时,服务器会返回HTTP 402状态码及付款要求。客户端签署USDC付款并携带付款头重试请求,支付服务商验证并完成付款结算后,服务器返回响应内容。
Confirm wallet is initialized and authed
确认钱包已初始化并认证
bash
npx awal@latest statusIf the wallet is not authenticated, refer to the skill.
authenticate-walletbash
npx awal@latest status如果钱包未认证,请参考技能。
authenticate-walletStep 1: Get the Payment Address
步骤1:获取收款地址
Run this to get the wallet address that will receive payments:
bash
npx awal@latest addressUse this address as the value.
payTo运行以下命令获取将接收付款的钱包地址:
bash
npx awal@latest address将此地址作为的值。
payToStep 2: Set Up the Project
步骤2:搭建项目
bash
mkdir x402-server && cd x402-server
npm init -y
npm install express x402-expressCreate :
index.jsjs
const express = require("express");
const { paymentMiddleware } = require("x402-express");
const app = express();
app.use(express.json());
const PAY_TO = "<address from step 1>";
// x402 payment middleware — protects routes below
const payment = paymentMiddleware(PAY_TO, {
"GET /api/example": {
price: "$0.01",
network: "base",
config: {
description: "Description of what this endpoint returns",
},
},
});
// Protected endpoint
app.get("/api/example", payment, (req, res) => {
res.json({ data: "This costs $0.01 per request" });
});
app.listen(3000, () => console.log("Server running on port 3000"));bash
mkdir x402-server && cd x402-server
npm init -y
npm install express x402-express创建:
index.jsjs
const express = require("express");
const { paymentMiddleware } = require("x402-express");
const app = express();
app.use(express.json());
const PAY_TO = "<address from step 1>";
// x402支付中间件——保护下方的路由
const payment = paymentMiddleware(PAY_TO, {
"GET /api/example": {
price: "$0.01",
network: "base",
config: {
description: "Description of what this endpoint returns",
},
},
});
// 受保护的端点
app.get("/api/example", payment, (req, res) => {
res.json({ data: "This costs $0.01 per request" });
});
app.listen(3000, () => console.log("Server running on port 3000"));Step 3: Run It
步骤3:运行服务器
bash
node index.jsTest with curl — you should get a 402 response with payment requirements:
bash
curl -i http://localhost:3000/api/examplebash
node index.js使用curl测试——你应该会收到包含付款要求的402响应:
bash
curl -i http://localhost:3000/api/exampleAPI Reference
API参考
paymentMiddleware(payTo, routes, facilitator?)
paymentMiddleware(payTo, routes, facilitator?)
Creates Express middleware that enforces x402 payments.
| Parameter | Type | Description |
|---|---|---|
| string | Ethereum address (0x...) to receive USDC payments |
| object | Route config mapping route patterns to payment config |
| object? | Optional custom facilitator (defaults to x402.org) |
创建用于强制执行x402付款的Express中间件。
| 参数 | 类型 | 描述 |
|---|---|---|
| string | 接收USDC付款的以太坊地址(0x...格式) |
| object | 路由配置,将路由模式映射到付款配置 |
| object? | 可选的自定义支付服务商(默认使用x402.org) |
Route Config
路由配置
Each key in the routes object is . The value is either a price string or a config object:
"METHOD /path"js
// Simple — just a price
{ "GET /api/data": "$0.05" }
// Full config
{
"POST /api/query": {
price: "$0.25",
network: "base",
config: {
description: "Human-readable description of the endpoint",
inputSchema: {
bodyType: "json",
bodyFields: {
query: { type: "string", description: "The query to run" },
},
},
outputSchema: {
type: "object",
properties: {
result: { type: "string" },
},
},
},
},
}routes对象中的每个键为,值可以是价格字符串或配置对象:
"METHOD /path"js
// 简单配置——仅指定价格
{ "GET /api/data": "$0.05" }
// 完整配置
{
"POST /api/query": {
price: "$0.25",
network: "base",
config: {
description: "Human-readable description of the endpoint",
inputSchema: {
bodyType: "json",
bodyFields: {
query: { type: "string", description: "The query to run" },
},
},
outputSchema: {
type: "object",
properties: {
result: { type: "string" },
},
},
},
},
}Route Config Fields
路由配置字段
| Field | Type | Description |
|---|---|---|
| string | USDC price (e.g. "$0.01", "$1.00") |
| string | Blockchain network: "base" or "base-sepolia" |
| string? | What this endpoint does (shown to clients) |
| object? | Expected request body/query schema |
| object? | Response body schema |
| number? | Max time for payment settlement |
| 字段 | 类型 | 描述 |
|---|---|---|
| string | USDC价格(例如"$0.01", "$1.00") |
| string | 区块链网络:"base"或"base-sepolia" |
| string? | 端点功能说明(展示给客户端) |
| object? | 预期的请求体/查询参数 schema |
| object? | 响应体 schema |
| number? | 付款结算的最长超时时间 |
Supported Networks
支持的网络
| Network | Description |
|---|---|
| Base mainnet (real USDC) |
| Base Sepolia testnet (test USDC) |
| 网络 | 描述 |
|---|---|
| Base主网(真实USDC) |
| Base Sepolia测试网(测试USDC) |
Patterns
配置模式
Multiple endpoints with different prices
多端点不同定价
js
const payment = paymentMiddleware(PAY_TO, {
"GET /api/cheap": { price: "$0.001", network: "base" },
"GET /api/expensive": { price: "$1.00", network: "base" },
"POST /api/query": { price: "$0.25", network: "base" },
});
app.get("/api/cheap", payment, (req, res) => { /* ... */ });
app.get("/api/expensive", payment, (req, res) => { /* ... */ });
app.post("/api/query", payment, (req, res) => { /* ... */ });js
const payment = paymentMiddleware(PAY_TO, {
"GET /api/cheap": { price: "$0.001", network: "base" },
"GET /api/expensive": { price: "$1.00", network: "base" },
"POST /api/query": { price: "$0.25", network: "base" },
});
app.get("/api/cheap", payment, (req, res) => { /* ... */ });
app.get("/api/expensive", payment, (req, res) => { /* ... */ });
app.post("/api/query", payment, (req, res) => { /* ... */ });Wildcard routes
通配符路由
js
const payment = paymentMiddleware(PAY_TO, {
"GET /api/*": { price: "$0.05", network: "base" },
});
app.use(payment);
app.get("/api/users", (req, res) => { /* ... */ });
app.get("/api/posts", (req, res) => { /* ... */ });js
const payment = paymentMiddleware(PAY_TO, {
"GET /api/*": { price: "$0.05", network: "base" },
});
app.use(payment);
app.get("/api/users", (req, res) => { /* ... */ });
app.get("/api/posts", (req, res) => { /* ... */ });Health check (no payment)
健康检查(无需付费)
Register free endpoints before the payment middleware:
js
app.get("/health", (req, res) => res.json({ status: "ok" }));
// Payment middleware only applies to routes registered after it
app.get("/api/data", payment, (req, res) => { /* ... */ });在支付中间件之前注册免费端点:
js
app.get("/health", (req, res) => res.json({ status: "ok" }));
// 支付中间件仅对其之后注册的路由生效
app.get("/api/data", payment, (req, res) => { /* ... */ });POST with body schema
带请求体Schema的POST端点
js
const payment = paymentMiddleware(PAY_TO, {
"POST /api/analyze": {
price: "$0.10",
network: "base",
config: {
description: "Analyze text sentiment",
inputSchema: {
bodyType: "json",
bodyFields: {
text: { type: "string", description: "Text to analyze" },
},
},
outputSchema: {
type: "object",
properties: {
sentiment: { type: "string" },
score: { type: "number" },
},
},
},
},
});
app.post("/api/analyze", payment, (req, res) => {
const { text } = req.body;
// ... your logic
res.json({ sentiment: "positive", score: 0.95 });
});js
const payment = paymentMiddleware(PAY_TO, {
"POST /api/analyze": {
price: "$0.10",
network: "base",
config: {
description: "Analyze text sentiment",
inputSchema: {
bodyType: "json",
bodyFields: {
text: { type: "string", description: "Text to analyze" },
},
},
outputSchema: {
type: "object",
properties: {
sentiment: { type: "string" },
score: { type: "number" },
},
},
},
},
});
app.post("/api/analyze", payment, (req, res) => {
const { text } = req.body;
// ... 你的业务逻辑
res.json({ sentiment: "positive", score: 0.95 });
});Using the CDP facilitator (authenticated)
使用CDP支付服务商(需认证)
For production use with the Coinbase facilitator (supports mainnet):
bash
npm install @coinbase/x402js
const { facilitator } = require("@coinbase/x402");
const payment = paymentMiddleware(PAY_TO, routes, facilitator);This requires and environment variables. Get these from https://portal.cdp.coinbase.com.
CDP_API_KEY_IDCDP_API_KEY_SECRET若要在生产环境中使用Coinbase的CDP支付服务商(支持主网):
bash
npm install @coinbase/x402js
const { facilitator } = require("@coinbase/x402");
const payment = paymentMiddleware(PAY_TO, routes, facilitator);Testing with the pay-for-service Skill
使用pay-for-service技能测试
Once the server is running, use the skill to test payments:
pay-for-servicebash
undefined服务器运行后,可使用技能测试付款流程:
pay-for-servicebash
undefinedCheck the endpoint's payment requirements
查看端点的付款要求
npx awal@latest x402 details http://localhost:3000/api/example
npx awal@latest x402 details http://localhost:3000/api/example
Make a paid request
发起付费请求
npx awal@latest x402 pay http://localhost:3000/api/example
undefinednpx awal@latest x402 pay http://localhost:3000/api/example
undefinedPricing Guidelines
定价指南
| Use Case | Suggested Price |
|---|---|
| Simple data lookup | $0.001 - $0.01 |
| API proxy / enrichment | $0.01 - $0.10 |
| Compute-heavy query | $0.10 - $0.50 |
| AI inference | $0.05 - $1.00 |
| 使用场景 | 建议价格 |
|---|---|
| 简单数据查询 | $0.001 - $0.01 |
| API代理/数据增强 | $0.01 - $0.10 |
| 计算密集型查询 | $0.10 - $0.50 |
| AI推理 | $0.05 - $1.00 |
Checklist
检查清单
- Get wallet address with
npx awal@latest address - Install and
expressx402-express - Define routes with prices and descriptions
- Register payment middleware before protected routes
- Keep health/status endpoints before payment middleware
- Test with (should get 402) and
curl(should get 200)npx awal@latest x402 pay - Announce your service so other agents can find and use it
- 使用获取钱包地址
npx awal@latest address - 安装和
expressx402-express - 定义包含价格和说明的路由
- 在受保护路由之前注册支付中间件
- 将健康/状态端点放在支付中间件之前
- 使用测试(应返回402)和
curl测试(应返回200)npx awal@latest x402 pay - 发布你的服务,让其他Agent可以发现并使用