PaymentOrderService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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::$CHANNEL[$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. if ($ret['code'] == 0) {
  208. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  209. $result['image'] = $qrCode;
  210. $item = $ret['data'];
  211. $data['status'] = self::STATUS_PROCESS;
  212. $data['pay_no'] = $item['tradeNo'];
  213. $data['pay_url'] = $item['payUrl'];
  214. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  215. $info = self::model()::create($data);
  216. $text = "✅ 支付提示 \n";
  217. // $text .= "请扫码支付 \n";
  218. $text .= "支付方式:{$data['bank_name']} \n";
  219. $text .= "请使用浏览器扫码 \n";
  220. $text .= "支付金额:" . $amount . " RMB \n";
  221. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  222. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  223. $result['text'] = $text;
  224. } else {
  225. $result['text'] = $ret['message'];
  226. }
  227. return $result;
  228. }
  229. /**
  230. * @description: 接收支付的通知
  231. * @param {*} $params
  232. * @return {*}
  233. */
  234. public static function receivePay($params)
  235. {
  236. // 判断商户号
  237. if ($params['mchId'] == SanJinService::getMerchantId()) {
  238. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  239. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  240. if ($info) {
  241. // 平台以分计算转成元
  242. $payAmount = $params['payAmount'] / 100;
  243. // 判断金额是不是正确认
  244. if ($info->amount != $payAmount) {
  245. $text = '❌ 支付失败提醒 \n';
  246. $text .= "订单金额:{$info->amount} \n";
  247. $text .= "实际支付:{$payAmount} \n";
  248. $text .= "订单号:{$params['outTradeNo']} \n";
  249. $text .= "失败原因:支付金额与订单金额不一致 \n";
  250. $text .= "请联系客服处理!";
  251. self::sendMessage($info->member_id, $text);
  252. return false;
  253. }
  254. if ($params['sign'] != SanJinService::signature($params, $must)) {
  255. return false;
  256. }
  257. if ($info->status != self::STATUS_PROCESS) {
  258. return false;
  259. }
  260. // 付款
  261. if ($info->type == self::TYPE_PAY) {
  262. if ($params['state'] == 1) {
  263. $info->status = self::STATUS_SUCCESS;
  264. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  265. $balance = $wallet->available_balance;
  266. $available_balance = bcadd($balance, $payAmount, 10);
  267. $wallet->available_balance = $available_balance;
  268. $wallet->save();
  269. // 记录余额变动日志
  270. BalanceLogService::addLog(
  271. $info->member_id,
  272. $payAmount,
  273. $balance,
  274. $available_balance,
  275. '三方充值',
  276. $info->id,
  277. ''
  278. );
  279. $text = "✅ 支付成功 \n";
  280. $text .= "充值金额:{$payAmount} RMB \n";
  281. $text .= "订单号:{$params['outTradeNo']} \n";
  282. $text .= "您充值的金额已到账,请注意查收!";
  283. self::sendMessage($info->member_id, $text);
  284. } else {
  285. $info->status = self::STATUS_FAIL;
  286. $text = "❌ 支付失败 \n";
  287. $text .= "充值金额:{$payAmount} RMB \n";
  288. $text .= "订单号:{$params['outTradeNo']} \n";
  289. }
  290. $info->save();
  291. return true;
  292. }
  293. }
  294. }
  295. }
  296. /**
  297. * @description: 创建代付订单
  298. * @param {*} $memberId 会员
  299. * @param {*} $amount 金额
  300. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  301. * @param {*} $bank_name 银行名称/支付宝
  302. * @param {*} $account 姓名
  303. * @param {*} $card_no 银行卡号/支付宝账号
  304. * @return {*}
  305. */
  306. public static function createPayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  307. {
  308. $default_amount = $amount;
  309. $result = [];
  310. $result['chat_id'] = $memberId;
  311. if ($amount < 100) {
  312. $result['text'] = '提现金额最少100';
  313. return $result;
  314. }
  315. if ($amount > 49999) {
  316. $result['text'] = '提现金额最多49999';
  317. return $result;
  318. }
  319. // 在调用三方支付前开始事务
  320. DB::beginTransaction();
  321. try {
  322. $wallet = WalletService::findOne(['member_id' => $memberId]);
  323. if (!$wallet) {
  324. $result['text'] = '钱包不存在!';
  325. return $result;
  326. }
  327. $balance = $wallet->available_balance;
  328. if (bccomp($balance, $amount, 2) < 0) {
  329. $result['text'] = '您的钱包余额不足!';
  330. return $result;
  331. }
  332. $available_balance = bcsub($balance, $amount, 10);
  333. $data = [];
  334. $data['type'] = self::TYPE_PAYOUT;
  335. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  336. $data['order_no'] = $order_no;
  337. $data['member_id'] = $memberId;
  338. $data['fee'] = $amount * 0.002 + 2;
  339. $amount = number_format($amount, 2, '.', '');
  340. $data['amount'] = $amount;
  341. $data['channel'] = $channel;
  342. $data['bank_name'] = $bank_name;
  343. $data['account'] = $account;
  344. $data['card_no'] = $card_no;
  345. $data['callback_url'] = QianBaoService::getNotifyUrl();
  346. $data['status'] = self::STATUS_STAY;
  347. $data['remark'] = '提现费率:0.2%+2';
  348. // 先预扣款(锁定资金)
  349. $wallet->available_balance = $available_balance;
  350. if (!$wallet->save()) {
  351. DB::rollBack();
  352. $result['text'] = '钱包更新失败!';
  353. return $result;
  354. }
  355. // 创建待处理状态的提现记录
  356. $info = self::model()::create($data);
  357. $id = $info->id;
  358. // 记录余额变动日志
  359. BalanceLogService::addLog(
  360. $memberId,
  361. $default_amount,
  362. $balance,
  363. $available_balance,
  364. '三方提现',
  365. $id,
  366. '钱宝提现费率:0.2%+2'
  367. );
  368. // 提交事务,确保预扣款成功
  369. DB::commit();
  370. } catch (\Exception $e) {
  371. // 预扣款失败,回滚事务
  372. DB::rollBack();
  373. $result['text'] = '系统繁忙,请稍后重试!';
  374. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  375. 'member_id' => $memberId,
  376. 'amount' => $amount
  377. ]);
  378. return $result;
  379. }
  380. // 调用三方支付接口(在事务外)
  381. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  382. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  383. if ($ret['code'] == 200) {
  384. // 更新提现记录状态为处理中
  385. DB::beginTransaction();
  386. try {
  387. $info->status = self::STATUS_PROCESS;
  388. $info->save();
  389. DB::commit();
  390. $text = "✅ 提现申请已提交!\n\n";
  391. $text .= "钱包余额:{$available_balance} RMB\n";
  392. $text .= "提现金额:{$default_amount} RMB\n";
  393. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  394. $result['text'] = $text;
  395. } catch (\Exception $e) {
  396. DB::rollBack();
  397. // 状态更新失败,但资金已扣款且三方支付已成功
  398. // 这里可以记录告警,需要人工干预
  399. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  400. 'member_id' => $memberId,
  401. 'order_no' => $order_no
  402. ]);
  403. $result['text'] = '提现申请已提交,系统处理中...';
  404. }
  405. } else {
  406. // 三方支付失败,需要回滚之前的预扣款
  407. DB::beginTransaction();
  408. try {
  409. // 恢复钱包余额
  410. $wallet->available_balance = $balance;
  411. $wallet->save();
  412. // 更新提现记录状态为失败
  413. $info->status = self::STATUS_FAIL;
  414. $info->remark = $ret['msg'];
  415. $info->save();
  416. // 记录退款日志
  417. BalanceLogService::addLog(
  418. $memberId,
  419. $default_amount,
  420. $available_balance,
  421. $balance,
  422. '三方提现',
  423. $id,
  424. '提现失败退款'
  425. );
  426. DB::commit();
  427. $result['text'] = $ret['msg'];
  428. } catch (\Exception $e) {
  429. DB::rollBack();
  430. // 回滚失败,需要记录告警,人工干预
  431. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  432. 'member_id' => $memberId,
  433. 'order_no' => $order_no,
  434. 'amount' => $amount
  435. ]);
  436. $result['text'] = '提现失败,请联系客服处理退款!';
  437. }
  438. }
  439. return $result;
  440. }
  441. /**
  442. * @description: 接收三方订单
  443. * @param {*} $params
  444. * @return {*}
  445. */
  446. public static function receiveOrder($params)
  447. {
  448. // 判断商户号是否一致
  449. if ($params['merchantNum'] == QianBaoService::getMerchantId()) {
  450. $info = self::findOne(['order_no' => $params['orderNo']]);
  451. if ($info) {
  452. // 判断金额是不是正确认
  453. if ($info->amount != $params['amount']) {
  454. return false;
  455. }
  456. // 验证签名
  457. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  458. if ($params['sign'] != $sign) {
  459. return false;
  460. }
  461. // 代付
  462. if ($info->type == self::TYPE_PAYOUT) {
  463. self::onSubmitPayout($params, $info);
  464. }
  465. // 代收
  466. if ($info->type == self::TYPE_PAY) {
  467. }
  468. }
  469. }
  470. }
  471. /**
  472. * @description: 处理代付订单
  473. * @param {*} $params
  474. * @return {*}
  475. */
  476. public static function onSubmitPayout($params, $info)
  477. {
  478. $memberId = $info->member_id;
  479. $amount = $params['amount'];
  480. $data = [];
  481. $result = [];
  482. $chat_id = $info->member_id;
  483. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  484. DB::beginTransaction();
  485. try {
  486. if ($params['state'] == 1) {
  487. $data['status'] = self::STATUS_SUCCESS;
  488. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  489. if ($res) {
  490. DB::commit();
  491. $text = "✅ 提现通知 \n";
  492. $text .= "提现平台:{$info->bank_name} \n";
  493. $text .= "收款人:{$info->account} \n";
  494. $text .= "收款卡号:{$info->card_no} \n";
  495. $text .= "提现金额:{$info->amount} \n";
  496. $text .= "提现成功,金额已到账,请注意查收!";
  497. self::sendMessage($chat_id, $text);
  498. }
  499. } else {
  500. $data['status'] = self::STATUS_FAIL;
  501. $res = self::model()::where(['order_no' => $params['orderNo']])->update($data);
  502. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  503. $balance = $wallet->available_balance; // 钱包当前余额
  504. $available_balance = bcadd($balance, $params['amount'], 10);
  505. $wallet->available_balance = $available_balance;
  506. $wallet->save();
  507. // 记录退款日志
  508. BalanceLogService::addLog(
  509. $memberId,
  510. $amount,
  511. $balance,
  512. $available_balance,
  513. '三方提现',
  514. $info->id,
  515. '提现失败退款'
  516. );
  517. if ($res) {
  518. DB::commit();
  519. $text = "❌ 提现通知 \n";
  520. $text .= "提现平台:{$info->bank_name} \n";
  521. $text .= "收款人:{$info->account} \n";
  522. $text .= "收款卡号:{$info->card_no} \n";
  523. $text .= "提现金额:{$info->amount} \n";
  524. $text .= "提现失败,金额已返回钱包,请注意查收!";
  525. self::sendMessage($chat_id, $text);
  526. }
  527. }
  528. } catch (\Exception $e) {
  529. DB::rollBack();
  530. // 回滚失败,需要记录告警,人工干预
  531. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  532. }
  533. }
  534. }