Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

为 HTTP 内容收费

mpp-proxy ↗ 模板是一个位于任意 HTTP 后端前面的 Cloudflare Worker。当请求命中受保护的路由时,代理返回带有 MPP 支付挑战的 402 响应。客户端付款后,代理验证支付、将请求转发到你的源站,并签发一个有效期为 1 小时的会话 cookie。

将 mpp-proxy 模板部署到你的 Cloudflare 账户:

Deploy to Cloudflare

先决条件

配置

wrangler.jsonc 中定义受保护的路由:

JSONC


{

  "vars": {

    "PAY_TO": "0xYourWalletAddress",

    "TEMPO_TESTNET": false,

    "PAYMENT_CURRENCY": "0x20c000000000000000000000b9537d11c60e8b50",

    "PROTECTED_PATTERNS": [

      {

        "pattern": "/premium/*",

        "amount": "0.01",

        "description": "Access to premium content for 1 hour"

      }

    ]

  }

}


Explain Code

注意

TEMPO_TESTNET 设置为 true,并将 PAYMENT_CURRENCY 设置为 0x20c0000000000000000000000000000000000000 以进行测试网开发。

使用 Bot Management 进行选择性门控

借助 Bot Management,代理可以向爬虫收费,同时让站点对人类用户保持免费:

JSONC


{

  "pattern": "/content/*",

  "amount": "0.25",

  "description": "Content access for 1 hour",

  "bot_score_threshold": 30,

  "except_detection_ids": [120623194, 117479730]

}


Bot 分数等于或低于 bot_score_threshold 的请求被定向到付费墙。使用 except_detection_ids 通过 detection ID 将特定爬虫加入允许列表。

部署

克隆模板,编辑 wrangler.jsonc 并部署:

终端窗口


git clone https://github.com/cloudflare/mpp-proxy

cd mpp-proxy

npm install

npx wrangler secret put JWT_SECRET

npx wrangler secret put MPP_SECRET_KEY

npx wrangler deploy


有关完整的配置选项、代理模式和 Bot Management 示例,请参阅 mpp-proxy README ↗

自定义 Worker 端点

为了获得更多控制,使用 Hono 直接将 MPP 中间件添加到你的 Worker:

TypeScript


import { Hono } from "hono";

import { Mppx, tempo } from "mppx/hono";


const app = new Hono();


const mppx = Mppx.create({

  methods: [

    tempo({

      currency: "0x20c0000000000000000000000000000000000000",

      recipient: "0xYourWalletAddress",

    }),

  ],

});


app.get("/premium", mppx.charge({ amount: "0.10" }), (c) =>

  c.json({ data: "Thanks for paying!" }),

);


export default app;


Explain Code

完整的 API,包括会话支付和付款人识别,请参阅 Hono middleware reference ↗

相关