PaymentOrderService.php 22 KB

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