mcpField
M
monetize-service

monetize-service

github.com/coinbase开发1272.9k 次安装12 周前更新
代码仓库

关于 monetize-service

用于构建通过 x402 协议按请求收取 USDC 的 Express API 技能,涵盖支付中间件、端点定价和 Bazaar 发现注册,面向服务运营者。

主要功能

  1. 01Express 支付中间件
  2. 02按端点设置 USDC 价格
  3. 03支持 Base 和 Base Sepolia
  4. 04x402 Bazaar 发现注册

适用场景

  1. 01为 API 请求收费
  2. 02发布端点供 Agent 发现

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/coinbase/agentic-wallet-skills --skill monetize-service

安装后在 Claude Code 中输入/monetize-service确认已加载。

详细介绍

构建 x402 支付服务

创建一个 Express 服务,使用 x402 支付协议通过 API 访问收取 USDC。调用方在 Base 上按请求支付 USDC,无需账户、API 密钥或订阅。其他 Agent 可通过 x402 Bazaar 自动发现你的服务。

工作原理

x402 是一种原生支持 HTTP 的支付协议。当客户端访问受保护的端点但未付款时,服务会返回包含支付要求的 HTTP 402 响应。客户端签署一笔 USDC 支付,并在请求中添加支付标头后重试。支付中介会验证并结算支付,然后服务返回响应。服务会注册到 x402 Bazaar,以便其他 Agent 自动发现并向其付款。

确认钱包已初始化并完成身份验证

npx [email protected] status

如果钱包尚未通过身份验证,请参考 authenticate-wallet 技能。

第 1 步:获取收款地址

运行以下命令,获取将用于接收付款的钱包地址:

npx [email protected] address

将此地址用作 payTo 的值。

第 2 步:设置项目

mkdir x402-server && cd x402-server
npm init -y
npm install express @x402/express @x402/core @x402/evm @x402/extensions

创建 index.js:

const express = require("express");
const { paymentMiddleware } = require("@x402/express");
const { x402ResourceServer, HTTPFacilitatorClient } = require("@x402/core/server");
const { ExactEvmScheme } = require("@x402/evm/exact/server");

const app = express();
app.use(express.json());

const PAY_TO = "<address from step 1>";

// Create facilitator client and x402 resource server
const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const server = new x402ResourceServer(facilitator);
server.register("eip155:8453", new ExactEvmScheme());

