Withdraw.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. namespace app\common\Service;
  3. use app\common\exception\BusinessException;
  4. use think\Db;
  5. use think\Log;
  6. use think\exception\HttpResponseException;
  7. use app\common\model\Withdraw as WithdrawModel;
  8. use app\common\model\WithdrawLog as WithdrawLogModel;
  9. use app\common\library\Operator;
  10. use app\common\library\BcMath;
  11. use app\common\model\ThirdOauth;
  12. use app\common\Service\Wallet as WalletService;
  13. use app\common\Service\Pay\PayService;
  14. use app\common\model\User;
  15. class Withdraw
  16. {
  17. protected $user = null;
  18. /**
  19. * @var array
  20. */
  21. public $config = [];
  22. public function __construct($user = null)
  23. {
  24. if ($user) {
  25. $this->user = is_numeric($user) ? User::get($user) : $user;
  26. }
  27. // 提现规则
  28. $config = shop_config('shop.withdraw');
  29. $config['min_amount'] = BcMath::isZero($config['min_amount']) ? $config['min_amount'] : BcMath::format($config['min_amount'], 2);
  30. $config['max_amount'] = BcMath::isZero($config['max_amount']) ? $config['max_amount'] : BcMath::format($config['max_amount'], 2);
  31. $config['charge_rate_format'] = round(floatval($config['charge_rate']), 1); // 1 位小数
  32. $config['charge_rate'] = BcMath::div($config['charge_rate'], '100', 3);
  33. $config['num_unit'] = $config['num_unit'] == 'day' ? '天' : '月';
  34. $this->config = $config;
  35. }
  36. /**
  37. * 获取用户提现记录列表
  38. * @param array $params 查询参数
  39. * @return array 包含列表数据和统计信息
  40. */
  41. public function getWithdrawList($params = [])
  42. {
  43. // 构建查询条件数组
  44. $arrWhere = ['user_id' => $this->user->id];
  45. // 状态筛选
  46. if (isset($params['status']) && $params['status'] !== '') {
  47. $arrWhere['status'] = (int)$params['status'];
  48. }
  49. // 年月筛选 (支持YYYY-MM格式)
  50. $timeWhere = [];
  51. if (isset($params['year_month']) && !empty($params['year_month'])) {
  52. $yearMonth = trim($params['year_month']);
  53. // 解析年月字符串 (YYYY-MM)
  54. if (preg_match('/^(\d{4})-(\d{2})$/', $yearMonth, $matches)) {
  55. $year = (int)$matches[1];
  56. $month = (int)$matches[2];
  57. // 按年月筛选
  58. $startTime = mktime(0, 0, 0, $month, 1, $year);
  59. $endTime = mktime(23, 59, 59, $month + 1, 0, $year);
  60. $timeWhere = [
  61. 'createtime' => ['between', [$startTime, $endTime]]
  62. ];
  63. }
  64. }
  65. // 合并查询条件
  66. $finalWhere = array_merge($arrWhere, $timeWhere);
  67. // 计算筛选条件下的总金额(使用BC数学函数)
  68. $totalAmount = '0.00';
  69. $totalChargeAmount = '0.00';
  70. $totalActualAmount = '0.00';
  71. $totalCount = 0;
  72. // 执行统计查询
  73. $statsRecords = WithdrawModel::where($finalWhere)->field(['amount', 'charge_fee'])->select();
  74. foreach ($statsRecords as $record) {
  75. $totalAmount = BcMath::add($totalAmount, $record->amount, 2);
  76. $totalChargeAmount = BcMath::add($totalChargeAmount, $record->charge_fee, 2);
  77. $actualAmount = BcMath::sub($record->amount, $record->charge_fee, 2);
  78. $totalActualAmount = BcMath::add($totalActualAmount, $actualAmount, 2);
  79. $totalCount++;
  80. }
  81. // 分页参数
  82. $page_size = isset($params['page_size']) ? (int)$params['page_size'] : 10;
  83. // 查询提现记录(使用相同的查询条件)
  84. $withdraws = WithdrawModel::where($finalWhere)
  85. ->order('id desc')
  86. ->paginate($page_size)
  87. ->each(function ($withdraw) {
  88. // 隐藏敏感信息
  89. $withdraw->hidden(['withdraw_info']);
  90. });
  91. // 组装返回数据
  92. $result = [
  93. 'list' => $withdraws,
  94. 'summary' => [
  95. 'total_count' => $totalCount,
  96. 'total_amount' => $totalAmount,
  97. 'total_charge_amount' => $totalChargeAmount,
  98. 'total_actual_amount' => $totalActualAmount,
  99. 'filter_info' => [
  100. 'year_month' => isset($params['year_month']) ? $params['year_month'] : null,
  101. 'status' => isset($params['status']) ? (int)$params['status'] : null,
  102. ]
  103. ]
  104. ];
  105. return $result;
  106. }
  107. /**
  108. * 获取提现状态列表
  109. * @return array
  110. */
  111. public function getStatusList()
  112. {
  113. return [
  114. -3 => '撤销提现',
  115. -2 => '提现失败',
  116. -1 => '已拒绝',
  117. 0 => '待审核',
  118. 1 => '处理中',
  119. 2 => '已处理'
  120. ];
  121. }
  122. // 发起提现申请
  123. public function apply($params)
  124. {
  125. $type = $params['type'];
  126. $money = $params['amount'] ?? 0; // money 改为 amount
  127. $money = (string)$money;
  128. // 手续费
  129. $charge = BcMath::mul($money, $this->config['charge_rate'], 2);
  130. // 检查提现规则
  131. $this->checkApply($type, $money, $charge);
  132. // 获取账号信息
  133. $withdrawInfo = $this->getAccountInfo($type, $params);
  134. // 添加提现记录
  135. $withdraw = new WithdrawModel();
  136. $withdraw->user_id = $this->user->id;
  137. $withdraw->amount = $money;
  138. $withdraw->charge_fee = $charge;
  139. $withdraw->charge_rate = $this->config['charge_rate'];
  140. $withdraw->withdraw_sn = get_sn($this->user->id, 'W');
  141. $withdraw->withdraw_type = $type;
  142. $withdraw->withdraw_info = $withdrawInfo;
  143. $withdraw->status = 0;
  144. $withdraw->platform = request()->header('platform');
  145. $withdraw->save();
  146. // 佣金钱包变动
  147. WalletService::change($this->user, 'commission', '-' . BcMath::add($charge, $money, 2), 'withdraw', [
  148. 'withdraw_id' => $withdraw->id,
  149. 'amount' => $withdraw->amount,
  150. 'charge_fee' => $withdraw->charge_fee,
  151. 'charge_rate' => $withdraw->charge_rate,
  152. ]);
  153. $this->handleLog($withdraw, '用户发起提现申请', $this->user);
  154. return $withdraw;
  155. }
  156. // 继续提现
  157. public function retry($params)
  158. {
  159. $withdraw = WithdrawModel::where('user_id', $this->user->id)
  160. ->where('withdraw_sn', $params['withdraw_sn'])
  161. ->where('status', 1)
  162. ->where('withdraw_type', 'wechat')
  163. ->find();
  164. if (!$withdraw) {
  165. throw new BusinessException('提现记录不存在');
  166. }
  167. if (request()->header('platform') !== $withdraw->platform) {
  168. throw new BusinessException('请在发起该次提现的平台操作');
  169. }
  170. $this->handleLog($withdraw, '用户重新发起提现申请');
  171. // 实时检查提现单状态
  172. return $this->checkWechatTransferResult($withdraw);
  173. }
  174. // 取消提现(适用于微信商家转账)
  175. public function cancel($params)
  176. {
  177. $withdraw = WithdrawModel::where('user_id', $this->user->id)
  178. ->where('withdraw_sn', $params['withdraw_sn'])
  179. ->where('status', 1)
  180. ->where('withdraw_type', 'wechat')
  181. ->find();
  182. if (!$withdraw) {
  183. throw new BusinessException('提现记录不存在');
  184. }
  185. if (request()->header('platform') !== $withdraw->platform) {
  186. throw new BusinessException('请在发起该次提现的平台操作');
  187. }
  188. // 实时检查提现单状态
  189. $withdraw = $this->checkWechatTransferResult($withdraw);
  190. if ($withdraw->wechat_transfer_state !== 'WAIT_USER_CONFIRM') {
  191. throw new BusinessException('该提现单暂无法发起取消操作,请联系客服');
  192. }
  193. // 提交微信撤销单
  194. $payService = new PayService($withdraw->withdraw_type, $withdraw->platform);
  195. try {
  196. $result = $payService->cancelTransferOrder([
  197. 'withdraw_sn' => $withdraw->withdraw_sn,
  198. ]);
  199. } catch (\Exception $e) {
  200. \think\Log::error('撤销提现失败: ' . ': 行号: ' . $e->getLine() . ': 文件: ' . $e->getFile() . ': 错误信息: ' . $e->getMessage());
  201. $this->handleLog($withdraw, '撤销微信商家转账失败: ' . $e->getMessage());
  202. throw new BusinessException($e->getMessage());
  203. }
  204. $withdraw->wechat_transfer_state = $result['state'];
  205. $withdraw->save();
  206. $this->handleLog($withdraw, '申请撤销微信商家转账成功,报文信息:' . json_encode($result, JSON_UNESCAPED_UNICODE));
  207. return $withdraw;
  208. }
  209. // 新版本微信商家转账
  210. // https://pay.weixin.qq.com/doc/v3/merchant/4012711988
  211. public function handleWechatTransfer($withdraw)
  212. {
  213. $payService = new PayService($withdraw->withdraw_type, $withdraw->platform);
  214. $payload = [
  215. '_action' => 'mch_transfer', // 新版转账
  216. 'out_bill_no' => $withdraw->withdraw_sn,
  217. 'transfer_scene_id' => '1005',
  218. 'openid' => $withdraw->withdraw_info['微信ID'] ?? '',
  219. 'user_name' => $withdraw->withdraw_info['真实姓名'] ?? '', // 明文传参即可,sdk 会自动加密
  220. 'transfer_amount' => $withdraw->amount,
  221. 'transfer_remark' => "用户[" . ($withdraw->withdraw_info['微信用户'] ?? '') . "]提现",
  222. 'transfer_scene_report_infos' => [
  223. ['info_type' => '岗位类型', 'info_content' => '推广专员'],
  224. ['info_type' => '报酬说明', 'info_content' => '推广佣金报酬'],
  225. ],
  226. ];
  227. try {
  228. list($response, $transferData) = $payService->transfer($payload);
  229. $withdraw->status = 1; // 提现处理中
  230. $withdraw->wechat_transfer_state = $response['state'];
  231. $withdraw->payment_json = json_encode($response, JSON_UNESCAPED_UNICODE);
  232. $withdraw->save();
  233. $this->handleLog($withdraw, '用户发起微信商家转账收款,报文信息:' . json_encode($response, JSON_UNESCAPED_UNICODE), $this->user);
  234. return $transferData;
  235. } catch (\Exception $e) {
  236. \think\Log::error('提现失败: ' . ': 行号: ' . $e->getLine() . ': 文件: ' . $e->getFile() . ': 错误信息: ' . $e->getMessage());
  237. // $withdraw->wechat_transfer_state = 'NOT_FOUND';
  238. $withdraw->save();
  239. $this->handleFail($withdraw, $e->getMessage());
  240. throw new BusinessException($e->getMessage());
  241. }
  242. // 发起提现失败,自动处理退还佣金
  243. }
  244. // 支付宝提现
  245. public function handleAlipayWithdraw($withdraw)
  246. {
  247. Db::startTrans();
  248. try {
  249. $withdraw = $this->handleAgree($withdraw, $this->user);
  250. $withdraw = $this->handleWithdraw($withdraw, $this->user);
  251. Db::commit();
  252. } catch (BusinessException $e) {
  253. Db::commit(); // 不回滚,记录错误日志
  254. throw new BusinessException($e->getMessage());
  255. } catch (HttpResponseException $e) {
  256. $data = $e->getResponse()->getData();
  257. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  258. throw new BusinessException($message);
  259. } catch (\Exception $e) {
  260. Db::rollback();
  261. throw new BusinessException($e->getMessage());
  262. }
  263. }
  264. // 同意操作
  265. public function handleAgree($withdraw, $oper = null)
  266. {
  267. if ($withdraw->status != 0) {
  268. throw new BusinessException('请勿重复操作');
  269. }
  270. $withdraw->status = 1;
  271. $withdraw->save();
  272. return $this->handleLog($withdraw, '同意提现申请', $oper);
  273. }
  274. // 处理打款
  275. public function handleWithdraw($withdraw, $oper = null)
  276. {
  277. $withDrawStatus = false;
  278. if ($withdraw->status != 1) {
  279. throw new BusinessException('请勿重复操作');
  280. }
  281. if ($withdraw->withdraw_type !== 'bank') {
  282. $withDrawStatus = $this->handleTransfer($withdraw);
  283. } else {
  284. $withDrawStatus = true;
  285. }
  286. if ($withDrawStatus) {
  287. $withdraw->status = 2;
  288. $withdraw->paid_fee = $withdraw->amount;
  289. $withdraw->save();
  290. return $this->handleLog($withdraw, '已打款', $oper);
  291. }
  292. return $withdraw;
  293. }
  294. // 拒绝操作
  295. public function handleRefuse($withdraw, $refuse_msg)
  296. {
  297. if ($withdraw->status != 0 && $withdraw->status != 1) {
  298. throw new BusinessException('请勿重复操作');
  299. }
  300. $withdraw->status = -1;
  301. $withdraw->save();
  302. // 退回用户佣金
  303. WalletService::change($this->user, 'commission', BcMath::add($withdraw->charge_fee, $withdraw->amount, 2), 'withdraw_error', [
  304. 'withdraw_id' => $withdraw->id,
  305. 'amount' => $withdraw->amount,
  306. 'charge_fee' => $withdraw->charge_fee,
  307. 'charge_rate' => $withdraw->charge_rate,
  308. ]);
  309. return $this->handleLog($withdraw, '拒绝:' . $refuse_msg);
  310. }
  311. // 失败
  312. public function handleFail($withdraw, $refuse_msg, $status = -2)
  313. {
  314. if ($withdraw->status != 0 && $withdraw->status != 1) {
  315. throw new BusinessException('请勿重复操作');
  316. }
  317. $withdraw->status = $status;
  318. $withdraw->save();
  319. // 退回用户佣金
  320. WalletService::change($this->user, 'commission', BcMath::add($withdraw->charge_fee, $withdraw->amount, 2), 'withdraw_error', [
  321. 'withdraw_id' => $withdraw->id,
  322. 'amount' => $withdraw->amount,
  323. 'charge_fee' => $withdraw->charge_fee,
  324. 'charge_rate' => $withdraw->charge_rate,
  325. ]);
  326. return $this->handleLog($withdraw, '提现失败,已退还提现佣金:' . $refuse_msg);
  327. }
  328. // 商家转账回调
  329. public function handleWechatTransferNotify($action, $withdrawSn, $originData)
  330. {
  331. $withdraw = WithdrawModel::where('withdraw_sn', $withdrawSn)->find();
  332. if (!$withdraw) {
  333. throw new BusinessException('提现记录不存在');
  334. }
  335. if ($withdraw->status !== 1) {
  336. throw new BusinessException('提现记录状态不正确');
  337. }
  338. $this->user = User::get($withdraw->user_id);
  339. if (!$this->user) {
  340. throw new BusinessException('用户不存在');
  341. }
  342. $withdraw->wechat_transfer_state = $action;
  343. switch ($action) {
  344. case 'SUCCESS':
  345. $withdraw->status = 2;
  346. $this->handleLog($withdraw, '微信商家转账成功,报文信息: ' . json_encode($originData, JSON_UNESCAPED_UNICODE), $this->user);
  347. $withdraw->save();
  348. break;
  349. case 'FAILED':
  350. $this->handleFail($withdraw, '微信商家转账失败,报文信息: ' . json_encode($originData, JSON_UNESCAPED_UNICODE), -2);
  351. break;
  352. case 'CANCELLED': // 撤销完成
  353. $this->handleFail($withdraw, '微信商家转账撤销成功,报文信息: ' . json_encode($originData, JSON_UNESCAPED_UNICODE), -3);
  354. break;
  355. default:
  356. $this->handleLog($withdraw, '回调结果不是终态,报文信息: ' . json_encode($originData, JSON_UNESCAPED_UNICODE), $this->user);
  357. }
  358. return true;
  359. }
  360. // 检查微信商家转账单结果
  361. public function checkWechatTransferResult($withdraw)
  362. {
  363. if ($withdraw->createtime < strtotime('-30 day')) {
  364. throw new BusinessException('提现单据已过期,请联系客服解决');
  365. }
  366. $payService = new PayService($withdraw->withdraw_type, $withdraw->platform);
  367. $result = $payService->queryTransferOrder([
  368. 'withdraw_sn' => $withdraw->withdraw_sn,
  369. ]);
  370. $withdraw->wechat_transfer_state = $result['state'];
  371. $withdraw->save();
  372. $this->handleLog($withdraw, '查询微信商家转账单,报文信息:' . json_encode($result, JSON_UNESCAPED_UNICODE));
  373. return $withdraw;
  374. }
  375. // 企业付款提现
  376. private function handleTransfer($withdraw)
  377. {
  378. $type = $withdraw->withdraw_type;
  379. $platform = $withdraw->platform;
  380. $payService = new PayService($type, $platform);
  381. if ($type == 'alipay') {
  382. $payload = [
  383. 'out_biz_no' => $withdraw->withdraw_sn,
  384. 'trans_amount' => $withdraw->amount,
  385. 'product_code' => 'TRANS_ACCOUNT_NO_PWD',
  386. 'biz_scene' => 'DIRECT_TRANSFER',
  387. // 'order_title' => '余额提现到',
  388. 'remark' => '用户提现',
  389. 'payee_info' => [
  390. 'identity' => $withdraw->withdraw_info['支付宝账户'] ?? '',
  391. 'identity_type' => 'ALIPAY_LOGON_ID',
  392. 'name' => $withdraw->withdraw_info['真实姓名'] ?? '',
  393. ]
  394. ];
  395. }
  396. try {
  397. list($code, $response) = $payService->transfer($payload);
  398. if ($code === 1) {
  399. $withdraw->payment_json = json_encode($response, JSON_UNESCAPED_UNICODE);
  400. $withdraw->save();
  401. return true;
  402. }
  403. throw new BusinessException(json_encode($response, JSON_UNESCAPED_UNICODE));
  404. } catch (HttpResponseException $e) {
  405. $data = $e->getResponse()->getData();
  406. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  407. throw new BusinessException($message);
  408. } catch (\Exception $e) {
  409. \think\Log::error('提现失败:' . ' 行号:' . $e->getLine() . '文件:' . $e->getFile() . '错误信息:' . $e->getMessage());
  410. $this->handleLog($withdraw, '提现失败:' . $e->getMessage());
  411. throw new BusinessException($e->getMessage()); // 弹出错误信息
  412. }
  413. return false;
  414. }
  415. // 添加日志
  416. private function handleLog($withdraw, $oper_info, $oper = null)
  417. {
  418. $oper = Operator::get($oper);
  419. WithdrawLogModel::insert([
  420. 'withdraw_id' => $withdraw->id,
  421. 'content' => $oper_info,
  422. 'oper_type' => $oper['type'],
  423. 'oper_id' => $oper['id'],
  424. 'createtime' => time()
  425. ]);
  426. return $withdraw;
  427. }
  428. // 提现条件检查
  429. private function checkApply($type, $money, $charge)
  430. {
  431. if (!in_array($type, $this->config['methods'])) {
  432. throw new BusinessException('暂不支持该提现方式');
  433. }
  434. // 使用BC数学函数检查金额是否大于0
  435. if (!BcMath::isPositive($money)) {
  436. throw new BusinessException('请输入正确的提现金额');
  437. }
  438. // 检查最小提现金额
  439. if (BcMath::isPositive($this->config['min_amount']) && BcMath::comp($money, $this->config['min_amount']) < 0) {
  440. throw new BusinessException('提现金额不能少于 ' . $this->config['min_amount'] . '元');
  441. }
  442. // 检查最大提现金额
  443. if (BcMath::isPositive($this->config['max_amount']) && BcMath::comp($money, $this->config['max_amount']) > 0) {
  444. throw new BusinessException('提现金额不能大于 ' . $this->config['max_amount'] . '元');
  445. }
  446. // 检查用户佣金余额是否足够
  447. $totalAmount = BcMath::add($charge, $money, 2);
  448. if (BcMath::comp($this->user->commission, $totalAmount) < 0) {
  449. throw new BusinessException('可提现佣金不足');
  450. }
  451. // 检查最大提现次数
  452. if (isset($this->config['max_num']) && $this->config['max_num'] > 0) {
  453. $start_time = $this->config['num_unit'] == 'day' ? strtotime(date('Y-m-d', time())) : strtotime(date('Y-m', time()));
  454. $num = WithdrawModel::where('user_id', $this->user->id)->where('createtime', '>=', $start_time)->count();
  455. if ($num >= $this->config['max_num']) {
  456. throw new BusinessException('每' . ($this->config['num_unit'] == 'day' ? '日' : '月') . '提现次数不能大于 ' . $this->config['max_num'] . '次');
  457. }
  458. }
  459. }
  460. // 获取提现账户信息
  461. private function getAccountInfo($type, $params)
  462. {
  463. // 根据账户ID查询账户信息
  464. $account = \app\common\model\user\Account::where([
  465. 'id' => $params['account_id'],
  466. 'user_id' => $this->user->id,
  467. 'type' => $type
  468. ])->find();
  469. if (!$account) {
  470. throw new BusinessException('账户信息不存在');
  471. }
  472. $platform = request()->header('platform');
  473. switch ($type) {
  474. case 'wechat':
  475. if ($platform == 'App') {
  476. $platform = 'openPlatform';
  477. } elseif (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  478. $platform = lcfirst(str_replace('Wechat', '', $platform));
  479. }
  480. $thirdOauth = ThirdOauth::where('provider', 'wechat')->where('platform', $platform)->where('user_id', $this->user->id)->find();
  481. if (!$thirdOauth) {
  482. throw new BusinessException('请先绑定微信账号', -1);
  483. }
  484. $withdrawInfo = [
  485. '真实姓名' => $account->account_name,
  486. '微信用户' => $thirdOauth['nickname'] ?: $this->user['nickname'],
  487. '微信ID' => $thirdOauth['openid'],
  488. ];
  489. break;
  490. case 'alipay':
  491. $withdrawInfo = [
  492. '真实姓名' => $account->account_name,
  493. '支付宝账户' => $account->account_no
  494. ];
  495. break;
  496. case 'bank':
  497. $withdrawInfo = [
  498. '真实姓名' => $account->account_name,
  499. '开户行' => $account->account_header,
  500. '银行卡号' => $account->account_no
  501. ];
  502. break;
  503. }
  504. if (!isset($withdrawInfo)) {
  505. throw new BusinessException('您的提现信息有误');
  506. }
  507. return $withdrawInfo;
  508. }
  509. }