WalletWithdrawRecordService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. namespace App\Services\Admin;
  3. use App\Models\WalletWithdrawRecord;
  4. use App\Models\WalletTransRecord;
  5. use App\Enums\WithdrawStatus;
  6. use App\Enums\WithdrawAuditStatus;
  7. use App\Enums\TransactionType;
  8. use App\Enums\TransactionStatus;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use App\Enums\WithdrawMethod;
  12. use EasyWeChat\Pay\Application;
  13. class WalletWithdrawRecordService
  14. {
  15. /**
  16. * 审核提现申请
  17. *
  18. * @param int $id 提现记录ID
  19. * @param int $status 审核状态(2:通过 3:拒绝)
  20. * @param string|null $remark 审核备注
  21. */
  22. public function audit(int $id, int $status, ?string $remark = null): void
  23. {
  24. DB::transaction(function () use ($id, $status, $remark) {
  25. // 获取提现记录
  26. $record = WalletWithdrawRecord::lockForUpdate()->findOrFail($id);
  27. // 验证记录状态
  28. abort_if($record->audit_state !== WithdrawAuditStatus::PENDING->value, 400, '提现申请状态异常');
  29. // 获取用户钱包
  30. $wallet = $record->wallet;
  31. abort_if(!$wallet, 404, '钱包信息不存在');
  32. // 验证冻结金额
  33. abort_if($wallet->frozen_amount < $record->amount, 400, '钱包冻结金额异常');
  34. if ($status === WithdrawAuditStatus::APPROVED->value) {
  35. // 审核通过,发起自动打款
  36. $this->processApproved($record, $remark);
  37. } else {
  38. // 审核拒绝,解冻余额
  39. $this->processRejected($record, $remark);
  40. }
  41. // 记录审核信息
  42. $record->auditor = auth()->user()->name;
  43. $record->audit_time = now();
  44. $record->audit_remark = $remark;
  45. $record->audit_state = $status;
  46. $record->save();
  47. // 记录日志
  48. Log::info('提现申请审核完成', [
  49. 'withdraw_id' => $record->id,
  50. 'external_no' => $record->external_no,
  51. 'status' => $status,
  52. 'remark' => $remark,
  53. 'auditor' => $record->auditor
  54. ]);
  55. });
  56. }
  57. /**
  58. * 处理审核通过
  59. */
  60. private function processApproved(WalletWithdrawRecord $record, ?string $remark): void
  61. {
  62. try {
  63. // 1. 更新提现记录状态为处理中
  64. $record->state = WithdrawStatus::PROCESSING->value;
  65. $record->save();
  66. // 获取钱包当前余额
  67. $wallet = $record->wallet;
  68. $currentBalance = $wallet->available_balance;
  69. $currentRechargeBalance = $wallet->recharge_amount;
  70. // 2. 创建转账记录
  71. $transRecord = WalletTransRecord::create([
  72. 'trans_no' => $this->generateTransNo(),
  73. 'wallet_id' => $record->wallet_id,
  74. 'owner_id' => $record->id,
  75. 'owner_type' => 'withdraw', // 业务类型:提现
  76. 'trans_type' => 2, // 交易类型:支出
  77. 'amount' => $record->amount,
  78. 'before_balance' => $currentBalance,
  79. 'after_balance' => $currentBalance - $record->amount,
  80. 'before_recharge_balance' => $currentRechargeBalance,
  81. 'after_recharge_balance' => $currentRechargeBalance,
  82. 'trans_time' => now(),
  83. 'remark' => '提现打款',
  84. 'state' => TransactionStatus::PROCESSING->value,
  85. 'province' => $record->area_code ? substr($record->area_code, 0, 2) . '0000' : null,
  86. 'city' => $record->area_code ? substr($record->area_code, 0, 4) . '00' : null,
  87. 'district' => $record->area_code
  88. ]);
  89. // 3. 调用支付服务发起转账
  90. // TODO: 对接实际的支付服务
  91. $paymentResult = $this->processPayment($record);
  92. if ($paymentResult['success']) {
  93. // 4. 打款成功
  94. // 4.1 更新提现记录状态
  95. $record->state = WithdrawStatus::SUCCESS->value;
  96. $record->withdraw_time = now();
  97. $record->trans_no = $paymentResult['trade_no'];
  98. $record->remark = '打款成功';
  99. $record->save();
  100. // 4.2 更新转账记录状态
  101. $transRecord->state = TransactionStatus::SUCCESS->value;
  102. $transRecord->trans_no = $paymentResult['trade_no'];
  103. $transRecord->save();
  104. // 4.3 扣除钱包冻结金额
  105. $record->wallet->decrement('frozen_amount', $record->amount);
  106. // 4.4 扣除钱包总金额
  107. $record->wallet->decrement('total_balance', $record->amount);
  108. } else {
  109. // 5. 打款失败
  110. throw new \Exception($paymentResult['message'] ?? '打款失败');
  111. }
  112. } catch (\Exception $e) {
  113. // 6. 处理异常
  114. Log::error('提现打款失败', [
  115. 'withdraw_id' => $record->id,
  116. 'error' => $e->getMessage()
  117. ]);
  118. // 6.1 更新提现记录状态
  119. $record->state = WithdrawStatus::FAILED->value;
  120. $record->remark = $e->getMessage();
  121. $record->save();
  122. // 6.2 更新转账记录状态
  123. if (isset($transRecord)) {
  124. $transRecord->state = TransactionStatus::FAILED->value;
  125. $transRecord->save();
  126. }
  127. // 6.3 解冻余额
  128. $this->unfreezeBalance($record);
  129. throw $e;
  130. }
  131. }
  132. /**
  133. * 处理审核拒绝
  134. */
  135. private function processRejected(WalletWithdrawRecord $record, ?string $remark): void
  136. {
  137. // 1. 更新提现记录状态
  138. $record->state = WithdrawStatus::FAILED->value;
  139. $record->save();
  140. // 2. 解冻余额
  141. $this->unfreezeBalance($record);
  142. // 3. 记录日志
  143. Log::info('提现申请已拒绝', [
  144. 'withdraw_id' => $record->id,
  145. 'external_no' => $record->external_no,
  146. 'amount' => $record->amount,
  147. 'remark' => $remark
  148. ]);
  149. }
  150. /**
  151. * 解冻余额
  152. */
  153. private function unfreezeBalance(WalletWithdrawRecord $record): void
  154. {
  155. $wallet = $record->wallet;
  156. // 获取当前余额
  157. $currentBalance = $wallet->available_balance;
  158. $currentRechargeBalance = $wallet->recharge_amount;
  159. // 从冻结金额中减少
  160. $wallet->decrement('frozen_amount', $record->amount);
  161. // 增加可用余额
  162. $wallet->increment('available_balance', $record->amount);
  163. // 记录解冻操作
  164. WalletTransRecord::create([
  165. 'trans_no' => $this->generateTransNo(),
  166. 'wallet_id' => $wallet->id,
  167. 'owner_id' => $record->id,
  168. 'owner_type' => 'withdraw',
  169. 'trans_type' => 1, // 交易类型:收入
  170. 'amount' => $record->amount,
  171. 'before_balance' => $currentBalance,
  172. 'after_balance' => $currentBalance + $record->amount,
  173. 'before_recharge_balance' => $currentRechargeBalance,
  174. 'after_recharge_balance' => $currentRechargeBalance,
  175. 'trans_time' => now(),
  176. 'remark' => '提现拒绝解冻',
  177. 'state' => TransactionStatus::SUCCESS->value
  178. ]);
  179. }
  180. /**
  181. * 生成交易流水号
  182. */
  183. private function generateTransNo(): string
  184. {
  185. return 'T' . date('YmdHis') . str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
  186. }
  187. /**
  188. * 处理实际打款
  189. *
  190. * @param WalletWithdrawRecord $record 提现记录
  191. * @return array [
  192. * 'success' => bool 是否成功
  193. * 'trade_no' => string 交易流水号
  194. * 'message' => string 结果信息
  195. * ]
  196. * @throws \Exception
  197. */
  198. private function processPayment(WalletWithdrawRecord $record): array
  199. {
  200. try {
  201. Log::info('开始处理提现打款', [
  202. 'withdraw_id' => $record->id,
  203. 'withdraw_type' => $record->withdraw_type,
  204. 'amount' => $record->amount,
  205. 'account' => $record->withdraw_account
  206. ]);
  207. // 根据提现方式调用不同的转账接口
  208. if ($record->withdraw_type === WithdrawMethod::WECHAT->value) {
  209. Log::info('使用微信转账方式', [
  210. 'withdraw_id' => $record->id,
  211. 'config' => config('wechat.pay.default')
  212. ]);
  213. // 使用 EasyWeChat 支付实例
  214. $config = config('wechat.pay.default');
  215. $app = new \EasyWeChat\Pay\Application($config);
  216. // 生成商户订单号
  217. $outTradeNo = 'W' . date('YmdHis') . str_pad($record->id, 6, '0', STR_PAD_LEFT);
  218. $requestData = [
  219. 'partner_trade_no' => $outTradeNo,
  220. 'openid' => $record->withdraw_account,
  221. 'check_name' => 'NO_CHECK', // 不校验真实姓名
  222. 'amount' => (int)bcmul($record->amount, '100'), // 金额单位为分
  223. 'desc' => '提现到零钱',
  224. ];
  225. Log::info('微信转账请求参数', [
  226. 'withdraw_id' => $record->id,
  227. 'request_data' => $requestData
  228. ]);
  229. try {
  230. // 使用商家转账API(需要用户确认)
  231. $response = $app->getClient()->postJson('v3/merchant-transfer/transfer-bills', [
  232. 'appid' => $config['app_id'],
  233. 'out_bill_no' => $outTradeNo,
  234. 'transfer_scene_id' => '1001', // 现金营销场景
  235. 'openid' => $record->withdraw_account,
  236. 'transfer_amount' => (int)bcmul($record->amount, '100'),
  237. 'transfer_remark' => '提现到零钱',
  238. 'transfer_scene_report_infos' => [
  239. [
  240. 'info_type' => '活动名称',
  241. 'info_content' => '用户提现'
  242. ],
  243. [
  244. 'info_type' => '奖励说明',
  245. 'info_content' => '余额提现'
  246. ]
  247. ]
  248. ]);
  249. $result = $response->toArray();
  250. Log::info('微信转账响应结果', [
  251. 'withdraw_id' => $record->id,
  252. 'result' => $result
  253. ]);
  254. // 返回需要前端处理的确认数据
  255. if (isset($result['transfer_id'])) {
  256. return [
  257. 'success' => true,
  258. 'trade_no' => $result['transfer_id'],
  259. 'message' => '请在微信中确认收款',
  260. 'need_confirm' => true,
  261. 'confirm_data' => [
  262. 'transfer_id' => $result['transfer_id'],
  263. 'out_bill_no' => $outTradeNo
  264. ]
  265. ];
  266. }
  267. throw new \Exception($result['err_code_des'] ?? '微信转账失败');
  268. } catch (\Exception $e) {
  269. Log::error('微信转账请求异常', [
  270. 'withdraw_id' => $record->id,
  271. 'error' => $e->getMessage(),
  272. 'trace' => $e->getTraceAsString()
  273. ]);
  274. throw $e;
  275. }
  276. } elseif ($record->withdraw_type === WithdrawMethod::ALIPAY->value) {
  277. Log::info('使用支付宝转账方式', [
  278. 'withdraw_id' => $record->id,
  279. 'config' => [
  280. 'app_id' => config('alipay.app_id'),
  281. // 不记录敏感信息
  282. ]
  283. ]);
  284. // 使用支付宝 SDK 调用转账接口
  285. $config = [
  286. 'app_id' => config('alipay.app_id'),
  287. 'private_key' => config('alipay.private_key'),
  288. 'alipay_public_key' => config('alipay.alipay_public_key'),
  289. ];
  290. // 初始化支付宝 SDK
  291. \Alipay\EasySDK\Kernel\Factory::setOptions($config);
  292. $requestData = [
  293. 'out_biz_no' => $record->external_no,
  294. 'trans_amount' => $record->amount,
  295. 'product_code' => 'TRANS_ACCOUNT_NO_PWD',
  296. 'biz_scene' => 'DIRECT_TRANSFER',
  297. 'payee_info' => [
  298. 'identity' => $record->withdraw_account,
  299. 'identity_type' => 'ALIPAY_LOGON_ID',
  300. 'name' => $record->withdraw_account_name,
  301. ],
  302. 'remark' => '用户提现',
  303. ];
  304. Log::info('支付宝转账请求参数', [
  305. 'withdraw_id' => $record->id,
  306. 'request_data' => $requestData
  307. ]);
  308. $result = \Alipay\EasySDK\Kernel\Factory::payment()->common()
  309. ->transfer($requestData);
  310. Log::info('支付宝转账响应结果', [
  311. 'withdraw_id' => $record->id,
  312. 'result' => json_encode($result)
  313. ]);
  314. if ($result->code === '10000') {
  315. Log::info('支付宝转账成功', [
  316. 'withdraw_id' => $record->id,
  317. 'trade_no' => $result->order_id
  318. ]);
  319. return [
  320. 'success' => true,
  321. 'trade_no' => $result->order_id,
  322. 'message' => '支付宝转账成功'
  323. ];
  324. }
  325. throw new \Exception($result->sub_msg ?? '支付宝转账失败');
  326. } elseif ($record->withdraw_type === WithdrawMethod::BANK->value) {
  327. Log::info('使用银行卡转账方式(模拟)', [
  328. 'withdraw_id' => $record->id
  329. ]);
  330. // 银行卡转账暂时使用模拟逻辑
  331. $tradeNo = 'BANK' . time() . random_int(1000, 9999);
  332. Log::info('模拟银行卡打款成功', [
  333. 'withdraw_id' => $record->id,
  334. 'trade_no' => $tradeNo
  335. ]);
  336. return [
  337. 'success' => true,
  338. 'trade_no' => $tradeNo,
  339. 'message' => '模拟银行卡打款成功'
  340. ];
  341. } else {
  342. Log::error('不支持的提现方式', [
  343. 'withdraw_id' => $record->id,
  344. 'withdraw_type' => $record->withdraw_type
  345. ]);
  346. throw new \Exception('不支持的提现方式');
  347. }
  348. } catch (\Exception $e) {
  349. Log::error('转账处理失败', [
  350. 'withdraw_id' => $record->id,
  351. 'withdraw_type' => $record->withdraw_type,
  352. 'error_message' => $e->getMessage(),
  353. 'error_trace' => $e->getTraceAsString()
  354. ]);
  355. return [
  356. 'success' => false,
  357. 'trade_no' => '',
  358. 'message' => $e->getMessage()
  359. ];
  360. }
  361. }
  362. /**
  363. * 审核通过提现申请
  364. *
  365. * @param WalletWithdrawRecord $record
  366. * @return array
  367. * @throws \Exception
  368. */
  369. public function approve(WalletWithdrawRecord $record): array
  370. {
  371. // 1. 检查状态
  372. if ($record->state !== WithdrawAuditStatus::PENDING->value) {
  373. throw new \Exception('提现记录状态不正确');
  374. }
  375. // 2. 处理打款
  376. $result = $this->processPayment($record);
  377. if ($result['success']) {
  378. // 3. 更新提现记录状态
  379. $record->update([
  380. 'state' => WithdrawAuditStatus::APPROVED->value, // 更新为处理中状态
  381. 'external_no' => $result['trade_no'], // 保存交易流水号
  382. 'audit_time' => now(), // 审核时间
  383. 'audit_user_id' => auth()->id(), // 审核人ID
  384. ]);
  385. // 4. 发送模板消息通知用户确认收款
  386. if (isset($result['need_confirm']) && $result['need_confirm']) {
  387. try {
  388. $this->sendConfirmNotification($record, $result['confirm_data']);
  389. } catch (\Exception $e) {
  390. Log::error('发送确认收款通知失败', [
  391. 'withdraw_id' => $record->id,
  392. 'error' => $e->getMessage()
  393. ]);
  394. }
  395. }
  396. // 5. 记录日志
  397. Log::info('提现申请已审核通过', [
  398. 'withdraw_id' => $record->id,
  399. 'external_no' => $result['trade_no'],
  400. 'amount' => $record->amount,
  401. 'need_confirm' => $result['need_confirm'] ?? false
  402. ]);
  403. return [
  404. 'success' => true,
  405. 'message' => $result['message']
  406. ];
  407. }
  408. throw new \Exception($result['message']);
  409. }
  410. /**
  411. * 发送确认收款通知
  412. */
  413. private function sendConfirmNotification(WalletWithdrawRecord $record, array $confirmData): void
  414. {
  415. // 获取微信配置
  416. $config = config('wechat.official_account.default');
  417. $app = new \EasyWeChat\OfficialAccount\Application($config);
  418. // 发送模板消息
  419. $app->getClient()->postJson('cgi-bin/message/template/send', [
  420. 'touser' => $record->withdraw_account,
  421. 'template_id' => config('wechat.template_ids.withdraw_confirm'),
  422. 'url' => config('app.h5_url') . '/pages/wallet/withdraw-confirm', // 确认收款页面
  423. 'data' => [
  424. 'first' => [
  425. 'value' => '您的提现申请已审核通过,请确认收款'
  426. ],
  427. 'keyword1' => [
  428. 'value' => $record->amount . '元'
  429. ],
  430. 'keyword2' => [
  431. 'value' => $record->external_no
  432. ],
  433. 'remark' => [
  434. 'value' => '请在24小时内确认收款,逾期未确认将自动退回。'
  435. ]
  436. ]
  437. ]);
  438. }
  439. }