creem.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # app/core/creem.py
  2. import hmac
  3. import hashlib
  4. import json
  5. from typing import Dict, Any, Optional
  6. import aiohttp
  7. from app.core.config import settings
  8. from app.core.logger import logger
  9. from app.core.biz_exception import BizLogicError
  10. def verify_creem_signature(payload_bytes: bytes, signature: str, secret_or_secrets: Any) -> bool:
  11. """
  12. 验证 Creem Webhook 签名 (HMAC-SHA256)
  13. Creem 发送 creem-signature 头部,为 HEX 格式
  14. 支持单个 secret 字符串或候选 secrets 列表(生产+测试)
  15. """
  16. if not signature or not secret_or_secrets:
  17. return False
  18. secrets = [secret_or_secrets] if isinstance(secret_or_secrets, str) else list(secret_or_secrets)
  19. for sec in secrets:
  20. if not sec:
  21. continue
  22. try:
  23. computed = hmac.new(sec.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()
  24. if hmac.compare_digest(computed.lower(), signature.strip().lower()):
  25. return True
  26. except Exception as e:
  27. logger.error(f"❌ [CREEM] Webhook signature verification error: {e}")
  28. return False
  29. class CreemClient:
  30. """
  31. Creem Payment API Client
  32. Official documentation: https://docs.creem.io/code/sdks/ai-agents
  33. """
  34. @classmethod
  35. def is_prod_mode(cls) -> bool:
  36. """
  37. 根据全局环境变量 ENV 控制整个系统是生产还是测试:
  38. - ENV='PROD' (或 prod/production) -> 生产正式环境,走生产配置
  39. - ENV='DEV' (或 dev/test/local) -> 测试环境,走测试配置
  40. """
  41. return settings.is_prod
  42. @classmethod
  43. def is_test_environment(cls, provider_config: Optional[Dict[str, Any]] = None) -> bool:
  44. return not cls.is_prod_mode()
  45. @classmethod
  46. def get_api_key(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  47. """根据当前全局 ENV 确定性返回 API Key"""
  48. return settings.active_creem_api_key
  49. @classmethod
  50. def get_base_url(cls, provider_config: Optional[Dict[str, Any]] = None, api_key: str = "") -> str:
  51. """根据当前全局 ENV 确定性返回 Base URL"""
  52. return settings.active_creem_base_url
  53. @classmethod
  54. def get_webhook_secret(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  55. """根据当前全局 ENV 确定性返回 Webhook Secret"""
  56. return settings.active_creem_webhook_secret
  57. @classmethod
  58. def get_product_id(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  59. """根据当前全局 ENV 确定性返回 Product ID"""
  60. return settings.active_creem_product_id
  61. @classmethod
  62. def get_webhook_secrets(cls, provider_config: Optional[Dict[str, Any]] = None) -> list[str]:
  63. """获取当前全局 ENV 的 Webhook Secret"""
  64. secret = cls.get_webhook_secret(provider_config)
  65. return [secret] if secret else []
  66. @classmethod
  67. async def create_product(
  68. cls,
  69. name: str,
  70. price_cents: int,
  71. currency: str = "USD",
  72. description: Optional[str] = None,
  73. billing_type: str = "onetime",
  74. provider_config: Optional[Dict[str, Any]] = None,
  75. ) -> Dict[str, Any]:
  76. """
  77. 在 Creem 创建商品
  78. POST /v1/products
  79. """
  80. api_key = cls.get_api_key(provider_config)
  81. base_url = cls.get_base_url(provider_config, api_key=api_key)
  82. if not api_key:
  83. raise BizLogicError("Creem API Key is not configured")
  84. url = f"{base_url}/v1/products"
  85. headers = {
  86. "x-api-key": api_key,
  87. "Content-Type": "application/json",
  88. }
  89. # Creem API 要求 billing_type 枚举必须为 'onetime' 或 'recurring'
  90. clean_billing_type = "recurring" if "recur" in billing_type.lower() else "onetime"
  91. desc = (description or f"{name} Application Service").strip()[:500]
  92. payload = {
  93. "name": name,
  94. "price": price_cents,
  95. "currency": currency.upper(),
  96. "billing_type": clean_billing_type,
  97. "description": desc,
  98. }
  99. logger.info(f"💳 [CREEM] Creating product on {url}: name={name} price={price_cents} {currency}")
  100. timeout = aiohttp.ClientTimeout(total=15)
  101. async with aiohttp.ClientSession(timeout=timeout) as session:
  102. async with session.post(url, headers=headers, json=payload) as resp:
  103. resp_text = await resp.text()
  104. if resp.status >= 400:
  105. logger.error(f"❌ [CREEM] Product creation failed ({resp.status}): {resp_text}")
  106. raise BizLogicError(f"Creem create product failed: {resp_text}")
  107. try:
  108. data = json.loads(resp_text)
  109. logger.info(f"✅ [CREEM] Product created: id={data.get('id')}")
  110. return data
  111. except Exception as e:
  112. logger.error(f"❌ [CREEM] Parse product response error: {e}")
  113. raise BizLogicError("Invalid response from Creem API")
  114. @classmethod
  115. async def create_checkout_session(
  116. cls,
  117. product_id: str,
  118. request_id: str,
  119. success_url: str,
  120. customer_email: Optional[str] = None,
  121. metadata: Optional[Dict[str, Any]] = None,
  122. provider_config: Optional[Dict[str, Any]] = None,
  123. ) -> Dict[str, Any]:
  124. """
  125. 创建 Creem 收银台 Checkout Session
  126. POST /v1/checkouts
  127. """
  128. api_key = cls.get_api_key(provider_config)
  129. base_url = cls.get_base_url(provider_config)
  130. if not api_key:
  131. raise BizLogicError("Creem API Key is not configured")
  132. url = f"{base_url}/v1/checkouts"
  133. headers = {
  134. "x-api-key": api_key,
  135. "Content-Type": "application/json",
  136. }
  137. payload: Dict[str, Any] = {
  138. "product_id": product_id,
  139. "request_id": request_id,
  140. "success_url": success_url,
  141. }
  142. if customer_email:
  143. payload["customer"] = {"email": customer_email}
  144. if metadata:
  145. payload["metadata"] = metadata
  146. logger.info(f"💳 [CREEM] Creating checkout on {url} for product={product_id} request_id={request_id}")
  147. timeout = aiohttp.ClientTimeout(total=15)
  148. async with aiohttp.ClientSession(timeout=timeout) as session:
  149. async with session.post(url, headers=headers, json=payload) as resp:
  150. resp_text = await resp.text()
  151. if resp.status >= 400:
  152. logger.error(f"❌ [CREEM] Checkout creation failed ({resp.status}): {resp_text}")
  153. raise BizLogicError(f"Creem create checkout failed: {resp_text}")
  154. try:
  155. data = json.loads(resp_text)
  156. logger.info(f"✅ [CREEM] Checkout created: id={data.get('id')} url={data.get('checkout_url')}")
  157. return data
  158. except Exception as e:
  159. logger.error(f"❌ [CREEM] Parse checkout response error: {e}")
  160. raise BizLogicError("Invalid response from Creem API")