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