Withdraw.php 20 KB

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