PaymentOrderService.php 20 KB

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