creem.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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: str) -> bool:
  11. """
  12. 验证 Creem Webhook 签名 (HMAC-SHA256)
  13. Creem 发送 creem-signature 头部,为 HEX 格式
  14. """
  15. if not signature or not secret:
  16. return False
  17. try:
  18. computed = hmac.new(secret.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()
  19. return hmac.compare_digest(computed.lower(), signature.strip().lower())
  20. except Exception as e:
  21. logger.error(f"❌ [CREEM] Webhook signature verification error: {e}")
  22. return False
  23. class CreemClient:
  24. """
  25. Creem Payment API Client
  26. Official documentation: https://docs.creem.io/code/sdks/ai-agents
  27. """
  28. @classmethod
  29. def get_api_key(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  30. if provider_config and provider_config.get("api_key"):
  31. return provider_config["api_key"]
  32. return settings.creem_api_key
  33. @classmethod
  34. def get_base_url(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  35. if provider_config and provider_config.get("base_url"):
  36. return provider_config["base_url"].rstrip("/")
  37. if provider_config and provider_config.get("test_mode") is False:
  38. return "https://api.creem.io"
  39. return settings.creem_base_url.rstrip("/") or "https://test-api.creem.io"
  40. @classmethod
  41. def get_webhook_secret(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
  42. if provider_config and provider_config.get("webhook_secret"):
  43. return provider_config["webhook_secret"]
  44. return settings.creem_webhook_secret
  45. @classmethod
  46. async def create_product(
  47. cls,
  48. name: str,
  49. price_cents: int,
  50. currency: str = "USD",
  51. description: Optional[str] = None,
  52. billing_type: str = "one_time",
  53. provider_config: Optional[Dict[str, Any]] = None,
  54. ) -> Dict[str, Any]:
  55. """
  56. 在 Creem 创建商品
  57. POST /v1/products
  58. """
  59. api_key = cls.get_api_key(provider_config)
  60. base_url = cls.get_base_url(provider_config)
  61. if not api_key:
  62. raise BizLogicError("Creem API Key is not configured")
  63. url = f"{base_url}/v1/products"
  64. headers = {
  65. "x-api-key": api_key,
  66. "Content-Type": "application/json",
  67. }
  68. payload = {
  69. "name": name,
  70. "price": price_cents,
  71. "currency": currency.upper(),
  72. "billing_type": billing_type,
  73. }
  74. if description:
  75. payload["description"] = description[:500]
  76. logger.info(f"💳 [CREEM] Creating product on {url}: name={name} price={price_cents} {currency}")
  77. timeout = aiohttp.ClientTimeout(total=15)
  78. async with aiohttp.ClientSession(timeout=timeout) as session:
  79. async with session.post(url, headers=headers, json=payload) as resp:
  80. resp_text = await resp.text()
  81. if resp.status >= 400:
  82. logger.error(f"❌ [CREEM] Product creation failed ({resp.status}): {resp_text}")
  83. raise BizLogicError(f"Creem create product failed: {resp_text}")
  84. try:
  85. data = json.loads(resp_text)
  86. logger.info(f"✅ [CREEM] Product created: id={data.get('id')}")
  87. return data
  88. except Exception as e:
  89. logger.error(f"❌ [CREEM] Parse product response error: {e}")
  90. raise BizLogicError("Invalid response from Creem API")
  91. @classmethod
  92. async def create_checkout_session(
  93. cls,
  94. product_id: str,
  95. request_id: str,
  96. success_url: str,
  97. customer_email: Optional[str] = None,
  98. metadata: Optional[Dict[str, Any]] = None,
  99. provider_config: Optional[Dict[str, Any]] = None,
  100. ) -> Dict[str, Any]:
  101. """
  102. 创建 Creem 收银台 Checkout Session
  103. POST /v1/checkouts
  104. """
  105. api_key = cls.get_api_key(provider_config)
  106. base_url = cls.get_base_url(provider_config)
  107. if not api_key:
  108. raise BizLogicError("Creem API Key is not configured")
  109. url = f"{base_url}/v1/checkouts"
  110. headers = {
  111. "x-api-key": api_key,
  112. "Content-Type": "application/json",
  113. }
  114. payload: Dict[str, Any] = {
  115. "product_id": product_id,
  116. "request_id": request_id,
  117. "success_url": success_url,
  118. }
  119. if customer_email:
  120. payload["customer"] = {"email": customer_email}
  121. if metadata:
  122. payload["metadata"] = metadata
  123. logger.info(f"💳 [CREEM] Creating checkout on {url} for product={product_id} request_id={request_id}")
  124. timeout = aiohttp.ClientTimeout(total=15)
  125. async with aiohttp.ClientSession(timeout=timeout) as session:
  126. async with session.post(url, headers=headers, json=payload) as resp:
  127. resp_text = await resp.text()
  128. if resp.status >= 400:
  129. logger.error(f"❌ [CREEM] Checkout creation failed ({resp.status}): {resp_text}")
  130. raise BizLogicError(f"Creem create checkout failed: {resp_text}")
  131. try:
  132. data = json.loads(resp_text)
  133. logger.info(f"✅ [CREEM] Checkout created: id={data.get('id')} url={data.get('checkout_url')}")
  134. return data
  135. except Exception as e:
  136. logger.error(f"❌ [CREEM] Parse checkout response error: {e}")
  137. raise BizLogicError("Invalid response from Creem API")