service.py 7.4 KB

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