service.py 47 KB

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