エージェント主導のAPIアクセスのためにStripeからBlockchain0xに移行。
Stripeを置き換えないでください;並行して実行します。単一のゲートが各保護されたエンドポイントの前に立ち、2つの認証方法を提供します:アクティブなStripeサブスクリプション(人間用)、さもなければx402受信側アダプタ(エージェント用)が402チャレンジを発行し、再試行時にX-Paymentヘッダーを検証します。ハンドラのロジックは変更されません。
始める前に。
- 少なくとも1つのアクティブな製品/価格(サブスクリプションまたは一回限り)を持つ動作するStripe統合。
- Blockchain0xエージェントプロフィールとAPIキー(add-payments-to-agentを参照)。
- 現在、アクセスを制限するためにStripeを呼び出すあなたのWebフレームワーク内の認証/ミドルウェアレイヤー。
- フィーチャーフラグメカニズム(環境変数、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 mode で展開し、その後 enabled mode に移行します。
全員に対して両方のパスを一度に切り替えないでください。安全なロールアウトパターンは4段階です - shadow, silent agent enablement, public agent enablement, observe. Stripeのフローは全体を通して変更せず、エージェントのトラフィックは段階的に増やします。
# 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.デュアルレールを痛みを伴うものにする4つの間違い。
Stripeを拡張するのではなく、置き換えようとする
Stripeは一度限りの人間のチェックアウトおよび人間のサブスクリプションに適しています。エージェントトラフィックをStripeを通じて強制しようとすると(呼び出しごとの請求書、動的価格設定)、カードネットワークの最小限および手数料構造に反します。成功するパターンは拡張です: Stripeが得意なこと(人間がカードで支払う)を続けさせ、Stripeが設計されていなかったトラフィックのためにx402 / エージェント支払いを追加します。どちらか一方を選ばないでください。
402の代わりにエージェントに401を返す
ほとんどの既存のエンドポイントは、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。これがないと、すべてのデュアルレールインシデントのトリアージに2倍の時間がかかります。
デュアルレールが稼働すると。
アーキテクチャが整った状態で、残りは運用です。ウェブフックの堅牢性は、StripeとBlockchain0xのイベントストリームの両方を処理します。支出管理は、あなたが運営するエージェントを保護します。プレローンチのセキュリティレビューは、単一のレール統合と同様に適用されます。
docs.blockchain0x.comに完全なリファレンスがあります。関連する製品サーフェス: Payment API。比較フレーミング: 比較。