PaymentOrderService.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\PaymentOrder;
  5. use Exception;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Services\Payment\JdPayService;
  9. use App\Services\Payment\QianBaoService;
  10. use App\Services\Payment\SanJinService;
  11. use App\Services\ConfigService;
  12. /**
  13. * 投注
  14. */
  15. class PaymentOrderService extends BaseService
  16. {
  17. const TYPE_PAY = 1; // 代收
  18. const TYPE_PAYOUT = 2; // 代付
  19. const TYPE_SELF_PAY = 3; // 手动充值
  20. const TYPE_SELF_PAYOUT = 4; // 手动提现打款
  21. const STATUS_STAY = 0; // 待处理
  22. const STATUS_PROCESS = 1; // 处理中
  23. const STATUS_SUCCESS = 2; // 成功
  24. const STATUS_FAIL = 3; // 失败
  25. const STATUS_USER = 4; // 待用户提交凭证
  26. const STATUS_AUDIT = 5; //待人工审核
  27. const STATUS_CANCEL = 6; //已撤回
  28. public static string $MODEL = PaymentOrder::class;
  29. /**
  30. * @description: 模型
  31. * @return {string}
  32. */
  33. public static function model(): string
  34. {
  35. return PaymentOrder::class;
  36. }
  37. /**
  38. * @description: 枚举
  39. * @return {*}
  40. */
  41. public static function enum(): string
  42. {
  43. return '';
  44. }
  45. /**
  46. * @description: 获取查询条件
  47. * @param {array} $search 查询内容
  48. * @return {array}
  49. */
  50. public static function getWhere(array $search = []): array
  51. {
  52. $where = [];
  53. if (isset($search['member_id']) && !empty($search['member_id'])) {
  54. $where[] = ['payment_orders.member_id', '=', $search['member_id']];
  55. }
  56. if (isset($search['channel']) && !empty($search['channel'])) {
  57. if ($search['channel'] == 'rgcz') {
  58. $search['type'] = 3;
  59. }
  60. $where[] = ['payment_orders.channel', '=', $search['channel']];
  61. }
  62. if (isset($search['type']) && !empty($search['type'])) {
  63. $where[] = ['payment_orders.type', '=', $search['type']];
  64. }
  65. if (isset($search['order_no']) && !empty($search['order_no'])) {
  66. $where[] = ['payment_orders.order_no', '=', $search['order_no']];
  67. }
  68. if (isset($search['id']) && !empty($search['id'])) {
  69. $where[] = ['payment_orders.id', '=', $search['id']];
  70. }
  71. if (isset($search['status']) && $search['status'] != '') {
  72. $where[] = ['payment_orders.status', '=', $search['status']];
  73. }
  74. if (isset($search['first_name']) && !empty($search['first_name'])) {
  75. $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
  76. }
  77. if (isset($search['payment_type']) && $search['payment_type'] != '') {
  78. $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
  79. }
  80. return $where;
  81. }
  82. /**
  83. * @description: 查询单条数据
  84. * @param array $search
  85. * @return \App\Models\Coin|null
  86. */
  87. public static function findOne(array $search): ?PaymentOrder
  88. {
  89. return static::$MODEL::where(self::getWhere($search))->first();
  90. }
  91. /**
  92. * @description: 查询所有数据
  93. * @param array $search
  94. * @return \Illuminate\Database\Eloquent\Collection
  95. */
  96. public static function findAll(array $search = [])
  97. {
  98. return static::$MODEL::where(self::getWhere($search))->get();
  99. }
  100. /**
  101. * @description: 分页查询
  102. * @param array $search
  103. * @return array
  104. */
  105. public static function paginate(array $search = [])
  106. {
  107. $limit = isset($search['limit']) ? $search['limit'] : 15;
  108. $paginator = static::$MODEL::where(self::getWhere($search))
  109. ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
  110. ->select("payment_orders.*", "users.first_name","users.admin_note as user_admin_note") // 提前查好需要的字段
  111. ->orderByDesc('payment_orders.created_at')
  112. ->paginate($limit);
  113. $totalAmount = 0;
  114. $totalSuccess = 0;
  115. $totalFail = 0;
  116. $list = $paginator->items();
  117. foreach ($list as $item) {
  118. $item['amount'] = floatval($item['amount']);
  119. $totalAmount += $item['amount'];
  120. if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
  121. if ($item['status'] == 3) $totalFail += $item['amount'];
  122. }
  123. return [
  124. 'total' => $paginator->total(),
  125. 'total_amount' => $totalAmount,
  126. 'total_success' => $totalSuccess,
  127. 'total_fail' => $totalFail,
  128. 'data' => $list
  129. ];
  130. }
  131. /**
  132. * @description:
  133. * @param {*} $params
  134. * @return {*}
  135. */
  136. public static function submit($params = [])
  137. {
  138. $result = false;
  139. $msg['code'] = self::NOT;
  140. $msg['msg'] = '';
  141. // 2. 判断是否是更新
  142. if (!empty($params['id'])) {
  143. // 更新
  144. $info = self::findOne(['id' => $params['id']]);
  145. if (!$info) {
  146. $msg['msg'] = '数据不存在!';
  147. } else {
  148. $result = $info->update($params);
  149. $id = $params['id'];
  150. }
  151. } else {
  152. // 创建
  153. $result = $info = static::$MODEL::create($params);
  154. $id = $result->id;
  155. }
  156. if ($result) {
  157. $msg['code'] = self::YES;
  158. $msg['msg'] = '设置成功';
  159. $msg['key'] = $id;
  160. } else {
  161. $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
  162. }
  163. return $msg;
  164. }
  165. /**
  166. * @description: 创建代收订单
  167. * @param {*} $memberId
  168. * @param {*} $amount
  169. * @param {*} $paymentType 支付类型:支付宝、数字人民币
  170. * @return {*}
  171. */
  172. public static function createPay($memberId, $amount, $paymentType)
  173. {
  174. $result = [];
  175. $result['chat_id'] = $memberId;
  176. $result['code'] = 0;
  177. $result['url'] = '';
  178. $channel = ''; // 支付的通道
  179. $product = SanJinService::product();
  180. $max = 0;
  181. $min = 0;
  182. $rate = 0;
  183. $selectedProduct = null;
  184. $geText = '';
  185. foreach ($product as $k => $v) {
  186. if ($v['type'] == $paymentType) {
  187. $selectedProduct = $v;
  188. if ($v['type'] == 'zfbge') {
  189. if (in_array($amount, $v['fixed'])) {
  190. $channel = $k;
  191. } else {
  192. $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请务必输入区间金额!";
  193. }
  194. } else {
  195. if ($amount >= $v['min'] && $amount <= $v['max']) {
  196. $channel = $k;
  197. $rate = $v['rate'];
  198. }
  199. if ($min == 0) {
  200. $min = $v['min'];
  201. }
  202. if ($max == 0) {
  203. $max = $v['max'];
  204. }
  205. if ($min > $v['min']) {
  206. $min = $v['min'];
  207. }
  208. if ($max < $v['max']) {
  209. $max = $v['max'];
  210. }
  211. }
  212. }
  213. }
  214. // 没有找到支付通道
  215. if (empty($channel) && !JdPayService::isChannel($paymentType)) {
  216. // $text = "发起充值失败 \n";
  217. // $text .= "最低充值:" . $min . " \n";
  218. // $text .= "最高充值:" . $max . " \n";
  219. // $text .= "请重新填写充值的金额!";
  220. $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
  221. $result['text'] = $text;
  222. if ($geText) {
  223. $result['text'] = $geText;
  224. }
  225. $result['code'] = 20001;
  226. return $result;
  227. }
  228. if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
  229. $channel = JdPayService::CHANNEL;
  230. $bankName = $selectedProduct['name'] ?? 'JD钱包';
  231. $data = [];
  232. $data['type'] = self::TYPE_PAY;
  233. $data['member_id'] = $memberId;
  234. $data['amount'] = JdPayService::amount($amount);
  235. $data['channel'] = $channel;
  236. $data['fee'] = $amount * $rate;
  237. $data['bank_name'] = $bankName;
  238. $order_no = self::createOrderNo('jd' . $data['type'] . '_', $memberId);
  239. $data['order_no'] = $order_no;
  240. $data['callback_url'] = JdPayService::getNotifyUrl();
  241. $data['remark'] = '充值费率:' . $rate;
  242. $data['status'] = self::STATUS_STAY;
  243. $ret = JdPayService::pay($amount, $order_no);
  244. Log::channel('payment')->info('JD支付发起', $ret);
  245. if (($ret['code'] ?? 0) == 200) {
  246. $item = $ret['data'] ?? [];
  247. $payUrl = $item['url'] ?? '';
  248. $data['status'] = self::STATUS_PROCESS;
  249. $data['pay_no'] = $item['orderNo'] ?? '';
  250. $data['pay_url'] = $payUrl;
  251. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  252. static::$MODEL::create($data);
  253. if ($payUrl) {
  254. $result['image'] = asset(self::createPaymentQrCode($payUrl));
  255. }
  256. $text = "{$bankName}充值确认 \n";
  257. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  258. $text .= "支付地址:{$payUrl}\n";
  259. $text .= "支付金额:" . $amount . " RMB \n";
  260. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  261. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  262. $result['text'] = $text;
  263. $result['url'] = $payUrl;
  264. } else {
  265. $result['text'] = $ret['message'] ?? 'JD支付发起失败';
  266. $result['code'] = 20002;
  267. }
  268. return $result;
  269. }
  270. $data = [];
  271. $data['type'] = self::TYPE_PAY;
  272. $data['member_id'] = $memberId;
  273. $data['amount'] = $amount;
  274. $data['channel'] = $channel;
  275. $data['fee'] = $amount * $rate;
  276. $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
  277. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  278. $data['order_no'] = $order_no;
  279. $data['callback_url'] = SanJinService::getNotifyUrl();
  280. $data['remark'] = '充值费率:' . $rate;
  281. $data['status'] = self::STATUS_STAY;
  282. $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
  283. Log::error('三斤支付发起:', $ret);
  284. if ($ret['code'] == 0) {
  285. $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
  286. $result['image'] = $qrCode;
  287. $item = $ret['data'];
  288. $data['status'] = self::STATUS_PROCESS;
  289. $data['pay_no'] = $item['tradeNo'];
  290. $data['pay_url'] = $item['payUrl'];
  291. $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
  292. $info = static::$MODEL::create($data);
  293. // $text = "✅ 支付提示 \n";
  294. $text = "{$data['bank_name']}充值确认 \n";
  295. // $text .= "支付方式:{$data['bank_name']} \n";
  296. $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
  297. $text .= "支付地址:{$ret['data']['payUrl']}\n";
  298. $text .= "支付金额:" . $amount . " RMB \n";
  299. $text .= "请按实际支付金额进行付款,否则影响到账 \n";
  300. $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
  301. $result['text'] = $text;
  302. $result['url'] = $ret['data']['payUrl'];
  303. } else {
  304. $result['text'] = $ret['message'];
  305. $result['code'] = 20002;
  306. }
  307. return $result;
  308. }
  309. /**
  310. * @description: 接收支付的通知
  311. * @param {*} $params
  312. * @return {*}
  313. */
  314. public static function receivePay($params)
  315. {
  316. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  317. $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
  318. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  319. if (!$info || $info->type != self::TYPE_PAY) {
  320. return false;
  321. }
  322. if (!JdPayService::verifyPayNotify($params)) {
  323. return false;
  324. }
  325. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  326. return false;
  327. }
  328. if ($info->status != self::STATUS_PROCESS) {
  329. return true;
  330. }
  331. $info->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
  332. $info->state = $params['status'];
  333. if ((string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
  334. $info->status = self::STATUS_SUCCESS;
  335. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  336. $balance = $wallet->available_balance;
  337. $available_balance = bcadd($balance, JdPayService::amount($info->amount), 10);
  338. $wallet->available_balance = $available_balance;
  339. $wallet->save();
  340. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  341. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  342. $text = "✅ 支付成功 \n";
  343. $text .= "充值金额:{$info->amount} RMB \n";
  344. $text .= "订单号:{$info->order_no} \n";
  345. $text .= "您充值的金额已到账,请注意查收!";
  346. self::sendMessage($info->member_id, $text);
  347. } elseif ((string)$params['status'] === JdPayService::PAY_STATUS_FAIL) {
  348. $info->status = self::STATUS_FAIL;
  349. }
  350. $info->save();
  351. return true;
  352. }
  353. // 判断商户号
  354. if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
  355. $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
  356. $info = self::findOne(['order_no' => $params['outTradeNo']]);
  357. if ($info) {
  358. // 平台以分计算转成元
  359. $payAmount = $params['payAmount'] / 100;
  360. // 判断金额是不是正确认
  361. if ($info->amount != $payAmount) {
  362. $text = '❌ 支付失败提醒 \n';
  363. $text .= "订单金额:{$info->amount} \n";
  364. $text .= "实际支付:{$payAmount} \n";
  365. $text .= "订单号:{$params['outTradeNo']} \n";
  366. $text .= "失败原因:支付金额与订单金额不一致 \n";
  367. $text .= "请联系客服处理!";
  368. self::sendMessage($info->member_id, $text);
  369. return false;
  370. }
  371. if ($params['sign'] != SanJinService::signature($params, $must)) {
  372. return false;
  373. }
  374. if ($info->status != self::STATUS_PROCESS) {
  375. return false;
  376. }
  377. // 付款
  378. if ($info->type == self::TYPE_PAY) {
  379. $info->state = $params['state'];
  380. if ($params['state'] == 1) {
  381. $info->status = self::STATUS_SUCCESS;
  382. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  383. $balance = $wallet->available_balance;
  384. $available_balance = bcadd($balance, $payAmount, 10);
  385. $wallet->available_balance = $available_balance;
  386. $wallet->save();
  387. // 记录余额变动日志
  388. BalanceLogService::addLog($info->member_id, $payAmount, $balance, $available_balance, '三方充值', $info->id, '');
  389. self::rechargesBibiReturn($info->member_id, $payAmount, $info->id);
  390. $text = "✅ 支付成功 \n";
  391. $text .= "充值金额:{$payAmount} RMB \n";
  392. $text .= "订单号:{$params['outTradeNo']} \n";
  393. $text .= "您充值的金额已到账,请注意查收!";
  394. self::sendMessage($info->member_id, $text);
  395. } else {
  396. $info->status = self::STATUS_FAIL;
  397. $text = "❌ 支付失败 \n";
  398. $text .= "充值金额:{$payAmount} RMB \n";
  399. $text .= "订单号:{$params['outTradeNo']} \n";
  400. }
  401. $info->save();
  402. return true;
  403. }
  404. }
  405. }
  406. }
  407. // 充值笔笔返
  408. public static function rechargesBibiReturn($memberId,$payAmount,$info_id)
  409. {
  410. $rate = ConfigService::getVal('recharges_bibi_return');
  411. $amount = $payAmount * $rate;
  412. if($rate > 0){
  413. $wallet = WalletService::findOne(['member_id' => $memberId]);
  414. $balance = $wallet->available_balance;
  415. $available_balance = bcadd($balance, $amount, 10);
  416. $wallet->available_balance = $available_balance;
  417. $wallet->save();
  418. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '优惠活动', $info_id, '充值笔笔返');
  419. }
  420. }
  421. /**
  422. * 拒绝提现
  423. * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
  424. * @param int $orderId 订单ID PaymentOrder 表的ID
  425. * @param string $remark 失败原因
  426. * @return array
  427. */
  428. public static function withdrawalFailed($orderId, $remark): array
  429. {
  430. try {
  431. $order = PaymentOrder::where('id', $orderId)
  432. ->where('type', 2)
  433. ->where('status', self::STATUS_STAY)
  434. ->first();
  435. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  436. // 更新提现记录状态为失败
  437. $order->status = self::STATUS_FAIL;
  438. $order->remark = $remark;
  439. if (!$order->save()) {
  440. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  441. }
  442. //钱包余额增加
  443. $wallet = WalletService::findOne(['member_id' => $order->member_id]);
  444. $beforeBalance = $wallet->available_balance;
  445. $availableBalance = bcadd($wallet->available_balance, $order->amount, 10);
  446. $wallet->available_balance = $availableBalance;
  447. if (!$wallet->save()) {
  448. throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
  449. }
  450. // 记录退款日志
  451. BalanceLogService::addLog($order->member_id, $order->amount, $beforeBalance, $availableBalance, '三方提现', $order->id, '提现失败退款');
  452. } catch (Exception $e) {
  453. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  454. }
  455. return ['code' => 0, 'msg' => 'ok'];
  456. }
  457. /**
  458. * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
  459. * @param int $orderId PaymentOrder 表的ID
  460. */
  461. public static function createPayout(int $orderId): array
  462. {
  463. try {
  464. $order = PaymentOrder::where('id', $orderId)
  465. ->where('type', 2)
  466. ->where('status', self::STATUS_STAY)
  467. ->first();
  468. if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
  469. $amount = $order->amount;
  470. $amount = number_format($amount, 2, '.', '');
  471. if (JdPayService::isChannel($order->channel)) {
  472. self::assertJdBalanceEnough($amount);
  473. $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
  474. Log::channel('payment')->info('JD下发接口调用', $ret);
  475. if (($ret['code'] ?? 0) != 200) {
  476. throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
  477. }
  478. $order->pay_no = $ret['data']['orderNo'] ?? '';
  479. $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  480. } else {
  481. $ret = QianBaoService::payout($amount, $order->order_no, $order->bank_name, $order->account, $order->card_no);
  482. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  483. if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
  484. }
  485. $order->status = self::STATUS_PROCESS;
  486. $order->save();
  487. } catch (Exception $e) {
  488. return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
  489. }
  490. return ['code' => 0, 'msg' => 'ok'];
  491. }
  492. /**
  493. * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
  494. * @param {*} $memberId 会员ID
  495. * @param {*} $amount 代付金额
  496. * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
  497. * @param {*} $bank_name 银行名称/支付宝
  498. * @param {*} $account 姓名
  499. * @param {*} $card_no 银行卡号/支付宝账号
  500. * @return {*}
  501. */
  502. public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $account, $card_no)
  503. {
  504. $default_amount = $amount;
  505. $result = [];
  506. $result['chat_id'] = $memberId;
  507. if ($amount < 100) {
  508. $result['text'] = '提现金额最少100';
  509. return $result;
  510. }
  511. if ($amount > 49999) {
  512. $result['text'] = '提现金额最多49999';
  513. return $result;
  514. }
  515. // 在调用三方支付前开始事务
  516. DB::beginTransaction();
  517. try {
  518. $wallet = WalletService::findOne(['member_id' => $memberId]);
  519. if (!$wallet) {
  520. $result['text'] = '钱包不存在!';
  521. return $result;
  522. }
  523. $balance = $wallet->available_balance;
  524. if (bccomp($balance, $amount, 2) < 0) {
  525. $result['text'] = '您的钱包余额不足!';
  526. return $result;
  527. }
  528. $available_balance = bcsub($balance, $amount, 10);
  529. $data = [];
  530. $data['type'] = self::TYPE_PAYOUT;
  531. $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
  532. $data['order_no'] = $order_no;
  533. $data['member_id'] = $memberId;
  534. $data['fee'] = $amount * 0.002 + 2;
  535. $amount = number_format($amount, 2, '.', '');
  536. $data['amount'] = $amount;
  537. $data['channel'] = $channel;
  538. $data['bank_name'] = $bank_name;
  539. $data['account'] = $account;
  540. $data['card_no'] = $card_no;
  541. $data['callback_url'] = JdPayService::isChannel($channel) ? JdPayService::getRemitNotifyUrl() : QianBaoService::getNotifyUrl();
  542. $data['status'] = self::STATUS_STAY;
  543. $data['remark'] = '提现费率:0.2%+2';
  544. // 先预扣款(锁定资金)
  545. $wallet->available_balance = $available_balance;
  546. if (!$wallet->save()) {
  547. DB::rollBack();
  548. $result['text'] = '钱包更新失败!';
  549. return $result;
  550. }
  551. // 创建待处理状态的提现记录
  552. $info = static::$MODEL::create($data);
  553. $id = $info->id;
  554. // 记录余额变动日志
  555. BalanceLogService::addLog($memberId, $default_amount * -1, $balance, $available_balance, '三方提现', $id, '钱宝提现费率:0.2%+2');
  556. // 提交事务,确保预扣款成功
  557. DB::commit();
  558. } //
  559. catch (Exception $e) {
  560. // 预扣款失败,回滚事务
  561. DB::rollBack();
  562. $result['text'] = '系统繁忙,请稍后重试!';
  563. Log::error('提现预扣款失败: ' . $e->getMessage(), [
  564. 'member_id' => $memberId,
  565. 'amount' => $amount
  566. ]);
  567. return $result;
  568. }
  569. // 调用三方支付接口(在事务外)
  570. if (JdPayService::isChannel($channel)) {
  571. try {
  572. self::assertJdBalanceEnough($amount);
  573. $ret = JdPayService::remit($amount, $order_no, $card_no);
  574. Log::channel('payment')->info('JD下发接口调用', $ret);
  575. $success = (($ret['code'] ?? 0) == 200);
  576. $failureMessage = $ret['message'] ?? 'JD下发失败';
  577. } catch (Exception $e) {
  578. $ret = ['message' => $e->getMessage()];
  579. $success = false;
  580. $failureMessage = $e->getMessage();
  581. }
  582. } else {
  583. $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no);
  584. Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
  585. $success = (($ret['code'] ?? 0) == 200);
  586. $failureMessage = $ret['msg'] ?? '代付失败';
  587. }
  588. if ($success) {
  589. // 更新提现记录状态为处理中
  590. DB::beginTransaction();
  591. try {
  592. $info->status = self::STATUS_PROCESS;
  593. if (JdPayService::isChannel($channel)) {
  594. $info->pay_no = $ret['data']['orderNo'] ?? '';
  595. $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  596. }
  597. $info->save();
  598. DB::commit();
  599. $text = "✅ 提现申请已提交!\n\n";
  600. $text .= "钱包余额:{$available_balance} RMB\n";
  601. $text .= "提现金额:{$default_amount} RMB\n";
  602. $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
  603. $result['text'] = $text;
  604. } catch (Exception $e) {
  605. DB::rollBack();
  606. // 状态更新失败,但资金已扣款且三方支付已成功
  607. // 这里可以记录告警,需要人工干预
  608. Log::error('提现状态更新失败: ' . $e->getMessage(), [
  609. 'member_id' => $memberId,
  610. 'order_no' => $order_no
  611. ]);
  612. $result['text'] = '提现申请已提交,系统处理中...';
  613. }
  614. } //
  615. else {
  616. // 三方支付失败,需要回滚之前的预扣款
  617. DB::beginTransaction();
  618. try {
  619. // 恢复钱包余额
  620. $wallet->available_balance = $balance;
  621. $wallet->save();
  622. // 更新提现记录状态为失败
  623. $info->status = self::STATUS_FAIL;
  624. $info->remark = $failureMessage;
  625. $info->save();
  626. // 记录退款日志
  627. BalanceLogService::addLog($memberId, $default_amount, $available_balance, $balance, '三方提现', $id, '提现失败退款');
  628. DB::commit();
  629. $result['text'] = $failureMessage;
  630. } catch (Exception $e) {
  631. DB::rollBack();
  632. // 回滚失败,需要记录告警,人工干预
  633. Log::error('提现失败回滚异常: ' . $e->getMessage(), [
  634. 'member_id' => $memberId,
  635. 'order_no' => $order_no,
  636. 'amount' => $amount
  637. ]);
  638. $result['text'] = '提现失败,请联系客服处理退款!';
  639. }
  640. }
  641. return $result;
  642. }
  643. /**
  644. * @description: 接收三方订单
  645. * @param {*} $params
  646. * @return {*}
  647. */
  648. public static function receiveOrder($params)
  649. {
  650. if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
  651. $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
  652. ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
  653. if (!$info || $info->type != self::TYPE_PAYOUT) {
  654. return false;
  655. }
  656. if (!JdPayService::verifyRemitNotify($params)) {
  657. return false;
  658. }
  659. if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
  660. return false;
  661. }
  662. self::onSubmitJdPayout($params, $info);
  663. return true;
  664. }
  665. // 判断商户号是否一致
  666. if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
  667. $info = self::findOne(['order_no' => $params['orderNo']]);
  668. if ($info) {
  669. // 判断金额是不是正确认
  670. if ($info->amount != $params['amount']) {
  671. return false;
  672. }
  673. // 验证签名
  674. $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
  675. if ($params['sign'] != $sign) {
  676. return false;
  677. }
  678. // 代付
  679. if ($info->type == self::TYPE_PAYOUT) {
  680. self::onSubmitPayout($params, $info);
  681. }
  682. // 代收
  683. if ($info->type == self::TYPE_PAY) {
  684. }
  685. }
  686. }
  687. }
  688. /**
  689. * @description: 处理代付订单
  690. * @param {*} $params
  691. * @return {*}
  692. */
  693. public static function onSubmitJdPayout($params, $info)
  694. {
  695. if ($info->status != self::STATUS_PROCESS) {
  696. return;
  697. }
  698. $memberId = $info->member_id;
  699. $amount = JdPayService::amount($params['amount'] ?? $info->amount);
  700. $data = [];
  701. $chat_id = $info->member_id;
  702. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  703. DB::beginTransaction();
  704. try {
  705. if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
  706. $data['status'] = self::STATUS_SUCCESS;
  707. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  708. if ($res) {
  709. $text = "✅ 提现通知 \n";
  710. $text .= "提现平台:{$info->bank_name} \n";
  711. $text .= "收款人:{$info->account} \n";
  712. $text .= "收款地址:{$info->card_no} \n";
  713. $text .= "提现金额:{$info->amount} \n";
  714. $text .= "提现成功,金额已到账,请注意查收!";
  715. self::sendMessage($chat_id, $text);
  716. }
  717. } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
  718. $data['status'] = self::STATUS_FAIL;
  719. $res = static::$MODEL::where(['id' => $info->id])->update($data);
  720. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  721. $balance = $wallet->available_balance;
  722. $available_balance = bcadd($balance, $amount, 10);
  723. $wallet->available_balance = $available_balance;
  724. $wallet->save();
  725. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  726. if ($res) {
  727. $text = "❌ 提现通知 \n";
  728. $text .= "提现平台:{$info->bank_name} \n";
  729. $text .= "收款人:{$info->account} \n";
  730. $text .= "收款地址:{$info->card_no} \n";
  731. $text .= "提现金额:{$info->amount} \n";
  732. $text .= "提现失败,金额已返回钱包,请注意查收!";
  733. self::sendMessage($chat_id, $text);
  734. }
  735. }
  736. DB::commit();
  737. } catch (Exception $e) {
  738. DB::rollBack();
  739. Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
  740. }
  741. }
  742. public static function onSubmitPayout($params, $info)
  743. {
  744. $memberId = $info->member_id;
  745. $amount = $params['amount'];
  746. $data = [];
  747. $result = [];
  748. $chat_id = $info->member_id;
  749. $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
  750. DB::beginTransaction();
  751. try {
  752. if ($params['state'] == 1) {
  753. $data['status'] = self::STATUS_SUCCESS;
  754. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  755. if ($res) {
  756. $text = "✅ 提现通知 \n";
  757. $text .= "提现平台:{$info->bank_name} \n";
  758. $text .= "收款人:{$info->account} \n";
  759. $text .= "收款卡号:{$info->card_no} \n";
  760. $text .= "提现金额:{$info->amount} \n";
  761. $text .= "提现成功,金额已到账,请注意查收!";
  762. self::sendMessage($chat_id, $text);
  763. }
  764. } else {
  765. $data['status'] = self::STATUS_FAIL;
  766. $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
  767. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  768. $balance = $wallet->available_balance; // 钱包当前余额
  769. $available_balance = bcadd($balance, $params['amount'], 10);
  770. $wallet->available_balance = $available_balance;
  771. $wallet->save();
  772. // 记录退款日志
  773. BalanceLogService::addLog($memberId, $amount, $balance, $available_balance, '三方提现', $info->id, '提现失败退款');
  774. if ($res) {
  775. $text = "❌ 提现通知 \n";
  776. $text .= "提现平台:{$info->bank_name} \n";
  777. $text .= "收款人:{$info->account} \n";
  778. $text .= "收款卡号:{$info->card_no} \n";
  779. $text .= "提现金额:{$info->amount} \n";
  780. $text .= "提现失败,金额已返回钱包,请注意查收!";
  781. self::sendMessage($chat_id, $text);
  782. }
  783. }
  784. DB::commit();
  785. } catch (Exception $e) {
  786. DB::rollBack();
  787. // 回滚失败,需要记录告警,人工干预
  788. Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
  789. }
  790. }
  791. /**
  792. * @description: 查询支付订单
  793. * @param {*} $id
  794. * @return {*}
  795. */
  796. public static function singlePayOrder($id)
  797. {
  798. $msg = [];
  799. $msg['code'] = self::NOT;
  800. $info = self::findOne(['id' => $id]);
  801. if ($info && $info->status == self::STATUS_PROCESS) {
  802. if (JdPayService::isChannel($info->channel)) {
  803. $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
  804. Log::channel('payment')->info('JD支付查询订单', $ret);
  805. if (($ret['code'] ?? 0) == 200) {
  806. $item = $ret['data'] ?? [];
  807. if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
  808. $info->status = self::STATUS_SUCCESS;
  809. $info->state = $item['status'];
  810. $info->callback_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
  811. $info->save();
  812. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  813. $balance = $wallet->available_balance;
  814. $available_balance = bcadd($balance, $info->amount, 10);
  815. $wallet->available_balance = $available_balance;
  816. $wallet->save();
  817. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  818. self::rechargesBibiReturn($info->member_id, $info->amount, $info->id);
  819. $msg['code'] = self::YES;
  820. $msg['msg'] = '支付成功';
  821. } else {
  822. $msg['msg'] = '支付中';
  823. }
  824. } else {
  825. $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
  826. }
  827. return $msg;
  828. }
  829. $ret = SanJinService::queryOrder($info->order_no);
  830. Log::error('三斤支付查询订单:', $ret);
  831. if ($ret['code'] == 0) {
  832. $item = [];
  833. $item['state'] = $ret['data']['state'];
  834. if ($ret['data']['state'] == 1) {
  835. $item['status'] = self::STATUS_SUCCESS;
  836. $info->update($item);
  837. $wallet = WalletService::findOne(['member_id' => $info->member_id]);
  838. $balance = $wallet->available_balance;
  839. $available_balance = bcadd($balance, $info->amount, 10);
  840. $wallet->available_balance = $available_balance;
  841. $wallet->save();
  842. // 记录余额变动日志
  843. BalanceLogService::addLog($info->member_id, $info->amount, $balance, $available_balance, '三方充值', $info->id, '');
  844. $msg['code'] = self::YES;
  845. $msg['msg'] = '支付成功';
  846. } else {
  847. $msg['msg'] = '支付中';
  848. }
  849. } else {
  850. $msg['msg'] = '查询失败:' . $ret['message'];
  851. }
  852. } else {
  853. $msg['msg'] = '该状态无法查询';
  854. }
  855. return $msg;
  856. }
  857. private static function assertJdBalanceEnough($amount): void
  858. {
  859. $ret = JdPayService::balance();
  860. Log::channel('payment')->info('JD余额查询', $ret);
  861. if (($ret['code'] ?? 0) != 200) {
  862. throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
  863. }
  864. $balance = $ret['data']['balance'] ?? null;
  865. if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
  866. throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
  867. }
  868. }
  869. public static function syncPayOrder()
  870. {
  871. $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
  872. // foreach($list->toArray() as $k => $v){
  873. // $item= [];
  874. // if($v['status'] == self::STATUS_SUCCESS){
  875. // $item['state'] = 1;
  876. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  877. // }else{
  878. // $ret = SanJinService::queryOrder($v['order_no']);
  879. // var_dump($ret);
  880. // if($ret['code'] == 0){
  881. // $item['state'] = $ret['data']['state'];
  882. // static::$MODEL::where(['id'=>$v['id']])->update($item);
  883. // }
  884. // }
  885. // }
  886. }
  887. }