service.py 48 KB

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