monetize-service

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Build 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 status
If the wallet is not authenticated, refer to the
authenticate-wallet
skill.
bash
npx awal@latest status
如果钱包未认证,请参考
authenticate-wallet
技能。

Step 1: Get the Payment Address

步骤1:获取收款地址

Run this to get the wallet address that will receive payments:
bash
npx awal@latest address
Use this address as the
payTo
value.
运行以下命令获取将接收付款的钱包地址:
bash
npx awal@latest address
将此地址作为
payTo
的值。

Step 2: Set Up the Project

步骤2:搭建项目

bash
mkdir x402-server && cd x402-server
npm init -y
npm install express x402-express
Create
index.js
:
js
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.js
js
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.js
Test with curl — you should get a 402 response with payment requirements:
bash
curl -i http://localhost:3000/api/example
bash
node index.js
使用curl测试——你应该会收到包含付款要求的402响应:
bash
curl -i http://localhost:3000/api/example

API Reference

API参考

paymentMiddleware(payTo, routes, facilitator?)

paymentMiddleware(payTo, routes, facilitator?)

Creates Express middleware that enforces x402 payments.
ParameterTypeDescription
payTo
stringEthereum address (0x...) to receive USDC payments
routes
objectRoute config mapping route patterns to payment config
facilitator
object?Optional custom facilitator (defaults to x402.org)
创建用于强制执行x402付款的Express中间件。
参数类型描述
payTo
string接收USDC付款的以太坊地址(0x...格式)
routes
object路由配置,将路由模式映射到付款配置
facilitator
object?可选的自定义支付服务商(默认使用x402.org)

Route Config

路由配置

Each key in the routes object is
"METHOD /path"
. The value is either a price string or a config object:
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

路由配置字段

FieldTypeDescription
price
stringUSDC price (e.g. "$0.01", "$1.00")
network
stringBlockchain network: "base" or "base-sepolia"
config.description
string?What this endpoint does (shown to clients)
config.inputSchema
object?Expected request body/query schema
config.outputSchema
object?Response body schema
config.maxTimeoutSeconds
number?Max time for payment settlement
字段类型描述
price
stringUSDC价格(例如"$0.01", "$1.00")
network
string区块链网络:"base"或"base-sepolia"
config.description
string?端点功能说明(展示给客户端)
config.inputSchema
object?预期的请求体/查询参数 schema
config.outputSchema
object?响应体 schema
config.maxTimeoutSeconds
number?付款结算的最长超时时间

Supported Networks

支持的网络

NetworkDescription
base
Base mainnet (real USDC)
base-sepolia
Base Sepolia testnet (test USDC)
网络描述
base
Base主网(真实USDC)
base-sepolia
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/x402
js
const { facilitator } = require("@coinbase/x402");

const payment = paymentMiddleware(PAY_TO, routes, facilitator);
This requires
CDP_API_KEY_ID
and
CDP_API_KEY_SECRET
environment variables. Get these from https://portal.cdp.coinbase.com.
若要在生产环境中使用Coinbase的CDP支付服务商(支持主网):
bash
npm install @coinbase/x402
js
const { facilitator } = require("@coinbase/x402");

const payment = paymentMiddleware(PAY_TO, routes, facilitator);
这需要设置
CDP_API_KEY_ID
CDP_API_KEY_SECRET
环境变量。可从https://portal.cdp.coinbase.com获取这些密钥。

Testing with the pay-for-service Skill

使用pay-for-service技能测试

Once the server is running, use the
pay-for-service
skill to test payments:
bash
undefined
服务器运行后,可使用
pay-for-service
技能测试付款流程:
bash
undefined

Check 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
undefined
npx awal@latest x402 pay http://localhost:3000/api/example
undefined

Pricing Guidelines

定价指南

Use CaseSuggested 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
    express
    and
    x402-express
  • Define routes with prices and descriptions
  • Register payment middleware before protected routes
  • Keep health/status endpoints before payment middleware
  • Test with
    curl
    (should get 402) and
    npx awal@latest x402 pay
    (should get 200)
  • Announce your service so other agents can find and use it
  • 使用
    npx awal@latest address
    获取钱包地址
  • 安装
    express
    x402-express
  • 定义包含价格和说明的路由
  • 在受保护路由之前注册支付中间件
  • 将健康/状态端点放在支付中间件之前
  • 使用
    curl
    测试(应返回402)和
    npx awal@latest x402 pay
    测试(应返回200)
  • 发布你的服务,让其他Agent可以发现并使用