Python
相容性
Python 3.6+。僅依賴 requests,其他都是標準庫。
安裝依賴
bash
pip install requests客戶端實現
python
import time, hmac, hashlib, secrets, json
from typing import Optional
import requests
APP_ID = "cp_a1b2c3d4e5f6071829304a5b6c7d8e9f"
SECRET = "f1e2d3c4b5a69788776655443322110099aabbccddeeff00112233445566778899"
BASE = "https://api.coinepay.net"
class brandError(Exception):
"""code 不為 0 的響應一律拋出該例外"""
def __init__(self, http_status, code, error_key, message, retry_after=None):
super().__init__(f"HTTP {http_status} code={code} error_key={error_key}: {message}")
self.http_status = http_status
self.code = code # 業務碼:40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
self.error_key = error_key # 穩定的機器識別碼——據此分支,不要用 message
self.message = message # 在地化文案(不傳 Accept-Language 時為英文)
self.retry_after = retry_after # Retry-After 響應頭(秒),429 時設定
def call(method: str, path: str, body_dict: Optional[dict] = None,
idempotency_key: Optional[str] = None):
"""統一呼叫 OpenAPI:code == 0 時返回 data,否則拋出 brandError"""
body = json.dumps(body_dict or {}, separators=(",", ":")).encode("utf-8")
body_hash = hashlib.sha256(body).hexdigest()
ts = str(int(time.time()))
nonce = secrets.token_hex(16)
sign_input = f"{method}\n{path}\n\n{ts}\n{nonce}\n{body_hash}"
sig = hmac.new(SECRET.encode(), sign_input.encode(), hashlib.sha256).hexdigest()
headers = {
"X-App-Id": APP_ID,
"X-Timestamp": ts,
"X-Nonce": nonce,
"X-Signature": sig,
"Content-Type": "application/json",
}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
r = requests.request(method, BASE + path, headers=headers, data=body, timeout=30)
retry_after = r.headers.get("Retry-After")
try:
resp = r.json()
except ValueError:
# 不是我們的 JSON 包絡(如代理層錯誤頁)
raise brandError(r.status_code, None, None, r.reason, retry_after)
# 大部分業務錯誤的 HTTP 狀態碼是 200——判斷 code,不要看 HTTP 狀態碼
if resp.get("code") == 0:
return resp.get("data")
raise brandError(r.status_code, resp.get("code"), resp.get("error_key"),
resp.get("message"), retry_after)
# Webhook 驗籤
def verify_webhook(signature_header: str, timestamp_header: str,
raw_body: bytes, webhook_secret: str) -> bool:
if not signature_header.startswith("v1,"):
return False
sig = signature_header[3:]
expected = hmac.new(
webhook_secret.encode(),
f"{timestamp_header}.".encode() + raw_body,
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(sig, expected)使用示例
python
import uuid
# 1. 列卡頭
data = call("POST", "/api/v1/openapi/card_headers/list", {"page": 1, "page_size": 20})
print(data["list"][0]["header_id"])
# 2. 列卡配置
data = call("POST", "/api/v1/openapi/card_configs/list", {"header_id": "hdr_5"})
package_id = data["list"][0]["package_id"]
# 3. 申請虛擬卡(帶冪等鍵)
data = call("POST", "/api/v1/openapi/card/apply",
{"header_id": "hdr_5", "package_id": package_id,
"cardholder_id": "chd_1024"},
idempotency_key=str(uuid.uuid4()))
card_id = data["card_id"]
print(f"Created card: {card_id}, status={data['status']}")
# 4. 卡啟用後(card.opened webhook / status 2)建立充值。
# amount 的單位是套餐的充值資產(如 USDT)。
try:
data = call("POST", "/api/v1/openapi/card/recharge",
{"card_id": card_id, "amount": "100.00"},
idempotency_key=str(uuid.uuid4()))
print(f"Transaction: {data['transaction_id']} ({data['status_desc']})") # processing → 等待 webhook
except brandError as e:
if e.error_key == "insufficient_balance":
print("請先為錢包儲值")
elif e.error_key == "card_number_not_ready":
print("virtual_s921 剛開卡,卡號尚未下發——幾秒後重試")
else:
raiseWebhook 接收(FastAPI)
python
from fastapi import FastAPI, Request, HTTPException
import os
app = FastAPI()
WEBHOOK_SECRET = os.environ["BRAND_WEBHOOK_SECRET"]
@app.post("/webhook")
async def webhook(request: Request):
raw = await request.body()
sig = request.headers.get("Webhook-Signature", "")
ts = request.headers.get("Webhook-Timestamp", "")
event_id = request.headers.get("Webhook-Id", "")
event_type = request.headers.get("Webhook-Type", "")
if not verify_webhook(sig, ts, raw, WEBHOOK_SECRET):
raise HTTPException(401, "invalid signature")
# 時間戳 ±5 分鐘內
if abs(int(time.time()) - int(ts)) > 300:
raise HTTPException(401, "timestamp expired")
# 基於 event_id 去重
if already_processed(event_id):
return {"ok": True}
payload = json.loads(raw)
handle_event(event_type, payload)
mark_processed(event_id)
return {"ok": True}重活丟佇列
handle_event 應只做"持久化 + 入隊"。不要在 webhook handler 裡做耗時操作(資料庫慢查詢、外部呼叫),5 秒不返回 2xx 就會重投。
錯誤處理與重試
成功的判斷是 code == 0。大部分業務錯誤(40000、40001、50000)的 HTTP 狀態碼是 200,不要只憑 HTTP 狀態碼判斷——上面的 call() 對任何非 0 的 code 都會拋出例外,再依 error_key 分支處理。
python
import time
def call_with_retry(method, path, body=None, idempotency_key=None,
max_attempts=4):
"""只重試可以安全重試的情況;每次重試都使用同一個 Idempotency-Key"""
for attempt in range(max_attempts):
try:
return call(method, path, body, idempotency_key)
except brandError as e:
if attempt == max_attempts - 1:
raise
if e.code == 42900:
# HTTP 429 too_many_requests:等待 Retry-After 秒
time.sleep(int(e.retry_after or 0) or min(2 ** attempt, 30))
continue
if e.error_key == "openapi_idempotency_key_in_progress":
# HTTP 409:同一個 key 的首個請求仍在處理——稍後用同一個 key 重試
time.sleep(2 ** attempt)
continue
if e.code == 50000 and (idempotency_key is None or e.http_status >= 500):
# 讀介面可以安全重試。寫介面返回的 HTTP 200 + 50000 已依 Idempotency-Key 存檔,
# 重試只會重放同一結果——請先查詢狀態
time.sleep(2 ** attempt)
continue
# 40100 openapi_invalid_credentials(HTTP 401):檢查簽名 / 時鐘 / 憑證
# 40000 / 40001 / 40300 / 40400 / 40900 openapi_idempotency_key_conflict:修正請求
raise