PaymentOrderService.php 20 KB

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