service.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. ):
  49. try:
  50. crud = TransferCRUD(auth)
  51. transfer = await crud.get_by_order_no(order_no)
  52. if not transfer or not transfer.out_biz_no:
  53. return
  54. crud = OpenTransferCRUD(auth)
  55. open_data = await crud.get(out_biz_no=transfer.out_biz_no)
  56. if not open_data:
  57. return
  58. conf = await OpenConfService.get_conf_service(auth)
  59. if not conf:
  60. return
  61. result = TransferOutSchema.model_validate(transfer).model_dump(exclude_none=True)
  62. result["third_biz_no"] = open_data.third_biz_no
  63. notify_id = f"n{get_snowflake_id()}"
  64. timestamp = int(time.time() * 1000)
  65. content = json.dumps(result)
  66. async with aiohttp.ClientSession() as session:
  67. log.info(f"调用回调接口: {conf.return_url}")
  68. await fetch_manual_retry(
  69. session, conf.return_url, notify_id, conf.app_id, timestamp, content
  70. )
  71. except: #ignore
  72. pass
  73. @classmethod
  74. async def open_query_service(
  75. cls,
  76. auth: AuthSchema,
  77. query: OpenTransferQuerySchema
  78. ) -> dict:
  79. crud = OpenTransferCRUD(auth)
  80. transfer_data = await crud.get(third_biz_no=query.third_biz_no)
  81. if transfer_data is None:
  82. raise CustomException("三方订单号不存在")
  83. result = await AccountService.transfer_detail_service(auth=auth, out_biz_no=transfer_data.out_biz_no)
  84. result_dict = result.model_dump(exclude_none=True)
  85. result_dict.update({"third_biz_no": transfer_data.third_biz_no})
  86. return result_dict
  87. @classmethod
  88. async def open_transfer_service(
  89. cls,
  90. auth: AuthSchema,
  91. data: OpenTransferSchema
  92. ) -> OpenTransferOutSchema:
  93. third_biz_no = data.third_biz_no
  94. if not third_biz_no:
  95. raise CustomException("三方订单号不能为空")
  96. # 先查询是否存在三方订单号
  97. crud = OpenTransferCRUD(auth)
  98. existing = await crud.get(third_biz_no=third_biz_no)
  99. if existing:
  100. raise CustomException("三方订单号已存在")
  101. # 执行转账记录创建
  102. result = await AccountService.transfer_service(auth=auth, data=data)
  103. log.info(f"租户资金专户转账发起成功: 企业: {data.enterprise_id}, 金额: {data.amount}")
  104. # 保存三方订单号关联记录
  105. create_data = {
  106. "third_biz_no": third_biz_no,
  107. "out_biz_no": result.out_biz_no,
  108. }
  109. await crud.create(create_data)
  110. return OpenTransferOutSchema(
  111. status=result.status,
  112. order_no=result.order_no,
  113. third_biz_no=third_biz_no,
  114. )
  115. class OpenConfService:
  116. """开放配置服务层"""
  117. @classmethod
  118. async def get_conf_service(
  119. cls,
  120. auth: AuthSchema,
  121. ) -> Optional[OpenConfOutSchema]:
  122. """
  123. 查询开放配置
  124. """
  125. crud = OpenConfCRUD(auth)
  126. result = await crud.get_first()
  127. if result is not None:
  128. return OpenConfOutSchema.model_validate(result)
  129. return None
  130. @classmethod
  131. async def save_conf_service(
  132. cls,
  133. auth: AuthSchema,
  134. data: OpenConfUpdateSchema,
  135. ) -> OpenConfOutSchema:
  136. """
  137. 创建/更新开放配置(前端只允许配置回调地址)
  138. """
  139. # 先查询是否存在配置
  140. update_data = {
  141. "notify_url": data.notify_url,
  142. "return_url": data.return_url,
  143. }
  144. crud = OpenConfCRUD(auth)
  145. existing = await crud.get_first()
  146. if not existing:
  147. update_data["app_id"] = get_snowflake_id_str(auth.tenant_id)
  148. update_data["gateway_url"] = "https://api.qcsj88888.com"
  149. result = await crud.create(update_data)
  150. log.info(f"开放配置创建成功: 租户ID: {auth.tenant_id}")
  151. else:
  152. result = await crud.update(existing.id, update_data)
  153. log.info(f"开放配置更新成功: 租户ID: {auth.tenant_id}")
  154. return OpenConfOutSchema.model_validate(result)