Skip to content

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:
        raise

Webhook 接收(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

采用 MIT 等价条款发布