service.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. from datetime import datetime
  2. from decimal import Decimal
  3. from typing import Any, Optional
  4. from redis.asyncio import Redis
  5. from app.api.v1.module_system.auth.schema import AuthSchema
  6. from app.core.alipay import AlipayClient
  7. from app.core.exceptions import CustomException
  8. from app.core.logger import log
  9. from app.utils.snowflake import get_snowflake_id_str
  10. from app.plugin.module_payment.enterprise.crud import EnterpriseCRUD
  11. from .crud import AccountCRUD, TransferCRUD, DepositCRUD, WithdrawCRUD
  12. from .enums import (
  13. DepositStatusEnum,
  14. WithdrawStatusEnum,
  15. )
  16. from .schema import (
  17. AccountAuthorizeApplySchema,
  18. AccountAuthorizeApplyOutSchema,
  19. AccountCreateSchema,
  20. AccountDepositSchema,
  21. AccountDepositOutSchema,
  22. AccountOperationOutSchema,
  23. AccountQuerySchema,
  24. AccountTransferSchema,
  25. AccountTransferOutSchema,
  26. AccountWithdrawSchema,
  27. ReceiptApplySchema,
  28. TransferListOutSchema,
  29. TransferOutSchema,
  30. TenantTransferCreate,
  31. TenantTransferResponse,
  32. )
  33. from ..openapi.crud import OpenTransferCRUD
  34. # 支付宝资金专户转账错误码 → 友好提示
  35. _TRANSFER_ERROR_HINTS = {
  36. "SYSTEM_ERROR": "系统繁忙,请稍后重试",
  37. "INVALID_PARAMETER": "请求参数有误,请检查后重试",
  38. "AMOUNT_LESS_THAN_ONE_CENT": "转账金额不能低于 0.01 元",
  39. "BALANCE_IS_NOT_ENOUGH": "企业余额不足,建议充值",
  40. "BANK_RESPONSE_ERROR": "银行处理失败:账户异常",
  41. "CARD_BIN_ERROR": "收款银行账号不正确,请确认",
  42. "DUPLICATE_DIFFERENT_REQUEST": "重复请求但参数不一致,请检查",
  43. "EXCEED_LIMIT_SM_MIN_AMOUNT": "转账金额不能低于 0.1 元",
  44. "EXCEED_LIMIT_DM_MAX_AMOUNT": "超出单日转账限额,请明天再试或联系管理员提升限额",
  45. "INVALID_ACCOUNT_BOOK": "资金专户不存在,请检查专户号",
  46. "INVALID_CARDNO": "无效的收款银行卡号",
  47. "INVALID_IDENTITY_TYPE": "收款方身份类型不匹配",
  48. "NO_AGREEMENT": "无转账权限,请联系管理员",
  49. "PAYEE_CARD_INFO_ERROR": "收款方账号或银行卡信息有误,请核实",
  50. "PAYEE_NOT_EXIST": "收款账号不存在或姓名有误",
  51. "PAYER_BALANCE_NOT_ENOUGH": "付款方余额不足,建议充值",
  52. "REQUEST_PROCESSING": "系统处理中,请稍后重试",
  53. "TRANS_AUTH_NO_EXIST": "转账授权协议不存在,请先签约",
  54. }
  55. def _parse_dt(val: str | None) -> datetime | None:
  56. """解析支付宝日期字符串"""
  57. if not val:
  58. return None
  59. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
  60. try:
  61. return datetime.strptime(val, fmt)
  62. except ValueError:
  63. continue
  64. return None
  65. class AccountService:
  66. """资金专户服务层"""
  67. @classmethod
  68. async def stat_transfer_amount_service(
  69. cls,
  70. auth: AuthSchema,
  71. tenant_id: Optional[int] = None,
  72. enterprise_id: Optional[str] = None,
  73. start_date: Optional[datetime] = None,
  74. end_date: Optional[datetime] = None,
  75. ) -> Decimal:
  76. """
  77. 统计转账金额(✅)
  78. 统计企业在指定时间范围内的转账总金额以及每天的转账金额。
  79. """
  80. crud = TransferCRUD(auth)
  81. return await crud.get_transfer_amount(
  82. tenant_id=tenant_id,
  83. enterprise_id=enterprise_id,
  84. start_date=start_date,
  85. end_date=end_date,
  86. )
  87. @classmethod
  88. async def authorize_apply_service(
  89. cls,
  90. auth: AuthSchema,
  91. data: AccountAuthorizeApplySchema
  92. ) -> AccountAuthorizeApplyOutSchema:
  93. """
  94. 申请转账授权签约(✅)
  95. 调用: alipay.commerce.ec.trans.authorize.apply
  96. """
  97. from alipay.aop.api.request.AlipayCommerceEcTransAuthorizeApplyRequest import (
  98. AlipayCommerceEcTransAuthorizeApplyRequest,
  99. )
  100. from alipay.aop.api.domain.AlipayCommerceEcTransAuthorizeApplyModel import (
  101. AlipayCommerceEcTransAuthorizeApplyModel,
  102. )
  103. from alipay.aop.api.response.AlipayCommerceEcTransAuthorizeApplyResponse import (
  104. AlipayCommerceEcTransAuthorizeApplyResponse,
  105. )
  106. model = AlipayCommerceEcTransAuthorizeApplyModel()
  107. model.enterprise_id = data.enterprise_id
  108. request = AlipayCommerceEcTransAuthorizeApplyRequest()
  109. request.biz_model = model
  110. client = AlipayClient.get_client()
  111. response = client.execute(request)
  112. if not response:
  113. raise CustomException(msg="申请转账授权失败: 无响应")
  114. result = AlipayCommerceEcTransAuthorizeApplyResponse()
  115. result.parse_response_content(response)
  116. if not result.is_success():
  117. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  118. raise CustomException(msg=f"申请转账授权失败: {result.msg}")
  119. return AccountAuthorizeApplyOutSchema(
  120. sign_url=result.sign_url,
  121. )
  122. @classmethod
  123. async def create_account_service(
  124. cls,
  125. auth: AuthSchema,
  126. data: AccountCreateSchema
  127. ) -> AccountOperationOutSchema:
  128. """
  129. 开通资金专户(✅)
  130. 调用: alipay.commerce.ec.trans.account.create
  131. """
  132. from alipay.aop.api.request.AlipayCommerceEcTransAccountCreateRequest import (
  133. AlipayCommerceEcTransAccountCreateRequest,
  134. )
  135. from alipay.aop.api.domain.AlipayCommerceEcTransAccountCreateModel import (
  136. AlipayCommerceEcTransAccountCreateModel,
  137. )
  138. from alipay.aop.api.response.AlipayCommerceEcTransAccountCreateResponse import (
  139. AlipayCommerceEcTransAccountCreateResponse,
  140. )
  141. model = AlipayCommerceEcTransAccountCreateModel()
  142. model.enterprise_id = data.enterprise_id
  143. # model.account_type = data.account_type or "ALL" # 收支全能户
  144. # model.scene = data.scene or "B2B_TRANS" # ToB转账场景
  145. model.account_type = "ALL"
  146. model.scene = "B2B_TRANS"
  147. request = AlipayCommerceEcTransAccountCreateRequest()
  148. request.biz_model = model
  149. client = AlipayClient.get_client()
  150. response = client.execute(request)
  151. if not response:
  152. raise CustomException(msg="开通资金专户失败: 无响应")
  153. result = AlipayCommerceEcTransAccountCreateResponse()
  154. result.parse_response_content(response)
  155. if not result.is_success():
  156. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  157. raise CustomException(msg=f"开通资金专户失败: {result.msg}")
  158. account_data = AccountCreateSchema(
  159. enterprise_id=model.enterprise_id,
  160. account_book_id=result.account_book_id,
  161. account_type=model.account_type,
  162. scene=model.scene,
  163. )
  164. if result.account_book_id:
  165. account_data.account_book_id = result.account_book_id
  166. await AccountCRUD(auth).create(account_data)
  167. return AccountOperationOutSchema(
  168. enterprise_id=account_data.enterprise_id,
  169. account_book_id=account_data.account_book_id,
  170. )
  171. @classmethod
  172. async def deposit_service(
  173. cls,
  174. auth: AuthSchema,
  175. data: AccountDepositSchema
  176. ) -> AccountDepositOutSchema:
  177. """
  178. 资金专户充值(✅)
  179. 调用: alipay.commerce.ec.trans.account.deposit
  180. """
  181. from alipay.aop.api.request.AlipayCommerceEcTransAccountDepositRequest import (
  182. AlipayCommerceEcTransAccountDepositRequest,
  183. )
  184. from alipay.aop.api.domain.AlipayCommerceEcTransAccountDepositModel import (
  185. AlipayCommerceEcTransAccountDepositModel,
  186. )
  187. from alipay.aop.api.response.AlipayCommerceEcTransAccountDepositResponse import (
  188. AlipayCommerceEcTransAccountDepositResponse,
  189. )
  190. model = AlipayCommerceEcTransAccountDepositModel()
  191. model.enterprise_id = data.enterprise_id
  192. model.account_book_id = data.account_book_id
  193. model.amount = str(data.amount)
  194. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  195. request = AlipayCommerceEcTransAccountDepositRequest()
  196. request.biz_model = model
  197. client = AlipayClient.get_client()
  198. response = client.execute(request)
  199. if not response:
  200. raise CustomException(msg="充值失败: 无响应")
  201. result = AlipayCommerceEcTransAccountDepositResponse()
  202. result.parse_response_content(response)
  203. if not result.is_success():
  204. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  205. raise CustomException(msg=f"充值失败: {result.msg}")
  206. deposit_crud = DepositCRUD(auth)
  207. deposit_data = {
  208. "enterprise_id": data.enterprise_id,
  209. "out_biz_no": model.out_biz_no,
  210. "account_book_id": data.account_book_id,
  211. "amount": data.amount,
  212. "url": result.url,
  213. "status": DepositStatusEnum.DEALING.value,
  214. "remark": data.remark,
  215. }
  216. await deposit_crud.create(deposit_data)
  217. return AccountDepositOutSchema(
  218. url=result.url,
  219. )
  220. @classmethod
  221. async def transfer_service(
  222. cls,
  223. auth: AuthSchema,
  224. data: AccountTransferSchema
  225. ) -> AccountTransferOutSchema:
  226. """
  227. 资金专户转账(✅)
  228. 调用: alipay.commerce.ec.trans.account.transfer
  229. """
  230. from alipay.aop.api.request.AlipayCommerceEcTransAccountTransferRequest import (
  231. AlipayCommerceEcTransAccountTransferRequest,
  232. )
  233. from alipay.aop.api.domain.AlipayCommerceEcTransAccountTransferModel import (
  234. AlipayCommerceEcTransAccountTransferModel,
  235. )
  236. from alipay.aop.api.response.AlipayCommerceEcTransAccountTransferResponse import (
  237. AlipayCommerceEcTransAccountTransferResponse,
  238. )
  239. from alipay.aop.api.domain.TransParticipant import (
  240. TransParticipant,
  241. )
  242. from alipay.aop.api.domain.BankCardExtInfoDTO import (
  243. BankCardExtInfoDTO,
  244. )
  245. # 检查资金专户是否存在
  246. account = await AccountCRUD(auth).get_by_account_book_id(data.account_book_id)
  247. if not account:
  248. raise CustomException(msg="资金账户不存在")
  249. if account.tenant_id != auth.tenant_id:
  250. raise CustomException(msg="无权限操作")
  251. if data.enterprise_id and account.enterprise_id != data.enterprise_id:
  252. raise CustomException(msg="参数错误")
  253. if not data.order_title and account.enterprise_id:
  254. enterprise = await EnterpriseCRUD(auth).get_by_enterprise_id(account.enterprise_id)
  255. if not enterprise:
  256. raise CustomException(msg="资金账户所属企业不存在")
  257. data.order_title = f"来自{enterprise.name}转账"
  258. model = AlipayCommerceEcTransAccountTransferModel()
  259. model.enterprise_id = account.enterprise_id
  260. model.account_book_id = account.account_book_id
  261. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  262. # 转账总金额,单位为元,精确到小数点后两位
  263. model.amount = str(data.amount)
  264. model.order_title = data.order_title
  265. payee_info = TransParticipant()
  266. payee_info.identity_type = data.payee_info.identity_type
  267. payee_info.name = data.payee_info.name
  268. payee_info.identity = data.payee_info.identity
  269. if data.payee_info.bankcard_ext_info:
  270. payee_info.bankcard_ext_info = BankCardExtInfoDTO.from_alipay_dict(
  271. data.payee_info.bankcard_ext_info.model_dump(exclude_none=True)
  272. )
  273. model.payee_info = payee_info
  274. request = AlipayCommerceEcTransAccountTransferRequest()
  275. request.biz_model = model
  276. client = AlipayClient.get_client()
  277. response = client.execute(request)
  278. if not response:
  279. raise CustomException(msg="转账失败: 无响应")
  280. result = AlipayCommerceEcTransAccountTransferResponse()
  281. result.parse_response_content(response)
  282. sub_code = getattr(result, 'sub_code', '') or ''
  283. sub_msg = getattr(result, 'sub_msg', '') or ''
  284. # 无论是否成功都写入转账记录,记录接口调用结果和错误信息,方便后续查询和排查
  285. transfer_crud = TransferCRUD(auth)
  286. transfer_data = {
  287. "enterprise_id": model.enterprise_id,
  288. "out_biz_no": model.out_biz_no,
  289. "account_book_id": model.account_book_id,
  290. "amount": model.amount,
  291. "order_title": model.order_title,
  292. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  293. "status": result.status,
  294. "order_no": result.order_no,
  295. "fund_order_id": result.fund_order_id,
  296. "remark":f"{result.code} - {result.msg} (sub_code={sub_code}, sub_msg={sub_msg})"
  297. }
  298. log.info(f"记录转账: {transfer_data}")
  299. await transfer_crud.create(transfer_data)
  300. if not result.is_success():
  301. # 优先用 sub_code 匹配
  302. hint = _TRANSFER_ERROR_HINTS.get(sub_code)
  303. # sub_code 无匹配时,尝试从 sub_msg 中提取错误码(支付宝部分接口sub_code返回unknown-sub-code)
  304. if not hint:
  305. for code_key, code_hint in _TRANSFER_ERROR_HINTS.items():
  306. if code_key in sub_msg:
  307. hint = code_hint
  308. break
  309. hint = hint or sub_msg or result.msg or "转账失败"
  310. log.error(f"支付宝接口调用失败: {result.code} - {result.msg} (sub_code={sub_code}, sub_msg={sub_msg})")
  311. raise CustomException(msg=f"转账失败: {hint}")
  312. return AccountTransferOutSchema(
  313. status=result.status,
  314. order_no=result.order_no,
  315. fund_order_id=result.fund_order_id,
  316. out_biz_no=model.out_biz_no,
  317. )
  318. @classmethod
  319. async def tenant_transfer_service(
  320. cls,
  321. auth: AuthSchema,
  322. tenant_id: int,
  323. data: TenantTransferCreate,
  324. request_ip: str,
  325. api_key_id: int | None = None,
  326. ) -> TenantTransferResponse:
  327. """
  328. 租户API转账(通过API Key认证)
  329. 调用: alipay.commerce.ec.trans.account.transfer
  330. """
  331. from alipay.aop.api.request.AlipayCommerceEcTransAccountTransferRequest import (
  332. AlipayCommerceEcTransAccountTransferRequest,
  333. )
  334. from alipay.aop.api.domain.AlipayCommerceEcTransAccountTransferModel import (
  335. AlipayCommerceEcTransAccountTransferModel,
  336. )
  337. from alipay.aop.api.response.AlipayCommerceEcTransAccountTransferResponse import (
  338. AlipayCommerceEcTransAccountTransferResponse,
  339. )
  340. from alipay.aop.api.domain.TransParticipant import (
  341. TransParticipant,
  342. )
  343. from alipay.aop.api.domain.BankCardExtInfoDTO import (
  344. BankCardExtInfoDTO,
  345. )
  346. # 检查资金专户是否存在
  347. account = await AccountCRUD(auth).get_by_account_book_id(data.account_book_id)
  348. if not account:
  349. raise CustomException(msg="资金账户不存在")
  350. if account.tenant_id != tenant_id:
  351. raise CustomException(msg="无权限操作")
  352. if data.enterprise_id and account.enterprise_id != data.enterprise_id:
  353. raise CustomException(msg="参数错误")
  354. if not data.order_title and account.enterprise_id:
  355. enterprise = await EnterpriseCRUD(auth).get_by_enterprise_id(account.enterprise_id)
  356. if not enterprise:
  357. raise CustomException(msg="资金账户所属企业不存在")
  358. data.order_title = f"来自{enterprise.name}转账"
  359. model = AlipayCommerceEcTransAccountTransferModel()
  360. model.enterprise_id = account.enterprise_id
  361. model.account_book_id = account.account_book_id
  362. model.out_biz_no = get_snowflake_id_str(tenant_id)
  363. # 转账总金额,单位为元,精确到小数点后两位
  364. model.amount = str(data.amount)
  365. model.order_title = data.order_title
  366. payee_info = TransParticipant()
  367. payee_info.identity_type = data.payee_info.identity_type
  368. payee_info.name = data.payee_info.name
  369. payee_info.identity = data.payee_info.identity
  370. if data.payee_info.bankcard_ext_info:
  371. payee_info.bankcard_ext_info = BankCardExtInfoDTO.from_alipay_dict(
  372. data.payee_info.bankcard_ext_info.model_dump(exclude_none=True)
  373. )
  374. model.payee_info = payee_info
  375. request = AlipayCommerceEcTransAccountTransferRequest()
  376. request.biz_model = model
  377. client = AlipayClient.get_client()
  378. response = client.execute(request)
  379. if not response:
  380. raise CustomException(msg="转账失败: 无响应")
  381. result = AlipayCommerceEcTransAccountTransferResponse()
  382. result.parse_response_content(response)
  383. if not result.is_success():
  384. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  385. raise CustomException(msg=f"转账失败: {result.sub_msg or result.msg or result.code}")
  386. transfer_crud = TransferCRUD(auth)
  387. transfer_data = {
  388. "enterprise_id": model.enterprise_id,
  389. "out_biz_no": model.out_biz_no,
  390. "account_book_id": model.account_book_id,
  391. "amount": model.amount,
  392. "order_title": model.order_title,
  393. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  394. "status": result.status,
  395. "order_no": result.order_no,
  396. "fund_order_id": result.fund_order_id,
  397. }
  398. await transfer_crud.create(transfer_data)
  399. return TenantTransferResponse(
  400. status=result.status,
  401. order_no=result.order_no,
  402. fund_order_id=result.fund_order_id,
  403. )
  404. @classmethod
  405. async def withdraw_service(
  406. cls,
  407. auth: AuthSchema,
  408. data: AccountWithdrawSchema
  409. ) -> AccountOperationOutSchema:
  410. """
  411. 资金专户提现
  412. 调用: alipay.commerce.ec.trans.account.withdraw
  413. 接口文档: https://opendocs.alipay.com/pre-open/d651859b_alipay.commerce.ec.trans.account.withdraw
  414. 参数说明:
  415. - enterprise_id: 企业ID
  416. - account_book_id: 资金专户号
  417. - amount: 提现金额
  418. - out_biz_no: 商家侧订单号(唯一)
  419. """
  420. from alipay.aop.api.request.AlipayCommerceEcTransAccountWithdrawRequest import (
  421. AlipayCommerceEcTransAccountWithdrawRequest,
  422. )
  423. from alipay.aop.api.domain.AlipayCommerceEcTransAccountWithdrawModel import (
  424. AlipayCommerceEcTransAccountWithdrawModel,
  425. )
  426. from alipay.aop.api.response.AlipayCommerceEcTransAccountWithdrawResponse import (
  427. AlipayCommerceEcTransAccountWithdrawResponse,
  428. )
  429. crud = AccountCRUD(auth)
  430. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  431. if not enterprise:
  432. raise CustomException(msg="企业不存在")
  433. model = AlipayCommerceEcTransAccountWithdrawModel()
  434. model.enterprise_id = enterprise.enterprise_id
  435. model.account_book_id = data.account_book_id
  436. model.amount = str(data.amount)
  437. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  438. request = AlipayCommerceEcTransAccountWithdrawRequest()
  439. request.biz_model = model
  440. client = AlipayClient.get_client()
  441. response = client.execute(request)
  442. if not response:
  443. raise CustomException(msg="提现失败: 无响应")
  444. result = AlipayCommerceEcTransAccountWithdrawResponse()
  445. result.parse_response_content(response)
  446. if not result.is_success():
  447. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  448. raise CustomException(msg=f"提现失败: {result.msg}")
  449. withdraw_crud = WithdrawCRUD(auth)
  450. withdraw_data = {
  451. "enterprise_id": data.enterprise_id,
  452. "out_biz_no": model.out_biz_no,
  453. "account_book_id": data.account_book_id,
  454. "amount": data.amount,
  455. # 专户提现到余额户是同步操作,要么执行成功,要么执行异常,
  456. # 出参status设计多余,遵循规范使用业务码区分成功与失败
  457. "status": WithdrawStatusEnum.SUCCESS.value,
  458. "order_no": result.order_no,
  459. }
  460. await withdraw_crud.create(withdraw_data)
  461. log.info(f"资金专户提现发起成功: 企业: {data.enterprise_id}, 金额: {data.amount}")
  462. return AccountOperationOutSchema(
  463. enterprise_id=data.enterprise_id,
  464. account_book_id=data.account_book_id,
  465. )
  466. @classmethod
  467. async def query_account_service(
  468. cls,
  469. auth: AuthSchema,
  470. data: AccountQuerySchema
  471. ) -> list[Any]:
  472. """
  473. 查询资金专户(调用支付宝接口)
  474. 调用: alipay.commerce.ec.trans.account.query
  475. """
  476. from alipay.aop.api.request.AlipayCommerceEcTransAccountQueryRequest import (
  477. AlipayCommerceEcTransAccountQueryRequest,
  478. )
  479. from alipay.aop.api.domain.AlipayCommerceEcTransAccountQueryModel import (
  480. AlipayCommerceEcTransAccountQueryModel,
  481. )
  482. from alipay.aop.api.response.AlipayCommerceEcTransAccountQueryResponse import (
  483. AlipayCommerceEcTransAccountQueryResponse,
  484. )
  485. from alipay.aop.api.domain.FundAccountApiDTO import (
  486. FundAccountApiDTO,
  487. )
  488. model = AlipayCommerceEcTransAccountQueryModel()
  489. model.enterprise_id = data.enterprise_id
  490. request = AlipayCommerceEcTransAccountQueryRequest()
  491. request.biz_model = model
  492. client = AlipayClient.get_client()
  493. response = client.execute(request)
  494. if not response:
  495. raise CustomException(msg="查询资金专户失败: 无响应")
  496. result = AlipayCommerceEcTransAccountQueryResponse()
  497. result.parse_response_content(response)
  498. if not result.is_success():
  499. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  500. raise CustomException(msg=f"查询资金专户失败: {result.msg}")
  501. collect = []
  502. for v in list(result.account_list or []):
  503. if not hasattr(v, "account_book_id"):
  504. continue
  505. if not hasattr(v, "scene") or v.scene != "B2B_TRANS":
  506. continue
  507. account = FundAccountApiDTO.to_alipay_dict(v)
  508. collect.append(account)
  509. return collect
  510. @classmethod
  511. async def transfer_detail_service(
  512. cls,
  513. auth: AuthSchema,
  514. out_biz_no: str
  515. ) -> TransferOutSchema:
  516. """
  517. 查询转账记录详情
  518. """
  519. crud = TransferCRUD(auth)
  520. transfer = await crud.get_by_out_biz_no(out_biz_no)
  521. if not transfer:
  522. raise CustomException(msg="转账记录不存在")
  523. transfer_result = TransferOutSchema.model_validate(transfer)
  524. # 查询三方订单号
  525. open_transfer_crud = OpenTransferCRUD(auth)
  526. open_transfer_data = await open_transfer_crud.get(out_biz_no=transfer.out_biz_no)
  527. if open_transfer_data:
  528. transfer_result.third_biz_no = open_transfer_data.third_biz_no
  529. return transfer_result
  530. @classmethod
  531. async def transfer_list_service(
  532. cls,
  533. auth: AuthSchema,
  534. page_no: int = 1,
  535. page_size: int = 20,
  536. search: dict | None = None,
  537. ) -> dict:
  538. """
  539. 查询转账记录列表
  540. """
  541. log.info(f"查询转账记录列表: {page_no}, {page_size}, {search}")
  542. crud = TransferCRUD(auth)
  543. offset = (page_no - 1) * page_size
  544. return await crud.page(
  545. offset=offset,
  546. limit=page_size,
  547. order_by=[{"id": "desc"}],
  548. search=search or {},
  549. out_schema=TransferListOutSchema,
  550. )
  551. @classmethod
  552. async def transfer_export_service(
  553. cls,
  554. auth: AuthSchema,
  555. start_time: str,
  556. end_time: str,
  557. enterprise_id: Optional[str] = None,
  558. ) -> bytes:
  559. """
  560. 导出转账记录报表为Excel文件
  561. """
  562. log.info(f"导出转账记录报表: {start_time} -> {end_time}")
  563. crud = TransferCRUD(auth)
  564. search = {
  565. "created_time__gte": start_time,
  566. "created_time__lte": end_time,
  567. }
  568. if enterprise_id:
  569. search["enterprise_id"] = enterprise_id
  570. records = await crud.list(
  571. search=search,
  572. order_by=[{"id": "desc"}],
  573. )
  574. from app.utils.excel_util import ExcelUtil
  575. status_map = {
  576. "DEALING": "处理中",
  577. "SUCCESS": "成功",
  578. "FAIL": "失败",
  579. "REFUND": "退票",
  580. }
  581. payee_type_map = {
  582. "ALIPAY_ACCOUNT": "支付宝账户",
  583. "BANK_CARD": "银行卡",
  584. }
  585. list_data = []
  586. for i, record in enumerate(records, start=1):
  587. payee_info = record.payee_info or {}
  588. list_data.append({
  589. "序号": i,
  590. "订单号": record.out_biz_no or "",
  591. "商户订单号": record.order_no or "",
  592. "金额(元)": str(record.amount or 0),
  593. "收款方姓名": payee_info.get("name", ""),
  594. "收款方类型": payee_type_map.get(payee_info.get("identity_type", ""), ""),
  595. "状态": status_map.get(record.status, record.status),
  596. "转账标题": record.order_title or "",
  597. "创建时间": record.created_time.strftime("%Y-%m-%d %H:%M:%S") if record.created_time else "",
  598. })
  599. mapping_dict = {
  600. "序号": "序号",
  601. "订单号": "订单号",
  602. "商户订单号": "商户订单号",
  603. "金额(元)": "金额(元)",
  604. "收款方姓名": "收款方姓名",
  605. "收款方类型": "收款方类型",
  606. "状态": "状态",
  607. "转账标题": "转账标题",
  608. "创建时间": "创建时间",
  609. }
  610. return ExcelUtil.export_list2excel(list_data, mapping_dict)
  611. @classmethod
  612. async def apply_receipt_service(
  613. cls,
  614. auth: AuthSchema,
  615. redis: Redis,
  616. data: ReceiptApplySchema,
  617. ) -> str:
  618. """
  619. 申请转账业务回单
  620. 调用: alipay.commerce.ec.trans.receipt.apply
  621. 参数:
  622. - enterprise_id: 企业ID
  623. - order_no: 支付宝转账单号
  624. 返回: file_id
  625. """
  626. from app.core.redis_crud import RedisCURD
  627. redis_crud = RedisCURD(redis)
  628. cache_key = f"receipt:{data.enterprise_id}:{data.order_no}"
  629. cached_file_id = await redis_crud.get(cache_key)
  630. if cached_file_id:
  631. log.info(f"使用缓存的 file_id: {cached_file_id}")
  632. return cached_file_id
  633. crud = EnterpriseCRUD(auth)
  634. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  635. if not enterprise:
  636. raise CustomException(msg="企业不存在")
  637. from alipay.aop.api.request.AlipayCommerceEcTransReceiptApplyRequest import (
  638. AlipayCommerceEcTransReceiptApplyRequest,
  639. )
  640. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptApplyModel import (
  641. AlipayCommerceEcTransReceiptApplyModel,
  642. )
  643. from alipay.aop.api.response.AlipayCommerceEcTransReceiptApplyResponse import (
  644. AlipayCommerceEcTransReceiptApplyResponse,
  645. )
  646. model = AlipayCommerceEcTransReceiptApplyModel()
  647. model.enterprise_id = data.enterprise_id
  648. model.order_no = data.order_no
  649. request = AlipayCommerceEcTransReceiptApplyRequest()
  650. request.biz_model = model
  651. client = AlipayClient.get_client()
  652. response = client.execute(request)
  653. if not response:
  654. raise CustomException(msg="申请回单失败: 无响应")
  655. result = AlipayCommerceEcTransReceiptApplyResponse()
  656. result.parse_response_content(response)
  657. if not result.is_success():
  658. # 清除缓存
  659. await redis_crud.delete(cache_key)
  660. raise CustomException(msg=f"申请回单失败: {result.msg}")
  661. file_id = str(result.file_id)
  662. await redis_crud.set(cache_key, file_id, expire=172800)
  663. log.info(f"申请回单成功: order_no={data.order_no}, file_id={file_id}")
  664. return file_id
  665. @classmethod
  666. async def query_receipt_service(cls, enterprise_id: str, file_id: str) -> dict:
  667. """
  668. 查询回单状态
  669. 调用: alipay.commerce.ec.trans.receipt.query
  670. 参数:
  671. - file_id: 文件申请号
  672. 返回: {file_id, status, download_url, error_message}
  673. """
  674. from alipay.aop.api.request.AlipayCommerceEcTransReceiptQueryRequest import (
  675. AlipayCommerceEcTransReceiptQueryRequest,
  676. )
  677. from alipay.aop.api.response.AlipayCommerceEcTransReceiptQueryResponse import (
  678. AlipayCommerceEcTransReceiptQueryResponse,
  679. )
  680. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptQueryModel import (
  681. AlipayCommerceEcTransReceiptQueryModel,
  682. )
  683. model = AlipayCommerceEcTransReceiptQueryModel()
  684. model.enterprise_id = enterprise_id
  685. model.file_id = file_id
  686. request = AlipayCommerceEcTransReceiptQueryRequest()
  687. request.biz_model = model
  688. client = AlipayClient.get_client()
  689. response = client.execute(request)
  690. if not response:
  691. raise CustomException(msg="查询回单失败: 无响应")
  692. result = AlipayCommerceEcTransReceiptQueryResponse()
  693. result.parse_response_content(response)
  694. if not result.is_success():
  695. raise CustomException(msg=f"查询回单失败: {result.msg}")
  696. data = {
  697. "file_id": file_id,
  698. "status": result.status,
  699. "download_url": result.download_url,
  700. "error_message": result.error_message,
  701. }
  702. return data
  703. @classmethod
  704. async def transfer_sync_status_service(
  705. cls,
  706. auth: AuthSchema,
  707. data: "TransferSyncStatusSchema",
  708. ) -> dict:
  709. """
  710. 手动同步转账状态(管理员补录)
  711. 用于修复因通知丢失而卡在 DEALING 的转账记录
  712. """
  713. from app.plugin.module_payment.account.crud import TransferCRUD
  714. from app.plugin.module_payment.account.schema import TransferSyncStatusSchema
  715. crud = TransferCRUD(auth)
  716. transfer = await crud.get_by_out_biz_no(data.out_biz_no)
  717. if not transfer:
  718. raise CustomException(msg=f"转账记录不存在: {data.out_biz_no}")
  719. if transfer.status != "DEALING" and data.status == "SUCCESS":
  720. raise CustomException(msg=f"转账记录当前状态为 {transfer.status},无需同步")
  721. update_data = {"status": data.status}
  722. if data.error_code:
  723. update_data["error_code"] = data.error_code
  724. if data.error_msg:
  725. update_data["error_msg"] = data.error_msg
  726. for key, value in update_data.items():
  727. if hasattr(transfer, key):
  728. setattr(transfer, key, value)
  729. await auth.db.flush()
  730. await auth.db.refresh(transfer)
  731. log.info(f"手动同步转账状态成功: out_biz_no={data.out_biz_no}, {transfer.status}")
  732. return {
  733. "out_biz_no": transfer.out_biz_no,
  734. "status": transfer.status,
  735. "error_code": transfer.error_code,
  736. "error_msg": transfer.error_msg,
  737. }
  738. @classmethod
  739. async def transfer_sync_all_service(
  740. cls,
  741. auth: AuthSchema,
  742. ) -> dict:
  743. """
  744. 全量同步转账状态
  745. 尝试调 fund.trans.common.query,如无权限则降级为列出 DEALING 记录供手动同步
  746. """
  747. from sqlalchemy import select
  748. from app.plugin.module_payment.account.model import TransferModel
  749. from app.plugin.module_payment.account.enums import TransferStatusEnum
  750. stmt = select(TransferModel).where(
  751. TransferModel.out_biz_no.isnot(None),
  752. ).order_by(TransferModel.id.asc())
  753. result = await auth.db.execute(stmt)
  754. all_transfers = result.scalars().all()
  755. synced = 0
  756. errors = 0
  757. details = []
  758. _has_permission = True
  759. for transfer in all_transfers:
  760. out_biz_no = transfer.out_biz_no
  761. eid = transfer.enterprise_id
  762. if not out_biz_no or not eid:
  763. continue
  764. try:
  765. result = await cls._sync_transfer_detail(auth, out_biz_no, eid)
  766. if result is False:
  767. # 两个方案都失败了(无权限),停止全量同步
  768. _has_permission = False
  769. break
  770. if isinstance(result, str):
  771. synced += 1
  772. details.append({"out_biz_no": out_biz_no, "old_status": transfer.status, "new_status": result})
  773. else:
  774. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "action": "no_change"})
  775. except Exception as e:
  776. errors += 1
  777. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "error": str(e)})
  778. log.warning(f"全量同步 - 查询失败: out_biz_no={out_biz_no}, err={e}")
  779. if not _has_permission:
  780. dealing = [t for t in all_transfers if t.status == TransferStatusEnum.DEALING.value]
  781. return {
  782. "total": len(all_transfers),
  783. "synced": synced,
  784. "no_permission": True,
  785. "dealing_count": len(dealing),
  786. "details": [{"out_biz_no": t.out_biz_no, "status": t.status} for t in dealing],
  787. "note": "无法通过支付宝 API 查询转账状态,请在开放平台开通 alipay.fund.trans.common.query 权限,或逐个使用 sync-status 手动补录",
  788. }
  789. if synced > 0:
  790. await auth.db.flush()
  791. return {
  792. "total": len(all_transfers),
  793. "synced": synced,
  794. "errors": errors,
  795. "details": details,
  796. }
  797. @classmethod
  798. async def _sync_transfer_detail(
  799. cls,
  800. auth: AuthSchema,
  801. out_biz_no: str,
  802. enterprise_id: str,
  803. ) -> str | bool | None:
  804. """查询单笔转账详情并更新本地记录
  805. 优先调 fund.trans.common.query,无权限时改用 consume.detail.query(用 order_no 当 pay_no 查)
  806. 返回: 新状态str / False(无权限) / None(失败/无变化)
  807. """
  808. from sqlalchemy import select, update as sa_update
  809. from app.plugin.module_payment.account.model import TransferModel
  810. from app.core.alipay import AlipayClient
  811. # 先查本地记录
  812. tf_stmt = select(TransferModel).where(TransferModel.out_biz_no == out_biz_no)
  813. tf_result = await auth.db.execute(tf_stmt)
  814. local_transfer = tf_result.scalar_one_or_none()
  815. # — 方案A: fund.trans.common.query —
  816. try:
  817. from alipay.aop.api.request.AlipayFundTransCommonQueryRequest import (
  818. AlipayFundTransCommonQueryRequest,
  819. )
  820. from alipay.aop.api.domain.AlipayFundTransCommonQueryModel import (
  821. AlipayFundTransCommonQueryModel,
  822. )
  823. from alipay.aop.api.response.AlipayFundTransCommonQueryResponse import (
  824. AlipayFundTransCommonQueryResponse,
  825. )
  826. model = AlipayFundTransCommonQueryModel()
  827. model.out_biz_no = out_biz_no
  828. model.product_code = "TRANS_ACCOUNT_NO_PWD"
  829. model.biz_scene = "DIRECT_TRANSFER"
  830. request = AlipayFundTransCommonQueryRequest()
  831. request.biz_model = model
  832. client = AlipayClient.get_client()
  833. response = client.execute(request)
  834. if response:
  835. result = AlipayFundTransCommonQueryResponse()
  836. result.parse_response_content(response)
  837. if result.is_success():
  838. alipay_status = getattr(result, 'status', None)
  839. if alipay_status and alipay_status != "DEALING":
  840. return await cls._apply_transfer_update(auth, out_biz_no, result, alipay_status)
  841. return None
  842. sub_msg = getattr(result, 'sub_msg', '') or ''
  843. if '权限' not in sub_msg and 'NO_PERMISSION' not in sub_msg:
  844. return None
  845. # 权限不足,继续方案B
  846. except ImportError:
  847. pass
  848. # — 方案B: consume.detail.query(用 order_no 当 pay_no 查) —
  849. order_no = local_transfer.order_no if local_transfer else None
  850. if not order_no:
  851. log.warning(f"无 order_no 可用于查询: out_biz_no={out_biz_no}")
  852. return False
  853. try:
  854. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  855. AlipayCommerceEcConsumeDetailQueryRequest,
  856. )
  857. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  858. AlipayCommerceEcConsumeDetailQueryModel,
  859. )
  860. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  861. AlipayCommerceEcConsumeDetailQueryResponse,
  862. )
  863. model = AlipayCommerceEcConsumeDetailQueryModel()
  864. model.pay_no = order_no
  865. model.enterprise_id = enterprise_id
  866. request = AlipayCommerceEcConsumeDetailQueryRequest()
  867. request.biz_model = model
  868. client = AlipayClient.get_client()
  869. response = client.execute(request)
  870. if not response:
  871. return False
  872. result = AlipayCommerceEcConsumeDetailQueryResponse()
  873. result.parse_response_content(response)
  874. if not result.is_success():
  875. sub_code = getattr(result, 'sub_code', '') or ''
  876. sub_msg = getattr(result, 'sub_msg', '') or ''
  877. # 权限不足
  878. if '权限' in sub_msg or 'NO_PERMISSION' in sub_code:
  879. return False
  880. log.warning(f"consume.detail.query 查无记录: out_biz_no={out_biz_no}, err={sub_msg}")
  881. return None
  882. consume_info = getattr(result, 'consume_info', None)
  883. if not consume_info:
  884. return None
  885. consume_type = getattr(consume_info, 'consume_type', '')
  886. if consume_type != "TRANSFER":
  887. return None
  888. notify_reason = getattr(consume_info, 'notify_reason', '') or ''
  889. if 'SUCCESS' in notify_reason.upper():
  890. new_status = "SUCCESS"
  891. elif 'FAIL' in notify_reason.upper():
  892. new_status = "FAIL"
  893. else:
  894. return None
  895. update_data = {"status": new_status}
  896. pay_no = getattr(consume_info, 'pay_no', None)
  897. if pay_no and pay_no != order_no:
  898. update_data["order_no"] = pay_no
  899. upd = sa_update(TransferModel).where(
  900. TransferModel.out_biz_no == out_biz_no
  901. ).values(**update_data)
  902. await auth.db.execute(upd)
  903. log.info(f"转账同步(consume详情) - out_biz_no={out_biz_no}, status={new_status}")
  904. return new_status
  905. except ImportError:
  906. log.warning("consume.detail.query SDK 不可用")
  907. return False
  908. except Exception as e:
  909. log.warning(f"consume.detail.query 异常: out_biz_no={out_biz_no}, err={e}")
  910. return False
  911. @classmethod
  912. async def _apply_transfer_update(
  913. cls,
  914. auth: AuthSchema,
  915. out_biz_no: str,
  916. result: object,
  917. alipay_status: str,
  918. ) -> str | None:
  919. """根据 fund.trans.common.query 结果更新本地记录"""
  920. from sqlalchemy import update as sa_update
  921. from app.plugin.module_payment.account.model import TransferModel
  922. update_data = {"status": alipay_status}
  923. order_no = getattr(result, 'order_id', None)
  924. pay_fund_order_id = getattr(result, 'pay_fund_order_id', None)
  925. trans_amount = getattr(result, 'trans_amount', None)
  926. error_code = getattr(result, 'error_code', None)
  927. fail_reason = getattr(result, 'fail_reason', None)
  928. if order_no:
  929. update_data["order_no"] = order_no
  930. if pay_fund_order_id:
  931. update_data["fund_order_id"] = pay_fund_order_id
  932. if trans_amount:
  933. update_data["amount"] = Decimal(str(trans_amount))
  934. if error_code:
  935. update_data["error_code"] = error_code
  936. if fail_reason:
  937. update_data["error_msg"] = fail_reason
  938. if update_data.get("status") != "DEALING":
  939. upd = sa_update(TransferModel).where(
  940. TransferModel.out_biz_no == out_biz_no
  941. ).values(**update_data)
  942. await auth.db.execute(upd)
  943. log.info(f"转账详情同步 - out_biz_no={out_biz_no}, status={alipay_status}")
  944. return alipay_status
  945. return None
  946. @classmethod
  947. async def update_transfer_status_service(
  948. cls,
  949. auth: AuthSchema,
  950. order_no: str,
  951. status: str,
  952. ext_info: dict = {}
  953. ) -> None:
  954. """
  955. 更新转账状态(由通知处理器调用)
  956. """
  957. crud = TransferCRUD(auth)
  958. transfer = await crud.get_by_order_no(order_no)
  959. if not transfer:
  960. log.warning(f"转账记录不存在: {order_no}")
  961. return
  962. update_data = {}
  963. update_data["status"] = status
  964. if ext_info:
  965. update_data["ext_info"] = ext_info
  966. await crud.update_by_order_no(order_no, update_data)
  967. @classmethod
  968. async def update_deposit_status_service(
  969. cls,
  970. auth: AuthSchema,
  971. out_biz_no: str,
  972. status: str,
  973. ) -> None:
  974. """
  975. 更新充值状态(由通知处理器调用)
  976. """
  977. crud = DepositCRUD(auth)
  978. deposit = await crud.get_by_out_biz_no(out_biz_no)
  979. if not deposit:
  980. log.warning(f"充值记录不存在: {out_biz_no}")
  981. return
  982. update_data = {"status": status}
  983. await crud.update_by_out_biz_no(out_biz_no, update_data)
  984. @classmethod
  985. async def update_withdraw_status_service(
  986. cls,
  987. auth: AuthSchema,
  988. out_biz_no: str,
  989. status: str,
  990. error_code: str | None = None,
  991. error_msg: str | None = None,
  992. ) -> None:
  993. """
  994. 更新提现状态(由通知处理器调用)
  995. """
  996. crud = WithdrawCRUD(auth)
  997. withdraw = await crud.get_by_out_biz_no(out_biz_no)
  998. if not withdraw:
  999. log.warning(f"提现记录不存在: {out_biz_no}")
  1000. return
  1001. update_data = {"status": status}
  1002. if error_code:
  1003. update_data["error_code"] = error_code
  1004. if error_msg:
  1005. update_data["error_msg"] = error_msg
  1006. await crud.update_by_out_biz_no(out_biz_no, update_data)
  1007. @classmethod
  1008. async def consume_detail_query_service(
  1009. cls,
  1010. auth: AuthSchema,
  1011. pay_no: str,
  1012. enterprise_id: str | None = None,
  1013. ant_shop_id: str | None = None,
  1014. query_options: list[str] | None = None,
  1015. ) -> dict:
  1016. """
  1017. 账单详情查询(✅)
  1018. 调用: alipay.commerce.ec.consume.detail.query
  1019. 用于查询企业码账单详情,支持查询关联退款、订单、票据等信息。
  1020. """
  1021. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  1022. AlipayCommerceEcConsumeDetailQueryRequest,
  1023. )
  1024. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  1025. AlipayCommerceEcConsumeDetailQueryModel,
  1026. )
  1027. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  1028. AlipayCommerceEcConsumeDetailQueryResponse,
  1029. )
  1030. model = AlipayCommerceEcConsumeDetailQueryModel()
  1031. model.pay_no = pay_no
  1032. if enterprise_id:
  1033. model.enterprise_id = enterprise_id
  1034. if ant_shop_id:
  1035. model.ant_shop_id = ant_shop_id
  1036. if query_options:
  1037. model.query_options = query_options
  1038. request = AlipayCommerceEcConsumeDetailQueryRequest()
  1039. request.biz_model = model
  1040. client = AlipayClient.get_client()
  1041. response = client.execute(request)
  1042. if not response:
  1043. raise CustomException(msg="账单详情查询失败: 无响应")
  1044. result = AlipayCommerceEcConsumeDetailQueryResponse()
  1045. result.parse_response_content(response)
  1046. if not result.is_success():
  1047. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  1048. raise CustomException(msg=f"账单详情查询失败: {result.msg}")
  1049. consume_info = result.consume_info
  1050. if not consume_info:
  1051. raise CustomException(msg="账单详情查询失败: 无账单信息")
  1052. return {
  1053. "account_id": consume_info.account_id,
  1054. "pay_no": consume_info.pay_no,
  1055. "consume_type": consume_info.consume_type,
  1056. "gmt_biz_create": consume_info.gmt_biz_create,
  1057. "consume_biz_type": consume_info.consume_biz_type,
  1058. "consume_amount": consume_info.consume_amount,
  1059. "order_complete_label": consume_info.order_complete_label,
  1060. "refund_status": consume_info.refund_status,
  1061. "refund_amount": consume_info.refund_amount,
  1062. "peer_payer_card_name": consume_info.peer_payer_card_name,
  1063. "user_id": getattr(consume_info, 'user_id', None),
  1064. "open_id": getattr(consume_info, 'open_id', None),
  1065. "enterprise_id": consume_info.enterprise_id,
  1066. "employee_id": consume_info.employee_id,
  1067. "enterprise_name": getattr(consume_info, 'enterprise_name', None),
  1068. "employee_name": getattr(consume_info, 'employee_name', None),
  1069. "consume_scene_code": getattr(consume_info, 'consume_scene_code', None),
  1070. "consume_type_sub_category": getattr(consume_info, 'consume_type_sub_category', None),
  1071. "consume_title": getattr(consume_info, 'consume_title', None),
  1072. "gmt_pay": getattr(consume_info, 'gmt_pay', None),
  1073. "gmt_refund": getattr(consume_info, 'gmt_refund', None),
  1074. "pay_amount": getattr(consume_info, 'pay_amount', None),
  1075. "invoice_amount": getattr(consume_info, 'invoice_amount', None),
  1076. "peer_pay_amount": getattr(consume_info, 'peer_pay_amount', None),
  1077. "subsidy_amount": getattr(consume_info, 'subsidy_amount', None),
  1078. "ext_infos": getattr(consume_info, 'ext_infos', None),
  1079. }