PaymentOrderService.php 20 KB

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