주 콘텐츠로 건너뛰기
LearnGuidesStripe에서 마이그레이션
가이드

에이전트 주도의 API 접근을 위해 Stripe에서 Blockchain0x로 마이그레이션.

20 minutes
짧은 답변

Stripe를 대체하지 마십시오; 함께 실행하십시오. 단일 게이트가 각 보호된 엔드포인트 앞에 두 가지 인증 방법을 제공합니다: 활성 Stripe 구독(인간용), 그렇지 않으면 x402 수신 측 어댑터(에이전트용)가 402 도전을 발행하고 재시도 시 X-Payment 헤더를 검증합니다. 핸들러 로직은 변경되지 않습니다.

전제 조건

시작하기 전에.

  • 하나 이상의 활성 제품/가격(구독 또는 일회성)을 가진 작동하는 Stripe 통합.
  • Blockchain0x 에이전트 프로필 및 API 키 (see add-payments-to-agent).
  • 현재 Stripe를 호출하여 액세스를 제한하는 웹 프레임워크의 인증/미들웨어 레이어.
  • 기능 플래그 메커니즘(환경 변수, LaunchDarkly, 간단한 부울 - 재배포 없이 동작을 전환할 수 있는 모든 것).
  • x402 패턴에 대한 이해 - 아래의 데코레이터가 이를 구현합니다.
3단계 중 1단계

이중 인증 게이트를 작성하세요.

게이트는 단일 접착제입니다. 먼저 활성 Stripe 구독을 확인합니다(인간 경로); 없으면 요청을 x402 수신 측 어댑터(에이전트 경로)로 전달하여 402 챌린지를 발행하고 에이전트가 재시도할 때 X-Payment 헤더를 확인합니다. Node 예제는 createX402Middleware를 사용합니다; Python 서비스는 수동으로 동일한 와이어를 사용합니다.

TypeScript (Express)
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);
}
Python (Flask)
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
3단계 중 2단계

엔드포인트에 적용하십시오.

핸들러 자체는 변경되지 않습니다 - 데코레이터가 인증/결제 논리를 처리한 다음 결제가 정산될 경우에만 기존 구현으로 전달합니다. 이것이 마이그레이션을 저위험으로 만드는 이유입니다: 인간 흐름은 손대지 않으며, 단지 대체 경로를 추가한 것입니다.

TypeScript
// 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);
  },
);
Python
@app.get("/api/premium-feature")
@stripe_or_x402("/api/premium-feature")
def premium_feature():
    return run_premium_feature()
3단계 중 3단계

섀도우 모드로 먼저 배포한 뒤 활성화 모드로 전환합니다.

모든 사용자에게 두 경로를 한 번에 전환하지 마세요. 안전한 롤아웃 패턴은 shadow, silent agent enablement, public agent enablement, observe의 4단계입니다. Stripe 흐름은 전체 과정에서 그대로 유지되고, 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 / 에이전트 지불을 추가하세요. 하나를 선택하지 마세요.

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. 없으면 모든 이중 레일 사건을 분류하는 데 두 배의 시간이 걸립니다.

다음 단계

이중 레일이 활성화되면.

아키텍처가 마련되면 나머지는 운영적입니다. 웹훅 강력성이 Stripe와 Blockchain0x 이벤트 스트림을 모두 처리합니다. 지출 통제가 운영하는 모든 에이전트를 보호합니다. 출시 전 보안 검토는 단일 레일 통합과 동일하게 적용됩니다.

전체 참조는 docs.blockchain0x.com에 있습니다. 관련 제품 표면: 결제 API. 비교 프레임: 비교.

마지막 검토: 2026-05-15. CC BY 4.0에 따라 게시됨.

Stripe를 유지하세요. 에이전트를 추가하세요.

하나의 데코레이터. 두 가지 결제 레일. 기존 고객에 대한 이탈 없음. 무료로 시작할 수 있습니다.