service.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from app.api.v1.module_system.auth.schema import AuthSchema
  2. from app.core.exceptions import CustomException
  3. from app.core.logger import log
  4. from app.utils.snowflake import get_snowflake_id_str, get_snowflake_id
  5. from typing import Optional
  6. import time
  7. from .crud import OpenConfCRUD, OpenTransferCRUD
  8. from .schema import OpenConfOutSchema, OpenConfUpdateSchema, OpenTransferSchema, OpenTransferOutSchema, \
  9. OpenTransferQuerySchema
  10. from app.plugin.module_payment.account import AccountService, TransferCRUD, TransferOutSchema
  11. import aiohttp
  12. import asyncio
  13. from ..apikey.service import TenantApiKeyService
  14. async def fetch_manual_retry(
  15. session,
  16. url: str,
  17. notify_id: str,
  18. timestamp: int,
  19. content: str,
  20. max_retries: int=2
  21. ):
  22. for attempt in range(max_retries):
  23. try:
  24. log.debug("第 {} 次尝试: {}", attempt + 1, url)
  25. form_data = aiohttp.FormData()
  26. form_data.add_field('notify_id', notify_id)
  27. form_data.add_field('timestamp', timestamp)
  28. form_data.add_field('content', content)
  29. async with session.post(url=url, data=form_data) as response:
  30. if response.status == 200:
  31. return await response.text()
  32. elif response.status in [500, 502, 503]:
  33. # 服务器错误,准备重试
  34. pass
  35. else:
  36. # 客户端错误,直接抛出,不再重试
  37. response.raise_for_status()
  38. except (aiohttp.ClientError, asyncio.TimeoutError) as e:
  39. if attempt < max_retries - 1:
  40. # 计算等待时间 (简单的指数退避: 1s, 2s, 4s...)
  41. wait_time = 2 ** attempt
  42. log.debug("等待 {} 秒后重试...", wait_time)
  43. await asyncio.sleep(wait_time)
  44. else:
  45. log.debug("达到最大重试次数,放弃。")
  46. return None
  47. return None
  48. class OpenTransferService:
  49. @classmethod
  50. async def open_return_service(
  51. cls,
  52. auth: AuthSchema,
  53. order_no: str,
  54. ) -> bool:
  55. """
  56. 发送转账回调通知
  57. 参数:
  58. - auth: 认证信息
  59. - order_no: 订单号
  60. 返回:
  61. - bool: 是否成功发送通知
  62. """
  63. try:
  64. transfer_crud = TransferCRUD(auth)
  65. transfer_data = await transfer_crud.get_by_order_no(order_no)
  66. if not transfer_data or not transfer_data.out_biz_no:
  67. log.info("开放回调通知: 订单不存在或缺少 out_biz_no, order_no={}", order_no)
  68. return False
  69. open_transfer_crud = OpenTransferCRUD(auth)
  70. open_data = await open_transfer_crud.get(out_biz_no=transfer_data.out_biz_no)
  71. if not open_data:
  72. log.info("开放回调通知: 开放转账记录不存在, out_biz_no={}", transfer_data.out_biz_no)
  73. return False
  74. auth.tenant_id = open_data.tenant_id
  75. auth.check_data_scope = True
  76. apikey_data = None
  77. # 先从apikey那return_url,否则使用conf
  78. if open_data.api_key:
  79. apikey_data = await TenantApiKeyService.get_apikey_service(auth=auth, api_key=open_data.api_key)
  80. if apikey_data:
  81. return_url = apikey_data.return_url
  82. else:
  83. conf = await OpenConfService.get_conf_service(auth)
  84. if not conf:
  85. log.info("开放回调通知: 开放转账配置不存在, tenant_id={}", auth.tenant_id)
  86. return False
  87. return_url = conf.return_url
  88. if not return_url:
  89. log.info("开放回调通知: 回调地址不存在")
  90. return False
  91. result = TransferOutSchema.model_validate(transfer_data)
  92. result.third_biz_no = open_data.third_biz_no
  93. notify_id = f"n{get_snowflake_id()}"
  94. timestamp = int(time.time() * 1000)
  95. content = result.model_dump_json(exclude_none=True)
  96. timeout = aiohttp.ClientTimeout(total=30)
  97. async with aiohttp.ClientSession(timeout=timeout) as session:
  98. log.info("开放回调通知: 回调请求 third_biz_no={} order_no={}, url={}, notify_id={}",
  99. open_data.third_biz_no, order_no, return_url, notify_id)
  100. await fetch_manual_retry(
  101. session, return_url, notify_id, timestamp, content
  102. )
  103. return True
  104. except Exception as e:
  105. log.error("开放回调通知异常: order_no={}, error={}", order_no, e, exc_info=True)
  106. return False
  107. @classmethod
  108. async def open_query_service(
  109. cls,
  110. auth: AuthSchema,
  111. query: OpenTransferQuerySchema
  112. ) -> dict:
  113. crud = OpenTransferCRUD(auth)
  114. transfer_data = await crud.get(third_biz_no=query.third_biz_no)
  115. if transfer_data is None:
  116. raise CustomException("三方订单号不存在")
  117. result = await AccountService.transfer_detail_service(auth=auth, out_biz_no=transfer_data.out_biz_no)
  118. result.third_biz_no = transfer_data.third_biz_no
  119. return result.model_dump(exclude_none=True)
  120. @classmethod
  121. async def open_transfer_service(
  122. cls,
  123. auth: AuthSchema,
  124. data: OpenTransferSchema
  125. ) -> OpenTransferOutSchema:
  126. third_biz_no = data.third_biz_no
  127. if not third_biz_no:
  128. raise CustomException("三方订单号不能为空")
  129. # 先查询是否存在三方订单号
  130. crud = OpenTransferCRUD(auth)
  131. existing = await crud.get(third_biz_no=third_biz_no)
  132. if existing:
  133. raise CustomException("三方订单号已存在")
  134. # 执行转账记录创建
  135. result = await AccountService.transfer_service(auth=auth, data=data)
  136. log.info(f"租户资金专户转账发起成功: 企业: {data.enterprise_id}, 金额: {data.amount}")
  137. # 保存三方订单号关联记录
  138. create_data = {
  139. "third_biz_no": third_biz_no,
  140. "out_biz_no": result.out_biz_no,
  141. "api_key": data.api_key,
  142. }
  143. await crud.create(create_data)
  144. return OpenTransferOutSchema(
  145. status=result.status,
  146. order_no=result.order_no,
  147. third_biz_no=third_biz_no,
  148. )
  149. class OpenConfService:
  150. """开放配置服务层"""
  151. @classmethod
  152. async def get_conf_service(
  153. cls,
  154. auth: AuthSchema,
  155. ) -> Optional[OpenConfOutSchema]:
  156. """
  157. 查询开放配置
  158. """
  159. crud = OpenConfCRUD(auth)
  160. result = await crud.get(tenant_id=auth.tenant_id)
  161. if result is not None:
  162. return OpenConfOutSchema.model_validate(result)
  163. return None
  164. @classmethod
  165. async def save_conf_service(
  166. cls,
  167. auth: AuthSchema,
  168. data: OpenConfUpdateSchema,
  169. ) -> OpenConfOutSchema:
  170. """
  171. 创建/更新开放配置(前端只允许配置回调地址)
  172. """
  173. # 先查询是否存在配置
  174. update_data = {
  175. "notify_url": data.notify_url,
  176. "return_url": data.return_url,
  177. }
  178. crud = OpenConfCRUD(auth)
  179. existing = await crud.get_first()
  180. if not existing:
  181. update_data["app_id"] = get_snowflake_id_str(auth.tenant_id)
  182. update_data["gateway_url"] = "https://api.qcsj88888.com"
  183. result = await crud.create(update_data)
  184. log.info(f"开放配置创建成功: 租户ID: {auth.tenant_id}")
  185. else:
  186. result = await crud.update(existing.id, update_data)
  187. log.info(f"开放配置更新成功: 租户ID: {auth.tenant_id}")
  188. return OpenConfOutSchema.model_validate(result)