Withdraw.php 19 KB

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