指南
FastAPI
按照本指南在 FastAPI 應用中整合 StableOps:安裝並設定 Python SDK,在伺服器端建立冪等付款訂單,向前端返回安全的付款指令,驗證 Webhook 簽名並更新業務狀態,同時處理環境變數、錯誤回應、重試和本地測試。
安裝
pip install stableops fastapi uvicorn python-dotenv設定
STABLEOPS_API_KEY=sk_sandbox_...
STABLEOPS_WEBHOOK_SECRET=whsec_...建立 lib/stableops.py:
import os
from stableops import StableOps
stableops = StableOps(
api_key=os.environ["STABLEOPS_API_KEY"],
)環境(sandbox / live)由 API Key 字首(sk_sandbox_… / sk_live_…)決定,無需額外參數。
建立付款單
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from lib.stableops import stableops
router = APIRouter()
class CreateOrderRequest(BaseModel):
merchant_order_id: str
amount: str
@router.post("/orders")
def create_order(input: CreateOrderRequest):
try:
# 30 分鐘後未支付自動過期,訂單進入 expired 並釋放地址。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=30)).isoformat()
order = stableops.payment_orders.create(
merchant_order_id=input.merchant_order_id,
amount=input.amount,
accepted_assets=[{"chain": "base", "asset": "USDC"}],
expires_at=expires_at,
)
return {
"id": order.id,
"status": order.status,
"amount": order.amount,
"payment_instructions": [
instruction.model_dump() for instruction in order.payment_instructions
],
}
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from excPython SDK 會用 merchant_order_id 同時作為 Idempotency-Key 請求頭,
保證建立請求可安全重試。
驗證 Webhook
import json
import os
from fastapi import APIRouter, Header, Request, Response
from stableops.webhooks import SIGNATURE_HEADER, verify_webhook_signature
router = APIRouter()
@router.post("/webhooks/stableops")
async def stableops_webhook(
request: Request,
x_product_signature: str | None = Header(default=None, alias=SIGNATURE_HEADER),
):
raw_body = await request.body()
result = verify_webhook_signature(
body=raw_body,
header=x_product_signature,
secret=os.environ["STABLEOPS_WEBHOOK_SECRET"],
)
if not result.valid:
return Response(f"invalid signature: {result.reason}", status_code=400)
event = json.loads(raw_body)
if event["type"] == "payment.finalized":
payment_order_id = event["data"]["payment_order_id"]
# 按 X-Event-Id 去重後再履約。
return Response("ok")這篇文件怎麼樣?
最後更新