Skip to content

Python ​

Compatibility

Python 3.6+. Only depends on requests; everything else is stdlib.

Install ​

bash
pip install requests

Client Implementation ​

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):
    """Raised for every response whose `code` is not 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            # business code: 40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
        self.error_key = error_key  # stable machine key — branch on this, never on `message`
        self.message = message      # localized text (English unless you send Accept-Language)
        self.retry_after = retry_after  # Retry-After header in seconds (set on 429)


def call(method: str, path: str, body_dict: Optional[dict] = None,
         idempotency_key: Optional[str] = None):
    """Unified OpenAPI call: returns `data` when code == 0, raises brandError otherwise."""
    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:
        # Not our JSON envelope (e.g. a proxy error page)
        raise brandError(r.status_code, None, None, r.reason, retry_after)

    # Most business errors arrive with HTTP 200 — check `code`, not the HTTP status
    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 signature verification
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)

Usage ​

python
import uuid

# 1. List card headers
data = call("POST", "/api/v1/openapi/card_headers/list", {"page": 1, "page_size": 20})
print(data["list"][0]["header_id"])

# 2. List card configs
data = call("POST", "/api/v1/openapi/card_configs/list", {"header_id": "hdr_5"})
package_id = data["list"][0]["package_id"]

# 3. Apply virtual card (with idempotency key)
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. Once the card is active (card.opened webhook / status 2), create a recharge.
#    `amount` is in the package's recharge asset (e.g. 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 → wait for webhook
except brandError as e:
    if e.error_key == "insufficient_balance":
        print("Top up your wallet first")
    elif e.error_key == "card_number_not_ready":
        print("virtual_s921 right after opening — retry in a few seconds")
    else:
        raise

Webhook Receiver (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")

    # Timestamp ±5 min
    if abs(int(time.time()) - int(ts)) > 300:
        raise HTTPException(401, "timestamp expired")

    # Dedupe by 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}

Defer heavy work

handle_event should only do "persist + enqueue". Don't do slow operations (DB queries, external calls) in the webhook handler — anything over 5 seconds will be re-delivered.

Errors & Retry ​

Success is code == 0. Most business errors (40000, 40001, 50000) come back with HTTP 200, so never decide on the HTTP status alone — call() above raises for any non-zero code, and you branch on error_key.

python
import time

def call_with_retry(method, path, body=None, idempotency_key=None,
                    max_attempts=4):
    """Retry only what is safe to retry; reuse the SAME Idempotency-Key on every attempt."""
    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: wait Retry-After seconds
                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: the first request with this key is still running — retry later, same key
                time.sleep(2 ** attempt)
                continue
            if e.code == 50000 and (idempotency_key is None or e.http_status >= 500):
                # Read endpoints are safe to retry. On write endpoints an HTTP-200 50000 is stored
                # under the Idempotency-Key and would only be replayed — check the state instead.
                time.sleep(2 ** attempt)
                continue
            # 40100 openapi_invalid_credentials (HTTP 401): fix signature / clock / credential.
            # 40000 / 40001 / 40300 / 40400 / 40900 openapi_idempotency_key_conflict: fix the request.
            raise

Released under MIT-equivalent terms.