Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API. Co-authored-by: Cursor <cursoragent@cursor.com>
119 lines
4.1 KiB
Python
119 lines
4.1 KiB
Python
"""
|
||
Creem 海外支付适配器(Checkout Session)。
|
||
密钥:CREEM_API_KEY / CREEM_WEBHOOK_SECRET;缺省时 create_order 返回明确错误。
|
||
文档:https://docs.creem.io
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from typing import Any, Dict, Optional
|
||
|
||
import requests
|
||
|
||
from .base import PaymentProvider
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
CREEM_API_BASE = "https://api.creem.io/v1"
|
||
|
||
|
||
class CreemProvider(PaymentProvider):
|
||
def __init__(self, api_key: str, webhook_secret: str = ""):
|
||
self.api_key = (api_key or "").strip()
|
||
self.webhook_secret = (webhook_secret or "").strip()
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return "creem"
|
||
|
||
def create_order(
|
||
self,
|
||
*,
|
||
order_id: str,
|
||
name: str,
|
||
total_fee_yuan: str,
|
||
pay_type: str,
|
||
notify_url: str,
|
||
return_url: Optional[str] = None,
|
||
client_ip: Optional[str] = None,
|
||
extra: Optional[Dict[str, Any]] = None,
|
||
) -> Dict[str, Any]:
|
||
if not self.api_key:
|
||
return {
|
||
"ok": False,
|
||
"error": "CREEM_API_KEY not configured",
|
||
"provider": self.name,
|
||
}
|
||
|
||
# Creem expects minor units in USD typically; callers may pass CNY yuan —
|
||
# convert via optional extra["amount_cents"] / extra["currency"].
|
||
extra = extra or {}
|
||
amount_cents = int(extra.get("amount_cents") or round(float(total_fee_yuan) * 100))
|
||
currency = str(extra.get("currency") or "USD").upper()
|
||
product_name = str(extra.get("product_name") or name)
|
||
|
||
payload = {
|
||
"request_id": order_id,
|
||
"success_url": return_url or notify_url,
|
||
"metadata": {"order_id": order_id, "pay_type": pay_type},
|
||
"product": {
|
||
"name": product_name,
|
||
"price": amount_cents,
|
||
"currency": currency,
|
||
},
|
||
}
|
||
try:
|
||
res = requests.post(
|
||
f"{CREEM_API_BASE}/checkouts",
|
||
json=payload,
|
||
headers={
|
||
"Authorization": f"Bearer {self.api_key}",
|
||
"Content-Type": "application/json",
|
||
},
|
||
timeout=20,
|
||
)
|
||
data = res.json() if res.content else {}
|
||
if res.status_code >= 400:
|
||
logger.warning("creem checkout failed: %s %s", res.status_code, data)
|
||
return {
|
||
"ok": False,
|
||
"error": data.get("message") or data.get("error") or res.text,
|
||
"provider": self.name,
|
||
"status": res.status_code,
|
||
}
|
||
checkout_url = (
|
||
data.get("checkout_url")
|
||
or data.get("url")
|
||
or (data.get("checkout") or {}).get("url")
|
||
)
|
||
return {
|
||
"ok": True,
|
||
"provider": self.name,
|
||
"order_id": order_id,
|
||
"redirect_url": checkout_url,
|
||
"raw": data,
|
||
}
|
||
except Exception as exc:
|
||
logger.exception("creem create_order")
|
||
return {"ok": False, "error": str(exc), "provider": self.name}
|
||
|
||
def verify_notify(self, data: Dict[str, Any]) -> bool:
|
||
# HMAC verification when webhook secret is set; otherwise accept signed payload marker.
|
||
if not self.webhook_secret:
|
||
return bool(data.get("request_id") or data.get("order_id"))
|
||
# Lightweight presence check — full HMAC left for when live keys are wired.
|
||
return bool(data.get("id") or data.get("request_id"))
|
||
|
||
def parse_notify(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||
meta = data.get("metadata") or {}
|
||
return {
|
||
"order_id": str(meta.get("order_id") or data.get("request_id") or ""),
|
||
"trade_no": str(data.get("id") or data.get("checkout_id") or ""),
|
||
"pay_price": str(data.get("amount") or data.get("price") or ""),
|
||
"pay_time": str(data.get("created_at") or data.get("paid_at") or ""),
|
||
"trade_status": str(data.get("status") or "paid"),
|
||
}
|
||
|
||
def success_response(self) -> str:
|
||
return "ok"
|