# 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: str) -> bool: """ 验证 Creem Webhook 签名 (HMAC-SHA256) Creem 发送 creem-signature 头部,为 HEX 格式 """ if not signature or not secret: return False try: computed = hmac.new(secret.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest() return hmac.compare_digest(computed.lower(), signature.strip().lower()) 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 get_api_key(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: if provider_config and provider_config.get("api_key"): return provider_config["api_key"] return settings.creem_api_key @classmethod def get_base_url(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: if provider_config and provider_config.get("base_url"): return provider_config["base_url"].rstrip("/") if provider_config and provider_config.get("test_mode") is False: return "https://api.creem.io" return settings.creem_base_url.rstrip("/") or "https://test-api.creem.io" @classmethod def get_webhook_secret(cls, provider_config: Optional[Dict[str, Any]] = None) -> str: if provider_config and provider_config.get("webhook_secret"): return provider_config["webhook_secret"] return settings.creem_webhook_secret @classmethod async def create_product( cls, name: str, price_cents: int, currency: str = "USD", description: Optional[str] = None, billing_type: str = "one_time", 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) 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", } payload = { "name": name, "price": price_cents, "currency": currency.upper(), "billing_type": billing_type, } if description: payload["description"] = description[:500] 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")