// x402 payment middleware — protects routes below
app.use(
  paymentMiddleware(
    {
      "GET /api/example": {
        accepts: {
          scheme: "exact",
          price: "$0.01",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Description of what this endpoint returns",
        mimeType: "application/json",
      },
    },
    server,
  ),
);

// Protected endpoint
app.get("/api/example", (req, res) => {
  res.json({ data: "This costs $0.01 per request" });
});

app.listen(3000, () => console.log("Server running on port 3000"));

第 3 步:运行

node index.js

使用 curl 测试——你应该会收到包含支付要求的 402 响应:

curl -i http://localhost:3000/api/example

API 参考

paymentMiddleware(routes, server)

创建用于强制执行 x402 支付的 Express 中间件。

参数类型描述
routes对象将路由模式映射到支付配置的路由配置
serverx402ResourceServer预配置的 x402 资源服务实例
x402ResourceServer

使用支付中介客户端创建。在传递给中间件之前,注册支付方案和扩展。

const { x402ResourceServer, HTTPFacilitatorClient } = require("@x402/core/server");
const { ExactEvmScheme } = require("@x402/evm/exact/server");

const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org" });
const server = new x402ResourceServer(facilitator);
server.register("eip155:8453", new ExactEvmScheme());
方法描述
register(network, scheme)为 CAIP-2 网络标识符注册支付方案
路由配置

routes 对象中的每个键都是 "METHOD /path"。对应的值是一个配置对象:

{
  "GET /api/data": {
    accepts: {
      scheme: "exact",
      price: "$0.05",
      network: "eip155:8453",
      payTo: "0x...",
    },
    description: "Human-readable description of the endpoint",
    mimeType: "application/json",
    extensions: {
      ...declareDiscoveryExtension({
        output: {
          example: { result: "example response" },
          schema: {
            properties: {
              result: { type: "string" },
            },
          },
        },
      }),
    },
  },
}
Accepts 配置字段

accepts 字段可以是单个对象,也可以是数组(用于提供多个支付选项):

字段类型描述
scheme字符串支付方案:"exact"
price字符串USDC 价格(例如 "$0.01"、"$1.00")
network字符串CAIP-2 网络标识符(例如 "eip155:8453")
payTo字符串用于接收 USDC 付款的以太坊地址(0x...)
路由级字段
字段类型描述
accepts对象或数组支付要求(单个或多个)
description字符串?此端点的功能(向客户端显示)
mimeType字符串?响应的 MIME 类型
extensions对象?扩展配置(例如 Bazaar 发现功能)
发现扩展

declareDiscoveryExtension 函数会将你的端点注册到 x402 Bazaar,以便其他 Agent 发现它:

const { declareDiscoveryExtension } = require("@x402/extensions/bazaar");

extensions: {
  ...declareDiscoveryExtension({
    output: {
      example: { /* example response body */ },
      schema: {
        properties: {
          /* JSON schema of the response */
        },
      },
    },
  }),
}
字段类型描述
output.example对象端点响应正文示例
output.schema对象描述响应格式的 JSON Schema
支持的网络
网络描述
eip155:8453Base 主网(真实 USDC)
eip155:84532Base Sepolia 测试网(测试 USDC)

模式

多个端点采用不同价格
app.use(
  paymentMiddleware(
    {
      "GET /api/cheap": {
        accepts: {
          scheme: "exact",
          price: "$0.001",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Inexpensive data lookup",
      },
      "GET /api/expensive": {
        accepts: {
          scheme: "exact",
          price: "$1.00",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Premium data access",
      },
      "POST /api/query": {
        accepts: {
          scheme: "exact",
          price: "$0.25",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Run a custom query",
      },
    },
    server,
  ),
);

app.get("/api/cheap", (req, res) => { /* ... */ });
app.get("/api/expensive", (req, res) => { /* ... */ });
app.post("/api/query", (req, res) => { /* ... */ });
通配符路由
app.use(
  paymentMiddleware(
    {
      "GET /api/*": {
        accepts: {
          scheme: "exact",
          price: "$0.05",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "API access",
      },
    },
    server,
  ),
);

app.get("/api/users", (req, res) => { /* ... */ });
app.get("/api/posts", (req, res) => { /* ... */ });
健康检查(无需付款)

在付款中间件之前注册免费端点:

app.get("/health", (req, res) => res.json({ status: "ok" }));

// Payment middleware only applies to routes registered after it
app.use(paymentMiddleware({ /* ... */ }, server));
app.get("/api/data", (req, res) => { /* ... */ });
带有请求体和发现扩展的 POST
app.use(
  paymentMiddleware(
    {
      "POST /api/analyze": {
        accepts: {
          scheme: "exact",
          price: "$0.10",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Analyze text sentiment",
        mimeType: "application/json",
        extensions: {
          ...declareDiscoveryExtension({
            output: {
              example: { sentiment: "positive", score: 0.95 },
              schema: {
                properties: {
                  sentiment: { type: "string" },
                  score: { type: "number" },
                },
              },
            },
          }),
        },
      },
    },
    server,
  ),
);

app.post("/api/analyze", (req, res) => {
  const { text } = req.body;
  // ... your logic
  res.json({ sentiment: "positive", score: 0.95 });
});
每个端点支持多种付款选项

同一端点接受多个网络上的付款:

"GET /api/data": {
  accepts: [
    {
      scheme: "exact",
      price: "$0.01",
      network: "eip155:8453",
      payTo: EVM_ADDRESS,
    },
    {
      scheme: "exact",
      price: "$0.01",
      network: "eip155:84532",
      payTo: EVM_ADDRESS,
    },
  ],
  description: "Data endpoint accepting Base mainnet or testnet",
}
使用 CDP facilitator(已认证)

在生产环境中使用 Coinbase facilitator(支持主网):

npm install @coinbase/x402
const { facilitator } = require("@coinbase/x402");
const { HTTPFacilitatorClient } = require("@x402/core/server");

const facilitatorClient = new HTTPFacilitatorClient(facilitator);
const server = new x402ResourceServer(facilitatorClient);
server.register("eip155:8453", new ExactEvmScheme());

这需要设置 CDP_API_KEY_ID 和 CDP_API_KEY_SECRET 环境变量。请从 https://portal.cdp.coinbase.com 获取这些变量。

使用 pay-for-service 技能进行测试

服务器运行后,使用 pay-for-service 技能测试付款:

# Check the endpoint's payment requirements
npx [email protected] x402 details http://localhost:3000/api/example

# Make a paid request
npx [email protected] x402 pay http://localhost:3000/api/example

定价指南

用例建议价格
简单数据查询$0.001 - $0.01
API 代理 / 数据增强$0.01 - $0.10
计算密集型查询$0.10 - $0.50
AI 推理$0.05 - $1.00

检查清单

  • 使用 npx [email protected] address 获取钱包地址
  • 安装 express、@x402/express、@x402/core、@x402/evm 和 @x402/extensions
  • 使用 facilitator 客户端创建 x402ResourceServer,并为 eip155:8453 注册 ExactEvmScheme
  • 定义带有价格、描述和发现扩展的路由(路由声明发现扩展后,Bazaar 会自动注册)
  • 在受保护的路由之前注册付款中间件
  • 将健康状态端点放在付款中间件之前
  • 使用 curl 测试(应返回 402),并使用 npx [email protected] x402 pay 测试(应返回 200)
  • 发布你的服务信息,让其他 Agent 能够发现并使用它

评论

支持 Markdown