Withdraw.php 18 KB

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