PaymentOrderService.php 40 KB

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