PaymentOrderService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. namespace App\Services;
  3. use App\Services\BaseService;
  4. use App\Models\PaymentOrder;
  5. use App\Models\Config;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Services\Payment\QianBaoService;
  11. use App\Services\Payment\SanJinService;
  12. use App\Services\WalletService;
  13. use App\Services\BalanceLogService;
  14. /**
  15. * 投注
  16. */
  17. class PaymentOrderService extends BaseService
  18. {
  19. const TYPE_PAY = 1; // 代收
  20. const TYPE_PAYOUT = 2; // 代付
  21. const STATUS_STAY = 0; // 待处理
  22. const STATUS_PROCESS = 1; // 处理中
  23. const STATUS_SUCCESS = 2; // 成功
  24. const STATUS_FAIL = 3; // 失败
  25. /**
  26. * @description: 模型
  27. * @return {string}
  28. */
  29. public static function model() :string
  30. {
  31. return PaymentOrder::class;
  32. }
  33. /**
  34. * @description: 枚举
  35. * @return {*}
  36. */
  37. public static function enum() :string
  38. {
  39. return '';
  40. }
  41. /**
  42. * @description: 获取查询条件
  43. * @param {array} $search 查询内容
  44. * @return {array}
  45. */
  46. public static function getWhere(array $search = []) :array
  47. {
  48. $where = [];
  49. if(isset($search['member_id']) && !empty($search['member_id'])){
  50. $where[] = ['member_id', '=', $search['member_id']];
  51. }
  52. if(isset($search['type']) && !empty($search['type'])){
  53. $where[] = ['type', '=', $search['type']];
  54. }
  55. if(isset($search['channel']) && !empty($search['channel'])){
  56. $where[] = ['channel', '=', $search['channel']];
  57. }
  58. if(isset($search['order_no']) && !empty($search['order_no'])){
  59. $where[] = ['order_no', '=', $search['order_no']];
  60. }
  61. if(isset($search['id']) && !empty($search['id'])){
  62. $where[] = ['id', '=', $search['id']];
  63. }
  64. if(isset($search['status']) && $search['status'] != ''){
  65. $where[] = ['status', '=', $search['status']];
  66. }
  67. return $where;
  68. }
  69. /**
  70. * @description: 查询单条数据
  71. * @param array $search
  72. * @return \App\Models\Coin|null
  73. */
  74. public static function findOne(array $search): ?PaymentOrder
  75. {
  76. return self::model()::where(self::getWhere($search))->first();
  77. }
  78. /**
  79. * @description: 查询所有数据
  80. * @param array $search
  81. * @return \Illuminate\Database\Eloquent\Collection
  82. */
  83. public static function findAll(array $search = [])
  84. {
  85. return self::model()::where(self::getWhere($search))->get();
  86. }
  87. /**
  88. * @description: 分页查询
  89. * @param array $search
  90. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  91. */
  92. public static function paginate(array $search = [])
  93. {
  94. $limit = isset($search['limit'])?$search['limit']:15;
  95. $paginator = self::model()::where(self::getWhere($search))->paginate($limit);
  96. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  97. }
  98. /**
  99. * @description:
  100. * @param {*} $params
  101. * @return {*}
  102. */
  103. public static function submit($params = [])
  104. {
  105. $result = false;
  106. $msg['code'] = self::NOT;
  107. $msg['msg'] = '';
  108. // 2. 判断是否是更新
  109. if (!empty($params['id'])) {
  110. // 更新
  111. $info = self::findOne(['id'=>$params['id']] );
  112. if (!$info) {
  113. $msg['msg'] = '数据不存在!';
  114. }else{
  115. $result = $info->update($params);
  116. $id = $params['id'];
  117. }
  118. } else {
  119. // 创建
  120. $result = $info = self::model()::create($params);
  121. $id = $result->id;
  122. }
  123. if($result){
  124. $msg['code'] = self::YES;
  125. $msg['msg'] = '设置成功';
  126. $msg['key'] = $id;
  127. }else{
  128. $msg['msg'] = empty($msg['msg']) ?'操作失败':$msg['msg'];
  129. }
  130. return $msg;
  131. }
  132. /**
  133. * @description: 创建代收订单
  134. * @param {*} $memberId
  135. * @param {*} $amount
  136. * @param {*} $paymentType 支付类型:支付宝、数字人民币
  137. * @return {*}
  138. */
  139. public static function createPay($memberId,$amount,$paymentType)
  140. {
  141. $result = [];
  142. $result['chat_id'] = $memberId;
  143. $channel = ''; // 支付的通道
  144. $product = SanJinService::$PRODUCT;
  145. $max = 0;
  146. $min = 0;
  147. $rate = 0;
  148. foreach($product as $k => $v){
  149. if($v['type'] == $paymentType){
  150. if($amount >= $v['min'] && $amount <= $v['max']){
  151. $channel = $k;
  152. $rate = $v['rate'];
  153. }
  154. if($min == 0){
  155. $min = $v['min'];
  156. }
  157. if($max == 0){
  158. $max = $v['max'];
  159. }
  160. if($min > $v['min']){
  161. $min = $v['min'];
  162. }
  163. if($max < $v['max']){
  164. $max = $v['max'];
  165. }
  166. }
  167. }
  168. // 没有找到支付通道
  169. if(empty($channel)){
  170. $text = "发起充值失败 \n";
  171. $text .= "最低充值:".$min." \n";
  172. $text .= "最高充值:".$max." \n";
  173. $text .= "请重新填写充值的金额!";
  174. $result['text'] = $text;
  175. return $result;
  176. }
  177. $data = [];
  178. $data['type'] = self::TYPE_PAY;
  179. $data['member_id'] = $memberId;
  180. $data['amount'] = $amount;
  181. $data['channel'] = $channel;
  182. $data['fee'] = $amount * $rate;
  183. $order_no = self::createOrderNo('sj'.$data['type'].'_', $memberId);
  184. $data['order_no'] = $order_no;
  185. $data['callback_url'] = SanJinService::getNotifyUrl();
  186. $data['remark'] = '充值费率:'.$rate;
  187. $data['status'] = self::STATUS_STAY;
  188. $ret = SanJinService::pay(($amount*100), $order_no, $channel);
  189. if($ret['code'] == 0){
  190. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  191. $result['image'] = $qrCode;
  192. $item = $ret['data'];
  193. $data['status'] = self::STATUS_PROCESS;
  194. $data['pay_no'] = $item['tradeNo'];
  195. $data['pay_url'] = $item['payUrl'];
  196. $data['pay_data'] = json_encode($ret,JSON_UNESCAPED_UNICODE);
  197. $info = self::model()::create($data);
  198. $text = "✅ 支付提示 \n";
  199. $text .= "请扫码支付 \n";
  200. $text .= "支付金额:".$amount." RMB \n";
  201. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  202. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  203. $result['text'] = $text;
  204. }else{
  205. $result['text'] = $ret['message'];
  206. }
  207. return $result;
  208. }
  209. /**
  210. * @description: 接收支付的通知
  211. * @param {*} $params
  212. * @return {*}
  213. */
  214. public static function receivePay($params)
  215. {
  216. // 判断商户号
  217. if($params['mchId'] == SanJinService::getMerchantId()){
  218. $must = ['mchId','productId','tradeNo','outTradeNo','amount','payAmount','state','createTime','payTime'];
  219. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  220. if($info){
  221. // 平台以分计算转成元
  222. $payAmount = $params['payAmount'] / 100;
  223. // 判断金额是不是正确认
  224. if($info->amount != $payAmount){
  225. $text = '❌ 支付失败提醒 \n';
  226. $text .= "订单金额:{$info->amount} \n";
  227. $text .= "实际支付:{$payAmount} \n";
  228. $text .= "订单号:{$params['outTradeNo']} \n";
  229. $text .= "失败原因:支付金额与订单金额不一致 \n";
  230. $text .= "请联系客服处理!";
  231. self::sendMessage($info->member_id,$text);
  232. return false;
  233. }
  234. if($params['sign'] != SanJinService::signature($params,$must)){
  235. return false;
  236. }
  237. if($info->status != self::STATUS_PROCESS){
  238. return false;
  239. }
  240. // 付款
  241. if($info->type == self::TYPE_PAY){
  242. if($params['state'] == 1){
  243. $info->status = self::STATUS_SUCCESS;
  244. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  245. $balance = $wallet->available_balance;
  246. $available_balance = bcadd($balance,$payAmount,10);
  247. $wallet->available_balance = $available_balance;
  248. $wallet->save();
  249. // 记录余额变动日志
  250. BalanceLogService::addLog(
  251. $info->member_id,
  252. $payAmount,
  253. $balance,
  254. $available_balance,
  255. '三方充值',
  256. $info->id,
  257. ''
  258. );
  259. $text = "✅ 支付成功 \n";
  260. $text .= "充值金额:{$payAmount} RMB \n";
  261. $text .= "订单号:{$params['outTradeNo']} \n";
  262. $text .= "您充值的金额已到账,请注意查收!";
  263. self::sendMessage($info->member_id,$text);
  264. }else{
  265. $info->status = self::STATUS_FAIL;
  266. $text = "❌ 支付失败 \n";
  267. $text .= "充值金额:{$payAmount} RMB \n";
  268. $text .= "订单号:{$params['outTradeNo']} \n";
  269. }
  270. $info->save();
  271. return true;
  272. }
  273. }
  274. }
  275. }
  276. /**
  277. * @description: 创建代付订单
  278. * @param {*} $memberId 会员
  279. * @param {*} $amount 金额
  280. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  281. * @param {*} $bank_name 银行名称/支付宝
  282. * @param {*} $account 姓名
  283. * @param {*} $card_no 银行卡号/支付宝账号
  284. * @return {*}
  285. */
  286. public static function createPayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  287. {
  288. $default_amount = $amount;
  289. $result = [];
  290. $result['chat_id'] = $memberId;
  291. if($amount < 100){
  292. $result['text'] = '提现金额最少100';
  293. return $result;
  294. }
  295. if($amount > 49999){
  296. $result['text'] = '提现金额最多49999';
  297. return $result;
  298. }
  299. // 在调用三方支付前开始事务
  300. DB::beginTransaction();
  301. try {
  302. $wallet = WalletService::findOne(['member_id' => $memberId]);
  303. if (!$wallet) {
  304. $result['text'] = '钱包不存在!';
  305. return $result;
  306. }
  307. $balance = $wallet->available_balance;
  308. if (bccomp($balance, $amount, 2) < 0) {
  309. $result['text'] = '您的钱包余额不足!';
  310. return $result;
  311. }
  312. $available_balance = bcsub($balance, $amount, 10);
  313. $data = [];
  314. $data['type'] = self::TYPE_PAYOUT;
  315. $order_no = self::createOrderNo('sj'.$data['type'].'_', $memberId);
  316. $data['order_no'] = $order_no;
  317. $data['member_id'] = $memberId;
  318. $data['fee'] = $amount * 0.002 + 2;
  319. $amount = number_format($amount, 2, '.', '');
  320. $data['amount'] = $amount;
  321. $data['channel'] = $channel;
  322. $data['bank_name'] = $bank_name;
  323. $data['account'] = $account;
  324. $data['card_no'] = $card_no;
  325. $data['callback_url'] = QianBaoService::getNotifyUrl();
  326. $data['status'] = self::STATUS_STAY;
  327. $data['remark'] = '提现费率:0.2%+2';
  328. // 先预扣款(锁定资金)
  329. $wallet->available_balance = $available_balance;
  330. if (!$wallet->save()) {
  331. DB::rollBack();
  332. $result['text'] = '钱包更新失败!';
  333. return $result;
  334. }
  335. // 创建待处理状态的提现记录
  336. $info = self::model()::create($data);
  337. $id = $info->id;
  338. // 记录余额变动日志
  339. BalanceLogService::addLog(
  340. $memberId,
  341. $default_amount,
  342. $balance,
  343. $available_balance,
  344. '三方提现',
  345. $id,
  346. '钱宝提现费率:0.2%+2'
  347. );
  348. // 提交事务,确保预扣款成功
  349. DB::commit();
  350. } catch (\Exception $e) {
  351. // 预扣款失败,回滚事务
  352. DB::rollBack();
  353. $result['text'] = '系统繁忙,请稍后重试!';
  354. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  355. 'member_id' => $memberId,
  356. 'amount' => $amount
  357. ]);
  358. return $result;
  359. }
  360. // 调用三方支付接口(在事务外)
  361. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  362. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  363. if ($ret['code'] == 200) {
  364. // 更新提现记录状态为处理中
  365. DB::beginTransaction();
  366. try {
  367. $info->status = self::STATUS_PROCESS;
  368. $info->save();
  369. DB::commit();
  370. $text = "✅ 提现申请已提交!\n\n";
  371. $text .= "钱包余额:{$available_balance} RMB\n";
  372. $text .= "提现金额:{$default_amount} RMB\n";
  373. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  374. $result['text'] = $text;
  375. } catch (\Exception $e) {
  376. DB::rollBack();
  377. // 状态更新失败,但资金已扣款且三方支付已成功
  378. // 这里可以记录告警,需要人工干预
  379. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  380. 'member_id' => $memberId,
  381. 'order_no' => $order_no
  382. ]);
  383. $result['text'] = '提现申请已提交,系统处理中...';
  384. }
  385. } else {
  386. // 三方支付失败,需要回滚之前的预扣款
  387. DB::beginTransaction();
  388. try {
  389. // 恢复钱包余额
  390. $wallet->available_balance = $balance;
  391. $wallet->save();
  392. // 更新提现记录状态为失败
  393. $info->status = self::STATUS_FAIL;
  394. $info->remark = $ret['msg'];
  395. $info->save();
  396. // 记录退款日志
  397. BalanceLogService::addLog(
  398. $memberId,
  399. $default_amount,
  400. $available_balance,
  401. $balance,
  402. '三方提现',
  403. $id,
  404. '提现失败退款'
  405. );
  406. DB::commit();
  407. $result['text'] = $ret['msg'];
  408. } catch (\Exception $e) {
  409. DB::rollBack();
  410. // 回滚失败,需要记录告警,人工干预
  411. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  412. 'member_id' => $memberId,
  413. 'order_no' => $order_no,
  414. 'amount' => $amount
  415. ]);
  416. $result['text'] = '提现失败,请联系客服处理退款!';
  417. }
  418. }
  419. return $result;
  420. }
  421. /**
  422. * @description: 接收三方订单
  423. * @param {*} $params
  424. * @return {*}
  425. */
  426. public static function receiveOrder($params)
  427. {
  428. // 判断商户号是否一致
  429. if($params['merchantNum'] == QianBaoService::getMerchantId()){
  430. $info = self::findOne(['order_no' => $params['orderNo']]);
  431. if($info){
  432. // 判断金额是不是正确认
  433. if($info->amount != $params['amount']){
  434. return false;
  435. }
  436. // 验证签名
  437. $sign = QianBaoService::verifyNotifySign($params['state'],$params['orderNo'],$params['amount']);
  438. if($params['sign'] != $sign){
  439. return false;
  440. }
  441. // 代付
  442. if($info->type == self::TYPE_PAYOUT){
  443. self::onSubmitPayout($params,$info);
  444. }
  445. // 代收
  446. if($info->type == self::TYPE_PAY){
  447. }
  448. }
  449. }
  450. }
  451. /**
  452. * @description: 处理代付订单
  453. * @param {*} $params
  454. * @return {*}
  455. */
  456. public static function onSubmitPayout($params,$info)
  457. {
  458. $memberId = $info->member_id;
  459. $amount = $params['amount'];
  460. $data = [];
  461. $result = [];
  462. $chat_id = $info->member_id;
  463. $data['callback_data'] =json_encode($params,JSON_UNESCAPED_UNICODE);
  464. DB::beginTransaction();
  465. try{
  466. if($params['state'] == 1){
  467. $data['status'] = self::STATUS_SUCCESS;
  468. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  469. if($res){
  470. DB::commit();
  471. $text = "✅ 提现通知 \n";
  472. $text .= "提现平台:{$info->bank_name} \n";
  473. $text .= "收款人:{$info->account} \n";
  474. $text .= "收款卡号:{$info->card_no} \n";
  475. $text .= "提现金额:{$info->amount} \n";
  476. $text .= "提现成功,金额已到账,请注意查收!";
  477. self::sendMessage($chat_id,$text);
  478. }
  479. }else{
  480. $data['status'] = self::STATUS_FAIL;
  481. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  482. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  483. $balance = $wallet->available_balance; // 钱包当前余额
  484. $available_balance = bcadd($balance, $params['amount'], 10);
  485. $wallet->available_balance = $available_balance;
  486. $wallet->save();
  487. // 记录退款日志
  488. BalanceLogService::addLog(
  489. $memberId,
  490. $amount,
  491. $balance,
  492. $available_balance,
  493. '三方提现',
  494. $info->id,
  495. '提现失败退款'
  496. );
  497. if($res){
  498. DB::commit();
  499. $text = "❌ 提现通知 \n";
  500. $text .= "提现平台:{$info->bank_name} \n";
  501. $text .= "收款人:{$info->account} \n";
  502. $text .= "收款卡号:{$info->card_no} \n";
  503. $text .= "提现金额:{$info->amount} \n";
  504. $text .= "提现失败,金额已返回钱包,请注意查收!";
  505. self::sendMessage($chat_id,$text);
  506. }
  507. }
  508. }catch(\Exception $e){
  509. DB::rollBack();
  510. // 回滚失败,需要记录告警,人工干预
  511. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  512. }
  513. }
  514. }