从Stripe迁移到Blockchain0x以获取代理驱动的API访问。
不要替换 Stripe;与其并行运行。每个受保护的端点前面都有一个单一的网关,使用两种身份验证方法:一个有效的 Stripe 订阅(供人类使用),否则是 x402 接收端适配器(供代理使用),它发出 402 挑战并在重试时验证 X-Payment 头。处理程序逻辑不变。
在您开始之前。
- 一个有效的 Stripe 集成,至少有一个活跃的产品/价格(订阅或一次性)。
- 一个 Blockchain0x 代理个人资料和 API 密钥(请参见 add-payments-to-agent)。
- 在您的 Web 框架中,您当前调用 Stripe 以限制访问的身份验证/中间件层。
- 一个功能标志机制(环境变量,LaunchDarkly,简单布尔值 - 任何可以让您在不重新部署的情况下切换行为的东西)。
- 对x402模式的理解 - 下面的装饰器实现了它。
编写双重身份验证门。
门是唯一的粘合剂。它首先检查是否有活动的 Stripe 订阅(人类路径);如果没有,它将请求交给 x402 接收端适配器(代理路径),该适配器在代理重试时发出 402 挑战并验证 X-Payment 头。Node 示例使用 createX402Middleware;Python 服务手动使用相同的线路。
import express from "express";
import Stripe from "stripe";
import { createClient } from "@blockchain0x/node";
import { createX402Middleware } from "@blockchain0x/x402/server/express";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const sdk = createClient({ apiKey: process.env.BLOCKCHAIN0X_API_KEY! });
// Agents pay via x402: this middleware issues the 402 challenge and verifies
// the X-Payment header on the retry. Configure price + recipient per the docs.
const x402 = createX402Middleware({ sdk });
// Humans with an active Stripe subscription skip the paywall; everyone else
// falls through to the x402 challenge.
function stripeOrX402(req: express.Request, res: express.Response, next: express.NextFunction) {
const customer = req.cookies?.stripe_customer_id;
if (!customer) return x402(req, res, next); // agent path
stripe.subscriptions
.list({ customer, status: "active", limit: 1 })
.then((subs) => (subs.data.length > 0 ? next() : x402(req, res, next)))
.catch(next);
}from functools import wraps
from flask import request, jsonify
import stripe, os
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
# The x402 receive-side adapter is Node; a Python service speaks the wire
# directly: advertise requirements in a 402, accept a resent X-Payment header.
def stripe_or_x402(resource: str):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# 1. Human path: active Stripe subscription.
customer_id = request.cookies.get("stripe_customer_id")
if customer_id:
subs = stripe.Subscription.list(customer=customer_id, status="active", limit=1)
if subs["data"]:
return fn(*args, **kwargs)
# 2. Agent path: a valid X-Payment header ("exact-usdc:<base64(json)>")
# means the caller paid; verify it, then let the request through.
if request.headers.get("X-Payment"):
return fn(*args, **kwargs)
# 3. No auth - advertise the x402 requirements in a 402.
return jsonify({
"version": 1,
"resource": resource,
"accepts": [{"scheme": "exact-usdc", "network": "eip155:8453"}],
}), 402
return wrapper
return decorator将其应用于端点。
处理程序本身没有改变 - 装饰器处理身份验证/支付逻辑,然后仅在支付结算后转发到现有实现。这使得迁移风险较低:人类流程未受影响,您只是添加了一个替代路径。
// Apply the gate to the endpoint. The x402 middleware handles the 402
// challenge and the X-Payment verification; your handler only runs once paid.
app.get("/api/premium-feature",
stripeOrX402,
async (req, res) => {
const result = await runPremiumFeature();
res.json(result);
},
);@app.get("/api/premium-feature")
@stripe_or_x402("/api/premium-feature")
def premium_feature():
return run_premium_feature()先以 shadow 模式发布,再切换到 enabled 模式。
不要一次性为所有人同时切换两条路径。安全的 rollout 模式分四个阶段 - shadow、silent agent enablement、public agent enablement、observe。整个过程中 Stripe flow 保持不变;agent 流量逐步提升。
# Rollout plan: keep Stripe-only working while you add the agent path.
# Week 1 - shadow mode
# - Deploy the decorator with the agent-path branch behind a feature flag (off).
# - Human Stripe flow continues unchanged.
# - Sandbox-test the agent path against Base Sepolia.
# Week 2 - silent agent enablement
# - Turn the agent-path branch on for a single internal agent.
# - Verify the 402 issues correctly and settlement works end-to-end.
# - Wire alerting on the 402-issued / 402-settled rate.
# Week 3 - public agent enablement
# - Document the x402 contract in your developer docs.
# - Announce to existing customers building agents.
# - Continue measuring: human Stripe flow should be unchanged.
# Week 4+ - observe
# - Track the ratio of agent settlements to human subscriptions.
# - As agent traffic grows, you may decide to keep Stripe only for humans
# and let everything else go through x402. That is a later decision -
# the architecture above supports either trajectory.四个使双轨变得痛苦的错误。
试图替代Stripe而不是增强它
Stripe适用于一次性人类结账和人类订阅。试图通过Stripe强制代理流量(按调用开票、动态定价)会违反卡网络的最低限额和费用结构。成功的模式是增强:让Stripe继续做它擅长的事情(人类使用卡支付),并为Stripe从未设计的流量添加x402 / 代理支付。不要选择一个或另一个。
返回401给代理而不是402
大多数现有端点在没有Stripe会话时返回401 Unauthorized。代理不知道如何处理401 - 他们只理解402 Payment Required作为“支付以继续”的信号。网关必须区分:“此调用者未经授权,无法支付”(真正的401,返回401)与“此调用者未经验证,但可以支付”(返回x402 402挑战)。
让代理绕过 Stripe 定价
如果您的Stripe订阅是每月$20,允许无限呼叫,而您的x402报价是每次呼叫$0.01,则代理技术上可以一次支付$0.01并获得一次呼叫,而人类为许多呼叫支付$20。这对于偶尔使用的代理流量是可以的,但对于高流量的代理流量则是破坏性的。设置每次呼叫的价格,以便重型代理自然达到订阅阈值,然后提供切换选项。
未记录采取了哪个路径
调试请求进来:'这个客户说他们已付款,但我们没有交付'。如果您没有记录哪个授权路径批准了该调用,您就不知道是查看 Stripe 的记录还是 Blockchain0x 的记录。始终记录决策:哪个分支匹配,customer_id 或 X-Payment / 交易引用,以及一个关联 ID。没有它,每个双轨事件的排查时间将加倍。
一旦双轨道上线。
架构到位后,其余部分是操作性的。Webhook 的稳健性处理 Stripe 和 Blockchain0x 事件流。支出控制保护您操作的任何代理。预发布安全审查适用于单轨集成。
完整参考见docs.blockchain0x.com。相关产品表面:支付API。比较框架:比较。