Withdraw.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. namespace addons\shopro\service;
  3. use addons\shopro\exception\ShoproException;
  4. use think\Db;
  5. use think\Log;
  6. use think\exception\HttpResponseException;
  7. use app\admin\model\shopro\Withdraw as WithdrawModel;
  8. use app\admin\model\shopro\WithdrawLog as WithdrawLogModel;
  9. use addons\shopro\library\Operator;
  10. use app\admin\model\shopro\ThirdOauth;
  11. use addons\shopro\service\Wallet as WalletService;
  12. use addons\shopro\library\pay\PayService;
  13. use app\admin\model\shopro\user\User;
  14. class Withdraw
  15. {
  16. protected $user = null;
  17. /**
  18. * @var array
  19. */
  20. public $config = [];
  21. public function __construct($user)
  22. {
  23. $this->user = is_numeric($user) ? User::get($user) : $user;
  24. // 提现规则
  25. $config = sheep_config('shop.recharge_withdraw.withdraw');
  26. $config['min_amount'] = $config['min_amount'] == 0 ? $config['min_amount'] : number_format(floatval($config['min_amount']), 2, '.', '');
  27. $config['max_amount'] = $config['max_amount'] == 0 ? $config['max_amount'] : number_format(floatval($config['max_amount']), 2, '.', '');
  28. $config['charge_rate_format'] = round(floatval($config['charge_rate']), 1); // 1 位小数
  29. $config['charge_rate'] = round((floatval($config['charge_rate']) * 0.01), 3);
  30. $this->config = $config;
  31. }
  32. private function checkApply($type, $money, $charge)
  33. {
  34. if (!in_array($type, $this->config['methods'])) {
  35. error_stop('暂不支持该提现方式');
  36. }
  37. if ($money <= 0) {
  38. error_stop('请输入正确的提现金额');
  39. }
  40. // 检查最小提现金额
  41. if ($this->config['min_amount'] > 0 && $money < $this->config['min_amount']) {
  42. error_stop('提现金额不能少于 ' . $this->config['min_amount'] . '元');
  43. }
  44. // 检查最大提现金额
  45. if ($this->config['max_amount'] > 0 && $money > $this->config['max_amount']) {
  46. error_stop('提现金额不能大于 ' . $this->config['max_amount'] . '元');
  47. }
  48. if ($this->user->commission < bcadd($charge, $money, 2)) {
  49. error_stop('可提现佣金不足');
  50. }
  51. // 检查最大提现次数
  52. if (isset($this->config['max_num']) && $this->config['max_num'] > 0) {
  53. $start_time = $this->config['num_unit'] == 'day' ? strtotime(date('Y-m-d', time())) : strtotime(date('Y-m', time()));
  54. $num = WithdrawModel::where('user_id', $this->user->id)->where('createtime', '>=', $start_time)->count();
  55. if ($num >= $this->config['max_num']) {
  56. error_stop('每' . ($this->config['num_unit'] == 'day' ? '日' : '月') . '提现次数不能大于 ' . $this->config['max_num'] . '次');
  57. }
  58. }
  59. }
  60. public function accountInfo($type, $params)
  61. {
  62. $platform = request()->header('platform');
  63. switch ($type) {
  64. case 'wechat':
  65. if ($platform == 'App') {
  66. $platform = 'openPlatform';
  67. } elseif (in_array($platform, ['WechatOfficialAccount', 'WechatMiniProgram'])) {
  68. $platform = lcfirst(str_replace('Wechat', '', $platform));
  69. }
  70. $thirdOauth = ThirdOauth::where('provider', 'wechat')->where('platform', $platform)->where('user_id', $this->user->id)->find();
  71. if (!$thirdOauth) {
  72. error_stop('请先绑定微信账号', -1);
  73. }
  74. $withdrawInfo = [
  75. '真实姓名' => $params['account_name'],
  76. '微信用户' => $thirdOauth['nickname'],
  77. '微信ID' => $thirdOauth['openid'],
  78. ];
  79. break;
  80. case 'alipay':
  81. $withdrawInfo = [
  82. '真实姓名' => $params['account_name'],
  83. '支付宝账户' => $params['account_no']
  84. ];
  85. break;
  86. case 'bank':
  87. $withdrawInfo = [
  88. '真实姓名' => $params['account_name'],
  89. '开户行' => $params['account_header'] ?? '',
  90. '银行卡号' => $params['account_no']
  91. ];
  92. break;
  93. }
  94. if (!isset($withdrawInfo)) {
  95. error_stop('您的提现信息有误');
  96. }
  97. return $withdrawInfo;
  98. }
  99. public function apply($params)
  100. {
  101. $type = $params['type'] ?? 'wechat';
  102. $money = $params['money'] ?? 0;
  103. $money = (string)$money;
  104. // 手续费
  105. $charge = bcmul($money, (string)$this->config['charge_rate'], 2);
  106. // 检查提现规则
  107. $this->checkApply($type, $money, $charge);
  108. // 获取账号信息
  109. $withdrawInfo = $this->accountInfo($type, $params);
  110. $withdraw = Db::transaction(function () use ($type, $money, $charge, $withdrawInfo) {
  111. $platform = request()->header('platform');
  112. // 添加提现记录
  113. $withdraw = new WithdrawModel();
  114. $withdraw->user_id = $this->user->id;
  115. $withdraw->amount = $money;
  116. $withdraw->charge_fee = $charge;
  117. $withdraw->charge_rate = $this->config['charge_rate'];
  118. $withdraw->withdraw_sn = get_sn($this->user->id, 'W');
  119. $withdraw->withdraw_type = $type;
  120. $withdraw->withdraw_info = $withdrawInfo;
  121. $withdraw->status = 0;
  122. $withdraw->platform = $platform;
  123. $withdraw->save();
  124. // 佣金钱包变动
  125. WalletService::change($this->user, 'commission', - bcadd($charge, $money, 2), 'withdraw', [
  126. 'withdraw_id' => $withdraw->id,
  127. 'amount' => $withdraw->amount,
  128. 'charge_fee' => $withdraw->charge_fee,
  129. 'charge_rate' => $withdraw->charge_rate,
  130. ]);
  131. $this->handleLog($withdraw, '用户发起提现申请', $this->user);
  132. return $withdraw;
  133. });
  134. // 检查是否执行自动打款
  135. $autoCheck = false;
  136. if ($type !== 'bank' && $this->config['auto_arrival']) {
  137. $autoCheck = true;
  138. }
  139. if ($autoCheck) {
  140. Db::startTrans();
  141. try {
  142. $withdraw = $this->handleAgree($withdraw, $this->user);
  143. $withdraw = $this->handleWithdraw($withdraw, $this->user);
  144. Db::commit();
  145. } catch (ShoproException $e) {
  146. Db::commit(); // 不回滚,记录错误日志
  147. error_stop($e->getMessage());
  148. } catch (HttpResponseException $e) {
  149. $data = $e->getResponse()->getData();
  150. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  151. error_stop($message);
  152. } catch (\Exception $e) {
  153. Db::rollback();
  154. error_stop($e->getMessage());
  155. }
  156. }
  157. return $withdraw;
  158. }
  159. // 同意
  160. public function handleAgree($withdraw, $oper = null)
  161. {
  162. if ($withdraw->status != 0) {
  163. throw new ShoproException('请勿重复操作');
  164. }
  165. $withdraw->status = 1;
  166. $withdraw->save();
  167. return $this->handleLog($withdraw, '同意提现申请', $oper);
  168. }
  169. // 处理打款
  170. public function handleWithdraw($withdraw, $oper = null)
  171. {
  172. $withDrawStatus = false;
  173. if ($withdraw->status != 1) {
  174. throw new ShoproException('请勿重复操作');
  175. }
  176. if ($withdraw->withdraw_type !== 'bank') {
  177. $withDrawStatus = $this->handleTransfer($withdraw);
  178. } else {
  179. $withDrawStatus = true;
  180. }
  181. if ($withDrawStatus) {
  182. $withdraw->status = 2;
  183. $withdraw->paid_fee = $withdraw->amount;
  184. $withdraw->save();
  185. return $this->handleLog($withdraw, '已打款', $oper);
  186. }
  187. return $withdraw;
  188. }
  189. // 拒绝
  190. public function handleRefuse($withdraw, $refuse_msg)
  191. {
  192. if ($withdraw->status != 0 && $withdraw->status != 1) {
  193. throw new ShoproException('请勿重复操作');
  194. }
  195. $withdraw->status = -1;
  196. $withdraw->save();
  197. // 退回用户佣金
  198. WalletService::change($this->user, 'commission', bcadd($withdraw->charge_fee, $withdraw->amount, 2), 'withdraw_error', [
  199. 'withdraw_id' => $withdraw->id,
  200. 'amount' => $withdraw->amount,
  201. 'charge_fee' => $withdraw->charge_fee,
  202. 'charge_rate' => $withdraw->charge_rate,
  203. ]);
  204. return $this->handleLog($withdraw, '拒绝:' . $refuse_msg);
  205. }
  206. // 企业付款提现
  207. private function handleTransfer($withdraw)
  208. {
  209. operate_disabled();
  210. $type = $withdraw->withdraw_type;
  211. $platform = $withdraw->platform;
  212. $payService = new PayService($type, $platform);
  213. if ($type == 'wechat') {
  214. $payload = [
  215. 'out_batch_no' => $withdraw->withdraw_sn,
  216. 'batch_name' => '商家转账到零钱',
  217. 'batch_remark' => "用户[" . ($withdraw->withdraw_info['微信用户'] ?? '') . "]提现",
  218. 'total_amount' => $withdraw->amount,
  219. 'total_num' => 1,
  220. 'transfer_detail_list' => [
  221. [
  222. 'out_detail_no' => $withdraw->withdraw_sn,
  223. 'transfer_amount' => $withdraw->amount,
  224. 'transfer_remark' => "用户[" . ($withdraw->withdraw_info['微信用户'] ?? '') . "]提现",
  225. 'openid' => $withdraw->withdraw_info['微信ID'] ?? '',
  226. 'user_name' => $withdraw->withdraw_info['真实姓名'] ?? '',
  227. ],
  228. ],
  229. ];
  230. } elseif ($type == 'alipay') {
  231. $payload = [
  232. 'out_biz_no' => $withdraw->withdraw_sn,
  233. 'trans_amount' => $withdraw->amount,
  234. 'product_code' => 'TRANS_ACCOUNT_NO_PWD',
  235. 'biz_scene' => 'DIRECT_TRANSFER',
  236. // 'order_title' => '余额提现到',
  237. 'remark' => '用户提现',
  238. 'payee_info' => [
  239. 'identity' => $withdraw->withdraw_info['支付宝账户'] ?? '',
  240. 'identity_type' => 'ALIPAY_LOGON_ID',
  241. 'name' => $withdraw->withdraw_info['真实姓名'] ?? '',
  242. ]
  243. ];
  244. }
  245. try {
  246. list($code, $response) = $payService->transfer($payload);
  247. Log::write('transfer-origin-data:' . json_encode($response));
  248. if ($code === 1) {
  249. $withdraw->payment_json = json_encode($response, JSON_UNESCAPED_UNICODE);
  250. $withdraw->save();
  251. return true;
  252. }
  253. throw new ShoproException(json_encode($response, JSON_UNESCAPED_UNICODE));
  254. } catch (HttpResponseException $e) {
  255. $data = $e->getResponse()->getData();
  256. $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
  257. throw new ShoproException($message);
  258. } catch (\Exception $e) {
  259. \think\Log::error('提现失败:' . ' 行号:' . $e->getLine() . '文件:' . $e->getFile() . '错误信息:' . $e->getMessage());
  260. $this->handleLog($withdraw, '提现失败:' . $e->getMessage());
  261. throw new ShoproException($e->getMessage()); // 弹出错误信息
  262. }
  263. return false;
  264. }
  265. private function handleLog($withdraw, $oper_info, $oper = null)
  266. {
  267. $oper = Operator::get($oper);
  268. WithdrawLogModel::insert([
  269. 'withdraw_id' => $withdraw->id,
  270. 'content' => $oper_info,
  271. 'oper_type' => $oper['type'],
  272. 'oper_id' => $oper['id'],
  273. 'createtime' => time()
  274. ]);
  275. return $withdraw;
  276. }
  277. }