# app/core/creem.py import hmac import hashlib import json from typing import Dict, Any, Optional import aiohttp from app.core.config import settings from app.core.logger import logger from app.core.biz_exception import BizLogicError def verify_creem_signature(payload_bytes: bytes, signature: str, secret_or_secrets: Any) -> bool: """ 验证 Creem Webhook 签名 (HMAC-SHA256) Creem 发送 creem-signature 头部,为 HEX 格式 支持单个 secret 字符串或候选 secrets 列表(生产+测试) """ if not signature or not secret_or_secrets: return False secrets = [secret_or_secrets] if isinstance(secret_or_secrets, str) else list(secret_or_secrets) for sec in secrets: if not sec: continue try: computed = hmac.new(sec.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest() if hmac.compare_digest(computed.lower(), signature.strip().lower()): return True except Exception as e: logger.error(f"❌ [CREEM] Webhook signature verification error: {e}") return False class CreemClient: """ Creem Payment API Client Official documentation: https://docs.creem.io/code/sdks/ai-agents """ @classmethod def is_prod_mode(cls) -> bool: """ 根据全局环境变量 ENV 控制整个系统是生产还是测试: - ENV='PROD' (或 prod/production) -> 生产正式环境,走生产配置 - ENV='DEV' (或 dev/test/local) -> 测试环境,走测试配置 """ return settings.is_prod @classmethod def is_test_environment(cls, provider_config: Optional[Dict[str, Any]] = None) -> bool: return not cls.is_prod_mode() @classmethod def get_api_key(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: """根据当前全局 ENV 确定性返回 API Key""" return settings.active_creem_api_key @classmethod def get_base_url(cls, provider_config: Optional[Dict[str, Any]] = None, api_key: str = "") -> str: """根据当前全局 ENV 确定性返回 Base URL""" return settings.active_creem_base_url @classmethod def get_webhook_secret(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: """根据当前全局 ENV 确定性返回 Webhook Secret""" return settings.active_creem_webhook_secret @classmethod def get_product_id(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: """根据当前全局 ENV 确定性返回 Product ID""" return settings.active_creem_product_id @classmethod def get_webhook_secrets(cls, provider_config: Optional[Dict[str, Any]] = None) -> list[str]: """获取当前全局 ENV 的 Webhook Secret""" secret = cls.get_webhook_secret(provider_config) return [secret] if secret else [] @classmethod async def create_product( cls, name: str, price_cents: int, currency: str = "USD", description: Optional[str] = None, billing_type: str = "onetime", provider_config: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """ 在 Creem 创建商品 POST /v1/products """ api_key = cls.get_api_key(provider_config) base_url = cls.get_base_url(provider_config, api_key=api_key) if not api_key: raise BizLogicError("Creem API Key is not configured") url = f"{base_url}/v1/products" headers = { "x-api-key": api_key, "Content-Type": "application/json", } # Creem API 要求 billing_type 枚举必须为 'onetime' 或 'recurring' clean_billing_type = "recurring" if "recur" in billing_type.lower() else "onetime" desc = (description or f"{name} Application Service").strip()[:500] payload = { "name": name, "price": price_cents, "currency": currency.upper(), "billing_type": clean_billing_type, "description": desc, } logger.info(f"💳 [CREEM] Creating product on {url}: name={name} price={price_cents} {currency}") timeout = aiohttp.ClientTimeout(total=15) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(url, headers=headers, json=payload) as resp: resp_text = await resp.text() if resp.status >= 400: logger.error(f"❌ [CREEM] Product creation failed ({resp.status}): {resp_text}") raise BizLogicError(f"Creem create product failed: {resp_text}") try: data = json.loads(resp_text) logger.info(f"✅ [CREEM] Product created: id={data.get('id')}") return data except Exception as e: logger.error(f"❌ [CREEM] Parse product response error: {e}") raise BizLogicError("Invalid response from Creem API") @classmethod async def create_checkout_session( cls, product_id: str, request_id: str, success_url: str, customer_email: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, provider_config: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """ 创建 Creem 收银台 Checkout Session POST /v1/checkouts """ api_key = cls.get_api_key(provider_config) base_url = cls.get_base_url(provider_config) if not api_key: raise BizLogicError("Creem API Key is not configured") url = f"{base_url}/v1/checkouts" headers = { "x-api-key": api_key, "Content-Type": "application/json", } payload: Dict[str, Any] = { "product_id": product_id, "request_id": request_id, "success_url": success_url, } if customer_email: payload["customer"] = {"email": customer_email} if metadata: payload["metadata"] = metadata logger.info(f"💳 [CREEM] Creating checkout on {url} for product={product_id} request_id={request_id}") timeout = aiohttp.ClientTimeout(total=15) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(url, headers=headers, json=payload) as resp: resp_text = await resp.text() if resp.status >= 400: logger.error(f"❌ [CREEM] Checkout creation failed ({resp.status}): {resp_text}") raise BizLogicError(f"Creem create checkout failed: {resp_text}") try: data = json.loads(resp_text) logger.info(f"✅ [CREEM] Checkout created: id={data.get('id')} url={data.get('checkout_url')}") return data except Exception as e: logger.error(f"❌ [CREEM] Parse checkout response error: {e}") raise BizLogicError("Invalid response from Creem API")