PaymentOrderService.php 20 KB

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