service.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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. if not result.is_success():
  283. sub_code = getattr(result, 'sub_code', '') or ''
  284. sub_msg = getattr(result, 'sub_msg', '') or ''
  285. # 优先用 sub_code 匹配
  286. hint = _TRANSFER_ERROR_HINTS.get(sub_code)
  287. # sub_code 无匹配时,尝试从 sub_msg 中提取错误码(支付宝部分接口sub_code返回unknown-sub-code)
  288. if not hint:
  289. for code_key, code_hint in _TRANSFER_ERROR_HINTS.items():
  290. if code_key in sub_msg:
  291. hint = code_hint
  292. break
  293. hint = hint or sub_msg or result.msg or "转账失败"
  294. log.error(f"支付宝接口调用失败: {result.code} - {result.msg} (sub_code={sub_code}, sub_msg={sub_msg})")
  295. raise CustomException(msg=f"转账失败: {hint}")
  296. transfer_crud = TransferCRUD(auth)
  297. transfer_data = {
  298. "enterprise_id": model.enterprise_id,
  299. "out_biz_no": model.out_biz_no,
  300. "account_book_id": model.account_book_id,
  301. "amount": model.amount,
  302. "order_title": model.order_title,
  303. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  304. "status": result.status,
  305. "order_no": result.order_no,
  306. "fund_order_id": result.fund_order_id,
  307. }
  308. await transfer_crud.create(transfer_data)
  309. return AccountTransferOutSchema(
  310. status=result.status,
  311. order_no=result.order_no,
  312. fund_order_id=result.fund_order_id,
  313. out_biz_no=model.out_biz_no,
  314. )
  315. @classmethod
  316. async def tenant_transfer_service(
  317. cls,
  318. auth: AuthSchema,
  319. tenant_id: int,
  320. data: TenantTransferCreate,
  321. request_ip: str,
  322. api_key_id: int | None = None,
  323. ) -> TenantTransferResponse:
  324. """
  325. 租户API转账(通过API Key认证)
  326. 调用: alipay.commerce.ec.trans.account.transfer
  327. """
  328. from alipay.aop.api.request.AlipayCommerceEcTransAccountTransferRequest import (
  329. AlipayCommerceEcTransAccountTransferRequest,
  330. )
  331. from alipay.aop.api.domain.AlipayCommerceEcTransAccountTransferModel import (
  332. AlipayCommerceEcTransAccountTransferModel,
  333. )
  334. from alipay.aop.api.response.AlipayCommerceEcTransAccountTransferResponse import (
  335. AlipayCommerceEcTransAccountTransferResponse,
  336. )
  337. from alipay.aop.api.domain.TransParticipant import (
  338. TransParticipant,
  339. )
  340. from alipay.aop.api.domain.BankCardExtInfoDTO import (
  341. BankCardExtInfoDTO,
  342. )
  343. # 检查资金专户是否存在
  344. account = await AccountCRUD(auth).get_by_account_book_id(data.account_book_id)
  345. if not account:
  346. raise CustomException(msg="资金账户不存在")
  347. if account.tenant_id != tenant_id:
  348. raise CustomException(msg="无权限操作")
  349. if data.enterprise_id and account.enterprise_id != data.enterprise_id:
  350. raise CustomException(msg="参数错误")
  351. if not data.order_title and account.enterprise_id:
  352. enterprise = await EnterpriseCRUD(auth).get_by_enterprise_id(account.enterprise_id)
  353. if not enterprise:
  354. raise CustomException(msg="资金账户所属企业不存在")
  355. data.order_title = f"来自{enterprise.name}转账"
  356. model = AlipayCommerceEcTransAccountTransferModel()
  357. model.enterprise_id = account.enterprise_id
  358. model.account_book_id = account.account_book_id
  359. model.out_biz_no = get_snowflake_id_str(tenant_id)
  360. # 转账总金额,单位为元,精确到小数点后两位
  361. model.amount = str(data.amount)
  362. model.order_title = data.order_title
  363. payee_info = TransParticipant()
  364. payee_info.identity_type = data.payee_info.identity_type
  365. payee_info.name = data.payee_info.name
  366. payee_info.identity = data.payee_info.identity
  367. if data.payee_info.bankcard_ext_info:
  368. payee_info.bankcard_ext_info = BankCardExtInfoDTO.from_alipay_dict(
  369. data.payee_info.bankcard_ext_info.model_dump(exclude_none=True)
  370. )
  371. model.payee_info = payee_info
  372. request = AlipayCommerceEcTransAccountTransferRequest()
  373. request.biz_model = model
  374. client = AlipayClient.get_client()
  375. response = client.execute(request)
  376. if not response:
  377. raise CustomException(msg="转账失败: 无响应")
  378. result = AlipayCommerceEcTransAccountTransferResponse()
  379. result.parse_response_content(response)
  380. if not result.is_success():
  381. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  382. raise CustomException(msg=f"转账失败: {result.sub_msg or result.msg or result.code}")
  383. transfer_crud = TransferCRUD(auth)
  384. transfer_data = {
  385. "enterprise_id": model.enterprise_id,
  386. "out_biz_no": model.out_biz_no,
  387. "account_book_id": model.account_book_id,
  388. "amount": model.amount,
  389. "order_title": model.order_title,
  390. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  391. "status": result.status,
  392. "order_no": result.order_no,
  393. "fund_order_id": result.fund_order_id,
  394. }
  395. await transfer_crud.create(transfer_data)
  396. return TenantTransferResponse(
  397. status=result.status,
  398. order_no=result.order_no,
  399. fund_order_id=result.fund_order_id,
  400. )
  401. @classmethod
  402. async def withdraw_service(
  403. cls,
  404. auth: AuthSchema,
  405. data: AccountWithdrawSchema
  406. ) -> AccountOperationOutSchema:
  407. """
  408. 资金专户提现
  409. 调用: alipay.commerce.ec.trans.account.withdraw
  410. 接口文档: https://opendocs.alipay.com/pre-open/d651859b_alipay.commerce.ec.trans.account.withdraw
  411. 参数说明:
  412. - enterprise_id: 企业ID
  413. - account_book_id: 资金专户号
  414. - amount: 提现金额
  415. - out_biz_no: 商家侧订单号(唯一)
  416. """
  417. from alipay.aop.api.request.AlipayCommerceEcTransAccountWithdrawRequest import (
  418. AlipayCommerceEcTransAccountWithdrawRequest,
  419. )
  420. from alipay.aop.api.domain.AlipayCommerceEcTransAccountWithdrawModel import (
  421. AlipayCommerceEcTransAccountWithdrawModel,
  422. )
  423. from alipay.aop.api.response.AlipayCommerceEcTransAccountWithdrawResponse import (
  424. AlipayCommerceEcTransAccountWithdrawResponse,
  425. )
  426. crud = AccountCRUD(auth)
  427. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  428. if not enterprise:
  429. raise CustomException(msg="企业不存在")
  430. model = AlipayCommerceEcTransAccountWithdrawModel()
  431. model.enterprise_id = enterprise.enterprise_id
  432. model.account_book_id = data.account_book_id
  433. model.amount = str(data.amount)
  434. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  435. request = AlipayCommerceEcTransAccountWithdrawRequest()
  436. request.biz_model = model
  437. client = AlipayClient.get_client()
  438. response = client.execute(request)
  439. if not response:
  440. raise CustomException(msg="提现失败: 无响应")
  441. result = AlipayCommerceEcTransAccountWithdrawResponse()
  442. result.parse_response_content(response)
  443. if not result.is_success():
  444. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  445. raise CustomException(msg=f"提现失败: {result.msg}")
  446. withdraw_crud = WithdrawCRUD(auth)
  447. withdraw_data = {
  448. "enterprise_id": data.enterprise_id,
  449. "out_biz_no": model.out_biz_no,
  450. "account_book_id": data.account_book_id,
  451. "amount": data.amount,
  452. # 专户提现到余额户是同步操作,要么执行成功,要么执行异常,
  453. # 出参status设计多余,遵循规范使用业务码区分成功与失败
  454. "status": WithdrawStatusEnum.SUCCESS.value,
  455. "order_no": result.order_no,
  456. }
  457. await withdraw_crud.create(withdraw_data)
  458. log.info(f"资金专户提现发起成功: 企业: {data.enterprise_id}, 金额: {data.amount}")
  459. return AccountOperationOutSchema(
  460. enterprise_id=data.enterprise_id,
  461. account_book_id=data.account_book_id,
  462. )
  463. @classmethod
  464. async def query_account_service(
  465. cls,
  466. auth: AuthSchema,
  467. data: AccountQuerySchema
  468. ) -> list[Any]:
  469. """
  470. 查询资金专户(调用支付宝接口)
  471. 调用: alipay.commerce.ec.trans.account.query
  472. """
  473. from alipay.aop.api.request.AlipayCommerceEcTransAccountQueryRequest import (
  474. AlipayCommerceEcTransAccountQueryRequest,
  475. )
  476. from alipay.aop.api.domain.AlipayCommerceEcTransAccountQueryModel import (
  477. AlipayCommerceEcTransAccountQueryModel,
  478. )
  479. from alipay.aop.api.response.AlipayCommerceEcTransAccountQueryResponse import (
  480. AlipayCommerceEcTransAccountQueryResponse,
  481. )
  482. from alipay.aop.api.domain.FundAccountApiDTO import (
  483. FundAccountApiDTO,
  484. )
  485. model = AlipayCommerceEcTransAccountQueryModel()
  486. model.enterprise_id = data.enterprise_id
  487. request = AlipayCommerceEcTransAccountQueryRequest()
  488. request.biz_model = model
  489. client = AlipayClient.get_client()
  490. response = client.execute(request)
  491. if not response:
  492. raise CustomException(msg="查询资金专户失败: 无响应")
  493. result = AlipayCommerceEcTransAccountQueryResponse()
  494. result.parse_response_content(response)
  495. if not result.is_success():
  496. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  497. raise CustomException(msg=f"查询资金专户失败: {result.msg}")
  498. collect = []
  499. for v in list(result.account_list or []):
  500. if not hasattr(v, "account_book_id"):
  501. continue
  502. if not hasattr(v, "scene") or v.scene != "B2B_TRANS":
  503. continue
  504. account = FundAccountApiDTO.to_alipay_dict(v)
  505. collect.append(account)
  506. return collect
  507. @classmethod
  508. async def transfer_detail_service(
  509. cls,
  510. auth: AuthSchema,
  511. out_biz_no: str
  512. ) -> TransferOutSchema:
  513. """
  514. 查询转账记录详情
  515. """
  516. crud = TransferCRUD(auth)
  517. transfer = await crud.get_by_out_biz_no(out_biz_no)
  518. if not transfer:
  519. raise CustomException(msg="转账记录不存在")
  520. transfer_result = TransferOutSchema.model_validate(transfer)
  521. # 查询三方订单号
  522. open_transfer_crud = OpenTransferCRUD(auth)
  523. open_transfer_data = await open_transfer_crud.get(out_biz_no=transfer.out_biz_no)
  524. if open_transfer_data:
  525. transfer_result.third_biz_no = open_transfer_data.third_biz_no
  526. return transfer_result
  527. @classmethod
  528. async def transfer_list_service(
  529. cls,
  530. auth: AuthSchema,
  531. page_no: int = 1,
  532. page_size: int = 20,
  533. search: dict | None = None,
  534. ) -> dict:
  535. """
  536. 查询转账记录列表
  537. """
  538. log.info(f"查询转账记录列表: {page_no}, {page_size}, {search}")
  539. crud = TransferCRUD(auth)
  540. offset = (page_no - 1) * page_size
  541. return await crud.page(
  542. offset=offset,
  543. limit=page_size,
  544. order_by=[{"id": "desc"}],
  545. search=search or {},
  546. out_schema=TransferListOutSchema,
  547. )
  548. @classmethod
  549. async def transfer_export_service(
  550. cls,
  551. auth: AuthSchema,
  552. start_time: str,
  553. end_time: str,
  554. enterprise_id: Optional[str] = None,
  555. ) -> bytes:
  556. """
  557. 导出转账记录报表为Excel文件
  558. """
  559. log.info(f"导出转账记录报表: {start_time} -> {end_time}")
  560. crud = TransferCRUD(auth)
  561. search = {
  562. "created_time__gte": start_time,
  563. "created_time__lte": end_time,
  564. }
  565. if enterprise_id:
  566. search["enterprise_id"] = enterprise_id
  567. records = await crud.list(
  568. search=search,
  569. order_by=[{"id": "desc"}],
  570. )
  571. from app.utils.excel_util import ExcelUtil
  572. status_map = {
  573. "DEALING": "处理中",
  574. "SUCCESS": "成功",
  575. "FAIL": "失败",
  576. "REFUND": "退票",
  577. }
  578. payee_type_map = {
  579. "ALIPAY_ACCOUNT": "支付宝账户",
  580. "BANK_CARD": "银行卡",
  581. }
  582. list_data = []
  583. for i, record in enumerate(records, start=1):
  584. payee_info = record.payee_info or {}
  585. list_data.append({
  586. "序号": i,
  587. "订单号": record.out_biz_no or "",
  588. "商户订单号": record.order_no or "",
  589. "金额(元)": str(record.amount or 0),
  590. "收款方姓名": payee_info.get("name", ""),
  591. "收款方类型": payee_type_map.get(payee_info.get("identity_type", ""), ""),
  592. "状态": status_map.get(record.status, record.status),
  593. "转账标题": record.order_title or "",
  594. "创建时间": record.created_time.strftime("%Y-%m-%d %H:%M:%S") if record.created_time else "",
  595. })
  596. mapping_dict = {
  597. "序号": "序号",
  598. "订单号": "订单号",
  599. "商户订单号": "商户订单号",
  600. "金额(元)": "金额(元)",
  601. "收款方姓名": "收款方姓名",
  602. "收款方类型": "收款方类型",
  603. "状态": "状态",
  604. "转账标题": "转账标题",
  605. "创建时间": "创建时间",
  606. }
  607. return ExcelUtil.export_list2excel(list_data, mapping_dict)
  608. @classmethod
  609. async def apply_receipt_service(
  610. cls,
  611. auth: AuthSchema,
  612. redis: Redis,
  613. data: ReceiptApplySchema,
  614. ) -> str:
  615. """
  616. 申请转账业务回单
  617. 调用: alipay.commerce.ec.trans.receipt.apply
  618. 参数:
  619. - enterprise_id: 企业ID
  620. - order_no: 支付宝转账单号
  621. 返回: file_id
  622. """
  623. from app.core.redis_crud import RedisCURD
  624. redis_crud = RedisCURD(redis)
  625. cache_key = f"receipt:{data.enterprise_id}:{data.order_no}"
  626. cached_file_id = await redis_crud.get(cache_key)
  627. if cached_file_id:
  628. log.info(f"使用缓存的 file_id: {cached_file_id}")
  629. return cached_file_id
  630. crud = EnterpriseCRUD(auth)
  631. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  632. if not enterprise:
  633. raise CustomException(msg="企业不存在")
  634. from alipay.aop.api.request.AlipayCommerceEcTransReceiptApplyRequest import (
  635. AlipayCommerceEcTransReceiptApplyRequest,
  636. )
  637. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptApplyModel import (
  638. AlipayCommerceEcTransReceiptApplyModel,
  639. )
  640. from alipay.aop.api.response.AlipayCommerceEcTransReceiptApplyResponse import (
  641. AlipayCommerceEcTransReceiptApplyResponse,
  642. )
  643. model = AlipayCommerceEcTransReceiptApplyModel()
  644. model.enterprise_id = data.enterprise_id
  645. model.order_no = data.order_no
  646. request = AlipayCommerceEcTransReceiptApplyRequest()
  647. request.biz_model = model
  648. client = AlipayClient.get_client()
  649. response = client.execute(request)
  650. if not response:
  651. raise CustomException(msg="申请回单失败: 无响应")
  652. result = AlipayCommerceEcTransReceiptApplyResponse()
  653. result.parse_response_content(response)
  654. if not result.is_success():
  655. # 清除缓存
  656. await redis_crud.delete(cache_key)
  657. raise CustomException(msg=f"申请回单失败: {result.msg}")
  658. file_id = str(result.file_id)
  659. await redis_crud.set(cache_key, file_id, expire=172800)
  660. log.info(f"申请回单成功: order_no={data.order_no}, file_id={file_id}")
  661. return file_id
  662. @classmethod
  663. async def query_receipt_service(cls, enterprise_id: str, file_id: str) -> dict:
  664. """
  665. 查询回单状态
  666. 调用: alipay.commerce.ec.trans.receipt.query
  667. 参数:
  668. - file_id: 文件申请号
  669. 返回: {file_id, status, download_url, error_message}
  670. """
  671. from alipay.aop.api.request.AlipayCommerceEcTransReceiptQueryRequest import (
  672. AlipayCommerceEcTransReceiptQueryRequest,
  673. )
  674. from alipay.aop.api.response.AlipayCommerceEcTransReceiptQueryResponse import (
  675. AlipayCommerceEcTransReceiptQueryResponse,
  676. )
  677. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptQueryModel import (
  678. AlipayCommerceEcTransReceiptQueryModel,
  679. )
  680. model = AlipayCommerceEcTransReceiptQueryModel()
  681. model.enterprise_id = enterprise_id
  682. model.file_id = file_id
  683. request = AlipayCommerceEcTransReceiptQueryRequest()
  684. request.biz_model = model
  685. client = AlipayClient.get_client()
  686. response = client.execute(request)
  687. if not response:
  688. raise CustomException(msg="查询回单失败: 无响应")
  689. result = AlipayCommerceEcTransReceiptQueryResponse()
  690. result.parse_response_content(response)
  691. if not result.is_success():
  692. raise CustomException(msg=f"查询回单失败: {result.msg}")
  693. data = {
  694. "file_id": file_id,
  695. "status": result.status,
  696. "download_url": result.download_url,
  697. "error_message": result.error_message,
  698. }
  699. return data
  700. @classmethod
  701. async def transfer_sync_status_service(
  702. cls,
  703. auth: AuthSchema,
  704. data: "TransferSyncStatusSchema",
  705. ) -> dict:
  706. """
  707. 手动同步转账状态(管理员补录)
  708. 用于修复因通知丢失而卡在 DEALING 的转账记录
  709. """
  710. from app.plugin.module_payment.account.crud import TransferCRUD
  711. from app.plugin.module_payment.account.schema import TransferSyncStatusSchema
  712. crud = TransferCRUD(auth)
  713. transfer = await crud.get_by_out_biz_no(data.out_biz_no)
  714. if not transfer:
  715. raise CustomException(msg=f"转账记录不存在: {data.out_biz_no}")
  716. if transfer.status != "DEALING" and data.status == "SUCCESS":
  717. raise CustomException(msg=f"转账记录当前状态为 {transfer.status},无需同步")
  718. update_data = {"status": data.status}
  719. if data.error_code:
  720. update_data["error_code"] = data.error_code
  721. if data.error_msg:
  722. update_data["error_msg"] = data.error_msg
  723. for key, value in update_data.items():
  724. if hasattr(transfer, key):
  725. setattr(transfer, key, value)
  726. await auth.db.flush()
  727. await auth.db.refresh(transfer)
  728. log.info(f"手动同步转账状态成功: out_biz_no={data.out_biz_no}, {transfer.status}")
  729. return {
  730. "out_biz_no": transfer.out_biz_no,
  731. "status": transfer.status,
  732. "error_code": transfer.error_code,
  733. "error_msg": transfer.error_msg,
  734. }
  735. @classmethod
  736. async def transfer_sync_all_service(
  737. cls,
  738. auth: AuthSchema,
  739. ) -> dict:
  740. """
  741. 全量同步转账状态
  742. 尝试调 fund.trans.common.query,如无权限则降级为列出 DEALING 记录供手动同步
  743. """
  744. from sqlalchemy import select
  745. from app.plugin.module_payment.account.model import TransferModel
  746. from app.plugin.module_payment.account.enums import TransferStatusEnum
  747. stmt = select(TransferModel).where(
  748. TransferModel.out_biz_no.isnot(None),
  749. ).order_by(TransferModel.id.asc())
  750. result = await auth.db.execute(stmt)
  751. all_transfers = result.scalars().all()
  752. synced = 0
  753. errors = 0
  754. details = []
  755. _has_permission = True
  756. for transfer in all_transfers:
  757. out_biz_no = transfer.out_biz_no
  758. eid = transfer.enterprise_id
  759. if not out_biz_no or not eid:
  760. continue
  761. try:
  762. result = await cls._sync_transfer_detail(auth, out_biz_no, eid)
  763. if result is False:
  764. # 两个方案都失败了(无权限),停止全量同步
  765. _has_permission = False
  766. break
  767. if isinstance(result, str):
  768. synced += 1
  769. details.append({"out_biz_no": out_biz_no, "old_status": transfer.status, "new_status": result})
  770. else:
  771. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "action": "no_change"})
  772. except Exception as e:
  773. errors += 1
  774. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "error": str(e)})
  775. log.warning(f"全量同步 - 查询失败: out_biz_no={out_biz_no}, err={e}")
  776. if not _has_permission:
  777. dealing = [t for t in all_transfers if t.status == TransferStatusEnum.DEALING.value]
  778. return {
  779. "total": len(all_transfers),
  780. "synced": synced,
  781. "no_permission": True,
  782. "dealing_count": len(dealing),
  783. "details": [{"out_biz_no": t.out_biz_no, "status": t.status} for t in dealing],
  784. "note": "无法通过支付宝 API 查询转账状态,请在开放平台开通 alipay.fund.trans.common.query 权限,或逐个使用 sync-status 手动补录",
  785. }
  786. if synced > 0:
  787. await auth.db.flush()
  788. return {
  789. "total": len(all_transfers),
  790. "synced": synced,
  791. "errors": errors,
  792. "details": details,
  793. }
  794. @classmethod
  795. async def _sync_transfer_detail(
  796. cls,
  797. auth: AuthSchema,
  798. out_biz_no: str,
  799. enterprise_id: str,
  800. ) -> str | bool | None:
  801. """查询单笔转账详情并更新本地记录
  802. 优先调 fund.trans.common.query,无权限时改用 consume.detail.query(用 order_no 当 pay_no 查)
  803. 返回: 新状态str / False(无权限) / None(失败/无变化)
  804. """
  805. from sqlalchemy import select, update as sa_update
  806. from app.plugin.module_payment.account.model import TransferModel
  807. from app.core.alipay import AlipayClient
  808. # 先查本地记录
  809. tf_stmt = select(TransferModel).where(TransferModel.out_biz_no == out_biz_no)
  810. tf_result = await auth.db.execute(tf_stmt)
  811. local_transfer = tf_result.scalar_one_or_none()
  812. # — 方案A: fund.trans.common.query —
  813. try:
  814. from alipay.aop.api.request.AlipayFundTransCommonQueryRequest import (
  815. AlipayFundTransCommonQueryRequest,
  816. )
  817. from alipay.aop.api.domain.AlipayFundTransCommonQueryModel import (
  818. AlipayFundTransCommonQueryModel,
  819. )
  820. from alipay.aop.api.response.AlipayFundTransCommonQueryResponse import (
  821. AlipayFundTransCommonQueryResponse,
  822. )
  823. model = AlipayFundTransCommonQueryModel()
  824. model.out_biz_no = out_biz_no
  825. model.product_code = "TRANS_ACCOUNT_NO_PWD"
  826. model.biz_scene = "DIRECT_TRANSFER"
  827. request = AlipayFundTransCommonQueryRequest()
  828. request.biz_model = model
  829. client = AlipayClient.get_client()
  830. response = client.execute(request)
  831. if response:
  832. result = AlipayFundTransCommonQueryResponse()
  833. result.parse_response_content(response)
  834. if result.is_success():
  835. alipay_status = getattr(result, 'status', None)
  836. if alipay_status and alipay_status != "DEALING":
  837. return await cls._apply_transfer_update(auth, out_biz_no, result, alipay_status)
  838. return None
  839. sub_msg = getattr(result, 'sub_msg', '') or ''
  840. if '权限' not in sub_msg and 'NO_PERMISSION' not in sub_msg:
  841. return None
  842. # 权限不足,继续方案B
  843. except ImportError:
  844. pass
  845. # — 方案B: consume.detail.query(用 order_no 当 pay_no 查) —
  846. order_no = local_transfer.order_no if local_transfer else None
  847. if not order_no:
  848. log.warning(f"无 order_no 可用于查询: out_biz_no={out_biz_no}")
  849. return False
  850. try:
  851. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  852. AlipayCommerceEcConsumeDetailQueryRequest,
  853. )
  854. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  855. AlipayCommerceEcConsumeDetailQueryModel,
  856. )
  857. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  858. AlipayCommerceEcConsumeDetailQueryResponse,
  859. )
  860. model = AlipayCommerceEcConsumeDetailQueryModel()
  861. model.pay_no = order_no
  862. model.enterprise_id = enterprise_id
  863. request = AlipayCommerceEcConsumeDetailQueryRequest()
  864. request.biz_model = model
  865. client = AlipayClient.get_client()
  866. response = client.execute(request)
  867. if not response:
  868. return False
  869. result = AlipayCommerceEcConsumeDetailQueryResponse()
  870. result.parse_response_content(response)
  871. if not result.is_success():
  872. sub_code = getattr(result, 'sub_code', '') or ''
  873. sub_msg = getattr(result, 'sub_msg', '') or ''
  874. # 权限不足
  875. if '权限' in sub_msg or 'NO_PERMISSION' in sub_code:
  876. return False
  877. log.warning(f"consume.detail.query 查无记录: out_biz_no={out_biz_no}, err={sub_msg}")
  878. return None
  879. consume_info = getattr(result, 'consume_info', None)
  880. if not consume_info:
  881. return None
  882. consume_type = getattr(consume_info, 'consume_type', '')
  883. if consume_type != "TRANSFER":
  884. return None
  885. notify_reason = getattr(consume_info, 'notify_reason', '') or ''
  886. if 'SUCCESS' in notify_reason.upper():
  887. new_status = "SUCCESS"
  888. elif 'FAIL' in notify_reason.upper():
  889. new_status = "FAIL"
  890. else:
  891. return None
  892. update_data = {"status": new_status}
  893. pay_no = getattr(consume_info, 'pay_no', None)
  894. if pay_no and pay_no != order_no:
  895. update_data["order_no"] = pay_no
  896. upd = sa_update(TransferModel).where(
  897. TransferModel.out_biz_no == out_biz_no
  898. ).values(**update_data)
  899. await auth.db.execute(upd)
  900. log.info(f"转账同步(consume详情) - out_biz_no={out_biz_no}, status={new_status}")
  901. return new_status
  902. except ImportError:
  903. log.warning("consume.detail.query SDK 不可用")
  904. return False
  905. except Exception as e:
  906. log.warning(f"consume.detail.query 异常: out_biz_no={out_biz_no}, err={e}")
  907. return False
  908. @classmethod
  909. async def _apply_transfer_update(
  910. cls,
  911. auth: AuthSchema,
  912. out_biz_no: str,
  913. result: object,
  914. alipay_status: str,
  915. ) -> str | None:
  916. """根据 fund.trans.common.query 结果更新本地记录"""
  917. from sqlalchemy import update as sa_update
  918. from app.plugin.module_payment.account.model import TransferModel
  919. update_data = {"status": alipay_status}
  920. order_no = getattr(result, 'order_id', None)
  921. pay_fund_order_id = getattr(result, 'pay_fund_order_id', None)
  922. trans_amount = getattr(result, 'trans_amount', None)
  923. error_code = getattr(result, 'error_code', None)
  924. fail_reason = getattr(result, 'fail_reason', None)
  925. if order_no:
  926. update_data["order_no"] = order_no
  927. if pay_fund_order_id:
  928. update_data["fund_order_id"] = pay_fund_order_id
  929. if trans_amount:
  930. update_data["amount"] = Decimal(str(trans_amount))
  931. if error_code:
  932. update_data["error_code"] = error_code
  933. if fail_reason:
  934. update_data["error_msg"] = fail_reason
  935. if update_data.get("status") != "DEALING":
  936. upd = sa_update(TransferModel).where(
  937. TransferModel.out_biz_no == out_biz_no
  938. ).values(**update_data)
  939. await auth.db.execute(upd)
  940. log.info(f"转账详情同步 - out_biz_no={out_biz_no}, status={alipay_status}")
  941. return alipay_status
  942. return None
  943. @classmethod
  944. async def update_transfer_status_service(
  945. cls,
  946. auth: AuthSchema,
  947. order_no: str,
  948. status: str,
  949. ext_info: dict = {}
  950. ) -> None:
  951. """
  952. 更新转账状态(由通知处理器调用)
  953. """
  954. crud = TransferCRUD(auth)
  955. transfer = await crud.get_by_order_no(order_no)
  956. if not transfer:
  957. log.warning(f"转账记录不存在: {order_no}")
  958. return
  959. update_data = {}
  960. update_data["status"] = status
  961. if ext_info:
  962. update_data["ext_info"] = ext_info
  963. await crud.update_by_order_no(order_no, update_data)
  964. @classmethod
  965. async def update_deposit_status_service(
  966. cls,
  967. auth: AuthSchema,
  968. out_biz_no: str,
  969. status: str,
  970. ) -> None:
  971. """
  972. 更新充值状态(由通知处理器调用)
  973. """
  974. crud = DepositCRUD(auth)
  975. deposit = await crud.get_by_out_biz_no(out_biz_no)
  976. if not deposit:
  977. log.warning(f"充值记录不存在: {out_biz_no}")
  978. return
  979. update_data = {"status": status}
  980. await crud.update_by_out_biz_no(out_biz_no, update_data)
  981. @classmethod
  982. async def update_withdraw_status_service(
  983. cls,
  984. auth: AuthSchema,
  985. out_biz_no: str,
  986. status: str,
  987. error_code: str | None = None,
  988. error_msg: str | None = None,
  989. ) -> None:
  990. """
  991. 更新提现状态(由通知处理器调用)
  992. """
  993. crud = WithdrawCRUD(auth)
  994. withdraw = await crud.get_by_out_biz_no(out_biz_no)
  995. if not withdraw:
  996. log.warning(f"提现记录不存在: {out_biz_no}")
  997. return
  998. update_data = {"status": status}
  999. if error_code:
  1000. update_data["error_code"] = error_code
  1001. if error_msg:
  1002. update_data["error_msg"] = error_msg
  1003. await crud.update_by_out_biz_no(out_biz_no, update_data)
  1004. @classmethod
  1005. async def consume_detail_query_service(
  1006. cls,
  1007. auth: AuthSchema,
  1008. pay_no: str,
  1009. enterprise_id: str | None = None,
  1010. ant_shop_id: str | None = None,
  1011. query_options: list[str] | None = None,
  1012. ) -> dict:
  1013. """
  1014. 账单详情查询(✅)
  1015. 调用: alipay.commerce.ec.consume.detail.query
  1016. 用于查询企业码账单详情,支持查询关联退款、订单、票据等信息。
  1017. """
  1018. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  1019. AlipayCommerceEcConsumeDetailQueryRequest,
  1020. )
  1021. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  1022. AlipayCommerceEcConsumeDetailQueryModel,
  1023. )
  1024. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  1025. AlipayCommerceEcConsumeDetailQueryResponse,
  1026. )
  1027. model = AlipayCommerceEcConsumeDetailQueryModel()
  1028. model.pay_no = pay_no
  1029. if enterprise_id:
  1030. model.enterprise_id = enterprise_id
  1031. if ant_shop_id:
  1032. model.ant_shop_id = ant_shop_id
  1033. if query_options:
  1034. model.query_options = query_options
  1035. request = AlipayCommerceEcConsumeDetailQueryRequest()
  1036. request.biz_model = model
  1037. client = AlipayClient.get_client()
  1038. response = client.execute(request)
  1039. if not response:
  1040. raise CustomException(msg="账单详情查询失败: 无响应")
  1041. result = AlipayCommerceEcConsumeDetailQueryResponse()
  1042. result.parse_response_content(response)
  1043. if not result.is_success():
  1044. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  1045. raise CustomException(msg=f"账单详情查询失败: {result.msg}")
  1046. consume_info = result.consume_info
  1047. if not consume_info:
  1048. raise CustomException(msg="账单详情查询失败: 无账单信息")
  1049. return {
  1050. "account_id": consume_info.account_id,
  1051. "pay_no": consume_info.pay_no,
  1052. "consume_type": consume_info.consume_type,
  1053. "gmt_biz_create": consume_info.gmt_biz_create,
  1054. "consume_biz_type": consume_info.consume_biz_type,
  1055. "consume_amount": consume_info.consume_amount,
  1056. "order_complete_label": consume_info.order_complete_label,
  1057. "refund_status": consume_info.refund_status,
  1058. "refund_amount": consume_info.refund_amount,
  1059. "peer_payer_card_name": consume_info.peer_payer_card_name,
  1060. "user_id": getattr(consume_info, 'user_id', None),
  1061. "open_id": getattr(consume_info, 'open_id', None),
  1062. "enterprise_id": consume_info.enterprise_id,
  1063. "employee_id": consume_info.employee_id,
  1064. "enterprise_name": getattr(consume_info, 'enterprise_name', None),
  1065. "employee_name": getattr(consume_info, 'employee_name', None),
  1066. "consume_scene_code": getattr(consume_info, 'consume_scene_code', None),
  1067. "consume_type_sub_category": getattr(consume_info, 'consume_type_sub_category', None),
  1068. "consume_title": getattr(consume_info, 'consume_title', None),
  1069. "gmt_pay": getattr(consume_info, 'gmt_pay', None),
  1070. "gmt_refund": getattr(consume_info, 'gmt_refund', None),
  1071. "pay_amount": getattr(consume_info, 'pay_amount', None),
  1072. "invoice_amount": getattr(consume_info, 'invoice_amount', None),
  1073. "peer_pay_amount": getattr(consume_info, 'peer_pay_amount', None),
  1074. "subsidy_amount": getattr(consume_info, 'subsidy_amount', None),
  1075. "ext_infos": getattr(consume_info, 'ext_infos', None),
  1076. }