PaymentOrderService.php 20 KB

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