| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656 |
- <?php
- namespace App\Services;
- use App\Constants\HttpStatus;
- use App\Models\PaymentOrder;
- use App\Models\RechargeChannel;
- use App\Models\User;
- use App\Models\Wallet as WalletModel;
- use Exception;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use App\Services\Payment\JdPayService;
- use App\Services\Payment\NoPayService;
- use App\Services\Payment\QianBaoService;
- use App\Services\Payment\SanJinService;
- use App\Services\Payment\ZimuPayService;
- use App\Services\Payment\PaymentProviderService;
- use App\Services\ConfigService;
- use App\Services\AdminRealtime\AdminRealtime;
- /**
- * 投注
- */
- class PaymentOrderService extends BaseService
- {
- const TYPE_PAY = 1; // 代收
- const TYPE_PAYOUT = 2; // 代付
- const TYPE_SELF_PAY = 3; // 手动充值
- const TYPE_SELF_PAYOUT = 4; // 手动提现打款
- const STATUS_STAY = 0; // 待处理
- const STATUS_PROCESS = 1; // 处理中
- const STATUS_SUCCESS = 2; // 成功
- const STATUS_FAIL = 3; // 失败
- const STATUS_USER = 4; // 待用户提交凭证
- const STATUS_AUDIT = 5; //待人工审核
- const STATUS_CANCEL = 6; //已撤回
- const STATUS_TIMEOUT = 7; //超时(在线充值处理中超过 PAY_TIMEOUT_MINUTES 未支付,仍可接收迟到的回调)
- const PAY_TIMEOUT_MINUTES = 30;
- const PAY_OPEN_STATUSES = [self::STATUS_PROCESS, self::STATUS_TIMEOUT]; // 在线充值可接收回调/查询入账的状态
- public static string $MODEL = PaymentOrder::class;
- /**
- * @description: 模型
- * @return {string}
- */
- public static function model(): string
- {
- return PaymentOrder::class;
- }
- /**
- * @description: 枚举
- * @return {*}
- */
- public static function enum(): string
- {
- return '';
- }
- /**
- * @description: 获取查询条件
- * @param {array} $search 查询内容
- * @return {array}
- */
- public static function getWhere(array $search = []): array
- {
- $where = [];
- if (isset($search['member_id']) && !empty($search['member_id'])) {
- $where[] = ['payment_orders.member_id', '=', $search['member_id']];
- }
- if (isset($search['channel']) && !empty($search['channel'])) {
- if ($search['channel'] == 'rgcz') {
- $search['type'] = 3;
- }
- $where[] = ['payment_orders.channel', '=', $search['channel']];
-
- }
- if (isset($search['type']) && !empty($search['type'])) {
- $where[] = ['payment_orders.type', '=', $search['type']];
- }
- if (isset($search['order_no']) && !empty($search['order_no'])) {
- $where[] = ['payment_orders.order_no', '=', $search['order_no']];
- }
- if (isset($search['id']) && !empty($search['id'])) {
- $where[] = ['payment_orders.id', '=', $search['id']];
- }
- if (isset($search['status']) && $search['status'] != '') {
- $where[] = ['payment_orders.status', '=', $search['status']];
- }
- if (!empty($search['account'])) {
- $where[] = ['users.account', 'like', '%' . trim((string)$search['account']) . '%'];
- }
- if (isset($search['first_name']) && !empty($search['first_name'])) {
- $where[] = ['users.first_name', 'like', "%" . $search['first_name'] . "%"];
- }
- if (isset($search['payment_type']) && $search['payment_type'] != '') {
- $where[] = ['payment_orders.payment_type', '=', $search['payment_type']];
- }
- return $where;
- }
- /**
- * @description: 查询单条数据
- * @param array $search
- * @return \App\Models\Coin|null
- */
- public static function findOne(array $search): ?PaymentOrder
- {
- return static::$MODEL::where(self::getWhere($search))->first();
- }
- /**
- * @description: 查询所有数据
- * @param array $search
- * @return \Illuminate\Database\Eloquent\Collection
- */
- public static function findAll(array $search = [])
- {
- return static::$MODEL::where(self::getWhere($search))->get();
- }
- /**
- * @description: 分页查询
- * @param array $search
- * @return array
- */
- public static function paginate(array $search = [])
- {
- $limit = isset($search['limit']) ? $search['limit'] : 15;
- $paginator = static::$MODEL::where(self::getWhere($search))
- ->join('users', 'users.member_id', '=', 'payment_orders.member_id')
- ->select("payment_orders.*", "users.first_name", "users.account", "users.admin_note as user_admin_note") // 提前查好需要的字段
- ->orderByDesc('payment_orders.created_at')
- ->paginate($limit);
- $totalAmount = 0;
- $totalSuccess = 0;
- $totalFail = 0;
- $list = $paginator->items();
- foreach ($list as $item) {
- $item['amount'] = floatval($item['amount']);
- $totalAmount += $item['amount'];
- if (in_array($item['status'], [1, 2])) $totalSuccess += $item['amount'];
- if ($item['status'] == 3) $totalFail += $item['amount'];
- }
- return [
- 'total' => $paginator->total(),
- 'total_amount' => $totalAmount,
- 'total_success' => $totalSuccess,
- 'total_fail' => $totalFail,
- 'data' => $list
- ];
- }
- /**
- * @description:
- * @param {*} $params
- * @return {*}
- */
- public static function submit($params = [])
- {
- $result = false;
- $msg['code'] = self::NOT;
- $msg['msg'] = '';
- // 2. 判断是否是更新
- if (!empty($params['id'])) {
- // 更新
- $info = self::findOne(['id' => $params['id']]);
- if (!$info) {
- $msg['msg'] = '数据不存在!';
- } else {
- $result = $info->update($params);
- $id = $params['id'];
- }
- } else {
- // 创建
- $result = $info = static::$MODEL::create($params);
- $id = $result->id;
- }
- if ($result) {
- $msg['code'] = self::YES;
- $msg['msg'] = '设置成功';
- $msg['key'] = $id;
- } else {
- $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
- }
- return $msg;
- }
- /**
- * @description: 创建代收订单
- * @param {*} $memberId
- * @param {*} $amount
- * @param {*} $paymentType 支付类型:支付宝、数字人民币
- * @return {*}
- */
- public static function createPay($memberId, $amount, $paymentType)
- {
- $result = [];
- $result['chat_id'] = $memberId;
- $result['code'] = 0;
- $result['url'] = '';
- if (!PaymentProviderService::requestEnabled((string)$paymentType, 1)) {
- $result['code'] = 20001;
- $result['text'] = '支付公司已禁用';
- return $result;
- }
- $user = User::query()->where('member_id', $memberId)->first();
- $groupId = (int)($user->recharge_channel_group_id ?? 1);
- $channelConfig = RechargeChannel::checkRechargeChannel($paymentType, $groupId);
- if ($channelConfig === false) {
- $result['text'] = '不支持此充值方式';
- $result['code'] = 20001;
- return $result;
- }
- $bonusSnapshot = RechargeBonusService::capture((string)$channelConfig->type, (string)$memberId);
- $channel = ''; // 支付的通道
- $product = SanJinService::product($groupId);
- $max = (float)($channelConfig->max ?? 0);
- $min = (float)($channelConfig->min ?? 0);
- $rate = (float)($channelConfig->rate ?? 0);
- $selectedProduct = null;
- $geText = '';
- foreach ($product as $k => $v) {
- if ($v['type'] == $paymentType) {
- $selectedProduct = $v;
- if ($v['type'] == 'zfbge') {
- if (in_array($amount, $v['fixed'])) {
- $channel = $k;
- } else {
- $geText .= "❌ 此充值通道固定充值金额为" . implode(',', $v['fixed']) . "请选择上述固定金额!";
- }
- } else {
- if ($amount >= $v['min'] && $amount <= $v['max']) {
- $channel = $k;
- $rate = $v['rate'];
- }
- if ($min == 0) {
- $min = $v['min'];
- }
- if ($max == 0) {
- $max = $v['max'];
- }
- if ($min > $v['min']) {
- $min = $v['min'];
- }
- if ($max < $v['max']) {
- $max = $v['max'];
- }
- }
- }
- }
- $isDirectProvider = JdPayService::isChannel($paymentType)
- || NoPayService::isRechargeChannel($paymentType)
- || ZimuPayService::isRechargeChannel($paymentType);
- if ($isDirectProvider && ($amount < $min || ($max > 0 && $amount > $max))) {
- $result['text'] = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
- $result['code'] = 20001;
- return $result;
- }
- // 没有找到支付通道
- if (empty($channel) && !JdPayService::isChannel($paymentType) && !NoPayService::isRechargeChannel($paymentType) && !ZimuPayService::isRechargeChannel($paymentType)) {
- // $text = "发起充值失败 \n";
- // $text .= "最低充值:" . $min . " \n";
- // $text .= "最高充值:" . $max . " \n";
- // $text .= "请重新填写充值的金额!";
- $text = "❌ 此充值通道充值金额{$min}-{$max}请务必输入区间金额!";
- $result['text'] = $text;
- if ($geText) {
- $result['text'] = $geText;
- }
- $result['code'] = 20001;
- return $result;
- }
- if (ZimuPayService::isRechargeChannel($paymentType) || ZimuPayService::isRechargeChannel($channel)) {
- $channel = ZimuPayService::CHANNEL_RECHARGE;
- $bankName = $selectedProduct['name'] ?? '808充值';
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = ZimuPayService::amount($amount);
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = $bankName;
- $order_no = self::createOrderNo('zm' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = ZimuPayService::getPayNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- if ($bonusSnapshot !== null) $data['recharge_bonus_snapshot'] = $bonusSnapshot;
- $data['status'] = self::STATUS_STAY;
- $ret = ZimuPayService::pay($amount, $order_no, (string)$memberId);
- Log::channel('payment')->info('ZIMU支付发起', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $data['amount'],
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? -1) == 0) {
- $item = $ret['data'] ?? [];
- $payUrl = $item['payUrl'] ?? '';
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_no'] = $item['orderNo'] ?? '';
- $data['pay_url'] = $payUrl;
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- static::$MODEL::create($data);
- if ($payUrl) {
- $result['image'] = asset(self::createPaymentQrCode($payUrl));
- }
- $result['text'] = "{$bankName}确认 \n";
- $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $result['text'] .= "支付地址:{$payUrl}\n";
- $result['text'] .= "支付金额:" . $amount . " RMB \n";
- $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['url'] = $payUrl;
- } else {
- $result['text'] = $ret['msg'] ?? 'ZIMU支付发起失败';
- $result['code'] = 20002;
- }
- return $result;
- }
- if (NoPayService::isRechargeChannel($paymentType) || NoPayService::isRechargeChannel($channel)) {
- $channel = NoPayService::isRechargeChannel($paymentType) ? $paymentType : $channel;
- $bankName = $selectedProduct['name'] ?? 'NO快捷充值';
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = NoPayService::amount($amount);
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = $bankName;
- $order_no = self::createOrderNo('no' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = NoPayService::getDepositNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- if ($bonusSnapshot !== null) $data['recharge_bonus_snapshot'] = $bonusSnapshot;
- $data['status'] = self::STATUS_STAY;
- $ret = NoPayService::pay($amount, $order_no, (string)$memberId, $channel);
- Log::channel('payment')->info('NO支付发起', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $data['amount'],
- 'channel' => $channel,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? -1) == 0) {
- $payUrl = $ret['data']['url'] ?? '';
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_url'] = $payUrl;
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- static::$MODEL::create($data);
- if ($payUrl) {
- $result['image'] = asset(self::createPaymentQrCode($payUrl));
- }
- $result['text'] = "{$bankName}充值确认 \n";
- $result['text'] .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $result['text'] .= "支付地址:{$payUrl}\n";
- $result['text'] .= "支付金额:" . $amount . " RMB \n";
- $result['text'] .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['url'] = $payUrl;
- } else {
- $result['text'] = $ret['msg'] ?? 'NO支付发起失败';
- $result['code'] = 20002;
- }
- return $result;
- }
- if (JdPayService::isChannel($paymentType) || JdPayService::isChannel($channel)) {
- $channel = JdPayService::CHANNEL;
- $bankName = $selectedProduct['name'] ?? 'JD钱包';
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = JdPayService::amount($amount);
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = $bankName;
- $order_no = self::createOrderNo('jd' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = JdPayService::getNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- if ($bonusSnapshot !== null) $data['recharge_bonus_snapshot'] = $bonusSnapshot;
- $data['status'] = self::STATUS_STAY;
- $ret = JdPayService::pay($amount, $order_no);
- Log::channel('payment')->info('JD支付发起', $ret);
- if (($ret['code'] ?? 0) == 200) {
- $item = $ret['data'] ?? [];
- $payUrl = $item['url'] ?? '';
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_no'] = $item['orderNo'] ?? '';
- $data['pay_url'] = $payUrl;
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- static::$MODEL::create($data);
- if ($payUrl) {
- $result['image'] = asset(self::createPaymentQrCode($payUrl));
- }
- $text = "{$bankName}充值确认 \n";
- $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $text .= "支付地址:{$payUrl}\n";
- $text .= "支付金额:" . $amount . " RMB \n";
- $text .= "请按实际支付金额进行付款,否则影响到账 \n";
- $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['text'] = $text;
- $result['url'] = $payUrl;
- } else {
- $result['text'] = $ret['message'] ?? 'JD支付发起失败';
- $result['code'] = 20002;
- }
- return $result;
- }
- $data = [];
- $data['type'] = self::TYPE_PAY;
- $data['member_id'] = $memberId;
- $data['amount'] = $amount;
- $data['channel'] = $channel;
- $data['fee'] = $amount * $rate;
- $data['bank_name'] = SanJinService::getChannel($paymentType) ?? '';
- $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['callback_url'] = SanJinService::getNotifyUrl();
- $data['remark'] = '充值费率:' . $rate;
- if ($bonusSnapshot !== null) $data['recharge_bonus_snapshot'] = $bonusSnapshot;
- $data['status'] = self::STATUS_STAY;
- $ret = SanJinService::pay(($amount * 100), $order_no, $channel);
- Log::error('三斤支付发起:', $ret);
- if ($ret['code'] == 0) {
- $qrCode = asset(self::createPaymentQrCode($ret['data']['payUrl']));
- $result['image'] = $qrCode;
- $item = $ret['data'];
- $data['status'] = self::STATUS_PROCESS;
- $data['pay_no'] = $item['tradeNo'];
- $data['pay_url'] = $item['payUrl'];
- $data['pay_data'] = json_encode($ret, JSON_UNESCAPED_UNICODE);
- $info = static::$MODEL::create($data);
- // $text = "✅ 支付提示 \n";
- $text = "{$data['bank_name']}充值确认 \n";
- // $text .= "支付方式:{$data['bank_name']} \n";
- $text .= "请使用浏览器扫码或者复制支付地址到浏览器打开 \n";
- $text .= "支付地址:{$ret['data']['payUrl']}\n";
- $text .= "支付金额:" . $amount . " RMB \n";
- $text .= "请按实际支付金额进行付款,否则影响到账 \n";
- $text .= "支付完成后请耐心等待,支付到账会第一时间通知您! \n";
- $result['text'] = $text;
- $result['url'] = $ret['data']['payUrl'];
- } else {
- $result['text'] = $ret['message'];
- $result['code'] = 20002;
- }
- return $result;
- }
- /**
- * @description: 接收支付的通知
- * @param {*} $params
- * @return {*}
- */
- public static function receivePay($params)
- {
- if (ZimuPayService::getAppId() !== '' && ($params['appId'] ?? '') === ZimuPayService::getAppId()) {
- $info = self::findOne(['order_no' => $params['mchOrderNo'] ?? '']);
- if (!$info || $info->type != self::TYPE_PAY || !ZimuPayService::isRechargeChannel($info->channel)) {
- Log::error('ZIMU充值回调订单不存在或类型不匹配', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'order_id' => $info->id ?? null,
- 'order_type' => $info->type ?? null,
- 'channel' => $info->channel ?? null,
- ]);
- return false;
- }
- if (!ZimuPayService::verifyNotify($params)) {
- Log::error('ZIMU充值回调验签失败', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'app_id' => $params['appId'] ?? '',
- 'signature' => ZimuPayService::notifySignatureDiagnostics($params),
- ]);
- return false;
- }
- if (bccomp(ZimuPayService::amount($info->amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- Log::error('ZIMU充值回调金额不一致', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'order_amount' => $info->amount,
- 'callback_amount' => $params['amount'] ?? null,
- ]);
- return false;
- }
- if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
- return true;
- }
- $processed = self::applyPayCallback(
- $info,
- ZimuPayService::amount($info->amount),
- (string)$params['status'],
- ZimuPayService::PAY_STATUS_SUCCESS,
- ZimuPayService::PAY_STATUS_FAIL,
- $params
- );
- if ($processed && (string)$params['status'] === ZimuPayService::PAY_STATUS_SUCCESS) {
- self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
- }
- return true;
- }
- if (NoPayService::getDepositMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getDepositMerchantId()) {
- $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
- if (!$info || $info->type != self::TYPE_PAY || !NoPayService::isRechargeChannel($info->channel)) {
- Log::error('NO钱包充值回调订单不存在或类型不匹配', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'order_id' => $info->id ?? null,
- 'order_type' => $info->type ?? null,
- 'channel' => $info->channel ?? null,
- ]);
- return false;
- }
- if (!NoPayService::verifyDepositNotify($params)) {
- Log::error('NO钱包充值回调验签失败', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'app_id' => $params['appId'] ?? '',
- 'signature' => NoPayService::depositNotifySignatureDiagnostics($params),
- ]);
- return false;
- }
- if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- Log::error('NO钱包充值回调金额不一致', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'order_amount' => $info->amount,
- 'callback_amount' => $params['amount'] ?? null,
- ]);
- return false;
- }
- if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
- return true;
- }
- $processed = self::applyPayCallback(
- $info,
- NoPayService::amount($info->amount),
- (string)$params['state'],
- NoPayService::STATE_SUCCESS,
- NoPayService::STATE_FAIL,
- $params
- );
- if ($processed && (string)$params['state'] === NoPayService::STATE_SUCCESS) {
- self::notifyUser($info->member_id, "✅ 支付成功 \n充值金额:{$info->amount} RMB \n订单号:{$info->order_no} \n您充值的金额已到账,请注意查收!");
- }
- return true;
- }
- if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['orderCode'] ?? ''])
- ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
- if (!$info || $info->type != self::TYPE_PAY) {
- return false;
- }
- if (!JdPayService::verifyPayNotify($params)) {
- return false;
- }
- if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- return false;
- }
- if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
- return true;
- }
- $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), (string)$params['status'], JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $params);
- if ($processed && (string)$params['status'] === JdPayService::PAY_STATUS_SUCCESS) {
- $text = "✅ 支付成功 \n";
- $text .= "充值金额:{$info->amount} RMB \n";
- $text .= "订单号:{$info->order_no} \n";
- $text .= "您充值的金额已到账,请注意查收!";
- self::notifyUser($info->member_id, $text);
- }
- return true;
- }
- // 判断商户号
- if (($params['mchId'] ?? '') == SanJinService::getMerchantId()) {
- $must = ['mchId', 'productId', 'tradeNo', 'outTradeNo', 'amount', 'payAmount', 'state', 'createTime', 'payTime'];
- $info = self::findOne(['order_no' => $params['outTradeNo']]);
- if ($info) {
- // 平台以分计算转成元
- $payAmount = $params['payAmount'] / 100;
- // 判断金额是不是正确认
- if ($info->amount != $payAmount) {
- $text = '❌ 支付失败提醒 \n';
- $text .= "订单金额:{$info->amount} \n";
- $text .= "实际支付:{$payAmount} \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- $text .= "失败原因:支付金额与订单金额不一致 \n";
- $text .= "请联系客服处理!";
- self::notifyUser($info->member_id, $text);
- return false;
- }
- if ($params['sign'] != SanJinService::signature($params, $must)) {
- return false;
- }
- if (!in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
- return false;
- }
- // 付款
- if ($info->type == self::TYPE_PAY) {
- $processed = self::applyPayCallback($info, $payAmount, (string)$params['state'], '1', null, $params);
- if ($processed && $params['state'] == 1) {
- $text = "✅ 支付成功 \n";
- $text .= "充值金额:{$payAmount} RMB \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- $text .= "您充值的金额已到账,请注意查收!";
- self::notifyUser($info->member_id, $text);
- } else {
- $text = "❌ 支付失败 \n";
- $text .= "充值金额:{$payAmount} RMB \n";
- $text .= "订单号:{$params['outTradeNo']} \n";
- }
- return true;
- }
- }
- }
- }
- private static function applyPayCallback(PaymentOrder $info, $payAmount, string $status, string $successStatus, ?string $failStatus, array $params): bool
- {
- return DB::transaction(function () use ($info, $payAmount, $status, $successStatus, $failStatus, $params) {
- $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
- if (!$order || (int)$order->type !== self::TYPE_PAY || !in_array((int)$order->status, self::PAY_OPEN_STATUSES, true)) {
- return false;
- }
- $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
- $order->state = $status;
- if ($status === $successStatus) {
- $order->status = self::STATUS_SUCCESS;
- $order->save();
- $wallet = WalletModel::where('member_id', $order->member_id)->lockForUpdate()->first();
- if (!$wallet) {
- throw new Exception('钱包不存在', HttpStatus::CUSTOM_ERROR);
- }
- $balance = $wallet->available_balance;
- $availableBalance = bcadd($balance, $payAmount, 10);
- $wallet->available_balance = $availableBalance;
- $wallet->save();
- $principal = BalanceLogService::addLog($order->member_id, $payAmount, $balance, $availableBalance, '三方充值', $order->id, '');
- RechargeBonusService::grant('payment_order', $order, $principal);
- // Deposit hooks can grant an immediately available first-deposit reward.
- $wallet->refresh();
- return true;
- }
- if ($failStatus === null || $status === $failStatus) {
- $order->status = self::STATUS_FAIL;
- }
- $order->save();
- return true;
- }, 3);
- }
- /**
- * 拒绝提现
- * @description 改变订单状态为失败,将金额退给用户,并记录提现退款的资金日
- * @param int $orderId 订单ID PaymentOrder 表的ID
- * @param string $remark 失败原因
- * @return array
- */
- public static function withdrawalFailed($orderId, $remark): array
- {
- try {
- DB::transaction(function () use ($orderId, $remark) {
- $order = PaymentOrder::where('id', $orderId)
- ->whereIn('type', [2,4])
- ->where('status', self::STATUS_STAY)
- ->lockForUpdate()
- ->first();
- if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
- // 更新提现记录状态为失败
- $order->status = self::STATUS_FAIL;
- $order->remark = $remark;
- if (!$order->save()) {
- throw new Exception("更新失败,请重试", HttpStatus::CUSTOM_ERROR);
- }
- // 冻结余额退回可用余额,并记录退款日志
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, $order->amount, '三方提现', '提现失败退款');
- }, 3);
- } catch (Exception $e) {
- return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
- }
- return ['code' => 0, 'msg' => 'ok'];
- }
- /**
- * 创建代付订单 (根据 orderId 将钱转到用户指定账户)
- * @param int $orderId PaymentOrder 表的ID
- */
- public static function createPayout(int $orderId): array
- {
- try {
- $order = PaymentOrder::where('id', $orderId)
- ->where('type', 2)
- ->where('status', self::STATUS_STAY)
- ->first();
- if (!$order) throw new Exception("订单不存在_{$orderId}", HttpStatus::CUSTOM_ERROR);
- $amount = $order->amount;
- if (!PaymentProviderService::requestEnabled((string)$order->channel, 2)) {
- throw new Exception('支付公司已禁用', HttpStatus::CUSTOM_ERROR);
- }
- if (!RechargeChannel::query()->where('data_type', 2)->where('type', $order->channel)->available()->exists()) {
- throw new Exception('提现通道已停用或删除', HttpStatus::CUSTOM_ERROR);
- }
- $amount = number_format($amount, 2, '.', '');
- if (NoPayService::isWithdrawChannel($order->channel)) {
- $ret = NoPayService::withdraw($amount, $order->order_no, (string)$order->member_id, (string)$order->account, (string)$order->card_no);
- Log::channel('payment')->info('NO提现接口调用', [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'q_account' => $order->card_no,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? -1) != 0) {
- throw new Exception($ret['msg'] ?? 'NO提现失败', HttpStatus::CUSTOM_ERROR);
- }
- $order->pay_no = $ret['data']['orderNo'] ?? '';
- $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- } elseif (ZimuPayService::isPayoutChannel($order->channel)) {
- self::assertZimuBalanceEnough($amount, [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'channel' => $order->channel,
- ]);
- if (ZimuPayService::isCashChannel($order->channel)) {
- $ret = ZimuPayService::cash(
- $amount,
- $order->order_no,
- (string)$order->account,
- (string)$order->card_no,
- (string)$order->bank_name,
- ZimuPayService::cashPayMethod((string)$order->bank_name)
- );
- } else {
- $ret = ZimuPayService::withdraw($amount, $order->order_no, (string)$order->member_id, (string)$order->card_no, (string)$order->account);
- }
- Log::channel('payment')->info('ZIMU提现/代付接口调用', [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'channel' => $order->channel,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? -1) != 0) {
- throw new Exception($ret['msg'] ?? 'ZIMU提现/代付失败', HttpStatus::CUSTOM_ERROR);
- }
- $order->pay_no = $ret['data']['orderNo'] ?? '';
- $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- } elseif (JdPayService::isChannel($order->channel)) {
- self::assertJdBalanceEnough($amount, [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'address' => $order->card_no,
- ]);
- $ret = JdPayService::remit($amount, $order->order_no, $order->card_no);
- Log::channel('payment')->info('JD下发接口调用', [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'address' => $order->card_no,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? 0) != 200) {
- $logContext = [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'member_id' => $order->member_id,
- 'amount' => $amount,
- 'address' => $order->card_no,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD下发接口失败', $logContext);
- Log::error('JD下发接口失败', $logContext);
- throw new Exception($ret['message'] ?? 'JD下发失败', HttpStatus::CUSTOM_ERROR);
- }
- $order->pay_no = $ret['data']['orderNo'] ?? '';
- $order->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- } else {
- $ret = QianBaoService::payout(
- $amount, $order->order_no, $order->bank_name, $order->account, $order->card_no, $order->channel
- );
- Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
- if ($ret['code'] != 200) throw new Exception($ret['msg'], HttpStatus::CUSTOM_ERROR);
- }
- $order->status = self::STATUS_PROCESS;
- $order->save();
- } catch (Exception $e) {
- Log::channel('payment_error')->error('创建代付订单失败', [
- 'order_id' => $orderId,
- 'error' => $e->getMessage(),
- ]);
- Log::error('创建代付订单失败', [
- 'order_id' => $orderId,
- 'error' => $e->getMessage(),
- ]);
- return ['code' => HttpStatus::CUSTOM_ERROR, 'msg' => $e->getMessage()];
- }
- return ['code' => 0, 'msg' => 'ok'];
- }
- /**
- * @description: 创建代付订单 (自动直接到账,包括用户钱包的扣款和提现记录的生成以及余额日志的创建)
- * @param {*} $memberId 会员ID
- * @param {*} $amount 代付金额
- * @param {*} $channel 提现通道 DF001 支付宝转卡/DF002 支付宝转支付宝
- * @param {*} $bank_name 银行名称/支付宝
- * @param {*} $card_no 银行卡号/支付宝账号
- * @return {*}
- */
- public static function autoCreatePayout($memberId, $amount, $channel, $bank_name, $card_no, ?string $bankBranch = null)
- {
- $default_amount = $amount;
- $result = [];
- $result['chat_id'] = $memberId;
- if ($channel === 'rgtx') {
- $result['text'] = lang('不支持此提现方式');
- return $result;
- }
- if (!PaymentProviderService::requestEnabled((string)$channel, 2)) {
- $result['text'] = '支付公司已禁用';
- return $result;
- }
- $user = User::query()->where('member_id', $memberId)->first();
- $groupId = (int)($user->recharge_channel_group_id ?? 1);
- $channelConfig = RechargeChannel::checkWithdrawChannel($channel, $groupId);
- if ($channelConfig === false) {
- $result['text'] = '不支持此提现方式';
- return $result;
- }
- $minAmount = (float)($channelConfig->min ?? 0);
- $maxAmount = (float)($channelConfig->max ?? 0);
- if ($amount < $minAmount || ($maxAmount > 0 && $amount > $maxAmount)) {
- $result['text'] = "提现金额范围为{$minAmount}-{$maxAmount}";
- return $result;
- }
- $channelRate = (float)($channelConfig->rate ?? 0);
- // 在调用三方支付前开始事务
- DB::beginTransaction();
- try {
- $account = WithdrawalName::forPayout($user, $channel);
- $bankBranch = WithdrawalDestination::bankBranch($channel, $bank_name, $bankBranch);
- $data = [];
- $data['type'] = self::TYPE_PAYOUT;
- $order_no = self::createOrderNo('sj' . $data['type'] . '_', $memberId);
- $data['order_no'] = $order_no;
- $data['member_id'] = $memberId;
- $data['fee'] = $amount * $channelRate + 2;
- $amount = number_format($amount, 2, '.', '');
- $data['amount'] = $amount;
- $data['channel'] = $channel;
- $data['bank_name'] = $bank_name;
- if ($bankBranch !== null) {
- $data['bank_branch'] = $bankBranch;
- }
- $data['account'] = $account;
- $data['card_no'] = $card_no;
- if (NoPayService::isWithdrawChannel($channel)) {
- $data['callback_url'] = NoPayService::getWithdrawNotifyUrl();
- } elseif (JdPayService::isChannel($channel)) {
- $data['callback_url'] = JdPayService::getRemitNotifyUrl();
- } elseif (ZimuPayService::isPayoutChannel($channel)) {
- $data['callback_url'] = ZimuPayService::getPayoutNotifyUrl();
- } else {
- $data['callback_url'] = QianBaoService::getNotifyUrl();
- }
- $data['status'] = self::STATUS_STAY;
- $data['remark'] = '提现费率:' . ($channelRate * 100) . '%+2';
- // 校验打码量 → 冻结资金 → 创建待处理的提现记录 → 重置打码周期
- [$info, $wallet] = WithdrawFundsService::hold((string)$memberId, $default_amount, '三方提现', '钱宝提现费率:' . ($channelRate * 100) . '%+2',
- WithdrawFundsService::PAYMENT_ORDERS, fn () => static::$MODEL::create($data));
- $id = $info->id;
- $available_balance = $wallet->available_balance;
- // 提交事务,确保预扣款成功
- DB::commit();
- } //
- catch (Exception $e) {
- // 预扣款失败,回滚事务
- DB::rollBack();
- $result['text'] = $e->getCode() === HttpStatus::CUSTOM_ERROR ? $e->getMessage() : '系统繁忙,请稍后重试!';
- Log::error('提现预扣款失败: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'amount' => $amount
- ]);
- return $result;
- }
- // 调用三方支付接口(在事务外)
- if (NoPayService::isWithdrawChannel($channel)) {
- try {
- $ret = NoPayService::withdraw($amount, $order_no, (string)$memberId, (string)$account, (string)$card_no);
- Log::channel('payment')->info('NO提现接口调用', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'q_account' => $card_no,
- 'response' => $ret,
- ]);
- $success = (($ret['code'] ?? -1) == 0);
- $failureMessage = $ret['msg'] ?? 'NO提现失败';
- } catch (Exception $e) {
- $ret = ['msg' => $e->getMessage()];
- $success = false;
- $failureMessage = $e->getMessage();
- Log::channel('payment_error')->error('NO提现接口异常', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'q_account' => $card_no,
- 'error' => $e->getMessage(),
- ]);
- }
- } elseif (ZimuPayService::isPayoutChannel($channel)) {
- try {
- self::assertZimuBalanceEnough($amount, [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'channel' => $channel,
- ]);
- if (ZimuPayService::isCashChannel($channel)) {
- $ret = ZimuPayService::cash(
- $amount,
- $order_no,
- (string)$account,
- (string)$card_no,
- (string)$bank_name,
- ZimuPayService::cashPayMethod((string)$bank_name)
- );
- } else {
- $ret = ZimuPayService::withdraw($amount, $order_no, (string)$memberId, (string)$card_no, $account);
- }
- Log::channel('payment')->info('ZIMU提现/代付接口调用', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'channel' => $channel,
- 'response' => $ret,
- ]);
- $success = (($ret['code'] ?? -1) == 0);
- $failureMessage = $ret['msg'] ?? 'ZIMU提现/代付失败';
- } catch (Exception $e) {
- $ret = ['msg' => $e->getMessage()];
- $success = false;
- $failureMessage = $e->getMessage();
- Log::channel('payment_error')->error('ZIMU提现/代付接口异常', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'channel' => $channel,
- 'error' => $e->getMessage(),
- ]);
- }
- } elseif (JdPayService::isChannel($channel)) {
- try {
- self::assertJdBalanceEnough($amount, [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'address' => $card_no,
- ]);
- $ret = JdPayService::remit($amount, $order_no, $card_no);
- Log::channel('payment')->info('JD下发接口调用', [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'response' => $ret,
- ]);
- $success = (($ret['code'] ?? 0) == 200);
- $failureMessage = $ret['message'] ?? 'JD下发失败';
- if (!$success) {
- $logContext = [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD下发接口失败', $logContext);
- Log::error('JD下发接口失败', $logContext);
- }
- } catch (Exception $e) {
- $ret = ['message' => $e->getMessage()];
- $success = false;
- $failureMessage = $e->getMessage();
- $logContext = [
- 'order_no' => $order_no,
- 'member_id' => $memberId,
- 'amount' => $amount,
- 'address' => $card_no,
- 'error' => $e->getMessage(),
- ];
- Log::channel('payment_error')->error('JD下发接口异常', $logContext);
- Log::error('JD下发接口异常', $logContext);
- }
- } else {
- $ret = QianBaoService::payout($amount, $order_no, $bank_name, $account, $card_no, $channel);
- Log::error('第三方代付接口调用:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
- $success = (($ret['code'] ?? 0) == 200);
- $failureMessage = $ret['msg'] ?? '代付失败';
- }
- if ($success) {
- // 更新提现记录状态为处理中
- DB::beginTransaction();
- try {
- $info->status = self::STATUS_PROCESS;
- if (NoPayService::isWithdrawChannel($channel) || JdPayService::isChannel($channel) || ZimuPayService::isPayoutChannel($channel)) {
- $info->pay_no = $ret['data']['orderNo'] ?? '';
- $info->pay_data = json_encode($ret, JSON_UNESCAPED_UNICODE);
- }
- $info->save();
- DB::commit();
- $text = "✅ 提现申请已提交!\n\n";
- $text .= "钱包余额:{$available_balance} RMB\n";
- $text .= "提现金额:{$default_amount} RMB\n";
- $text .= "⌛️请等待系统处理, 到账时间可能需要几分钟!\n";
- $result['text'] = $text;
- } catch (Exception $e) {
- DB::rollBack();
- // 状态更新失败,但资金已扣款且三方支付已成功
- // 这里可以记录告警,需要人工干预
- Log::error('提现状态更新失败: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'order_no' => $order_no
- ]);
- $result['text'] = '提现申请已提交,系统处理中...';
- }
- } //
- else {
- // 三方支付失败,需要回滚之前的预扣款
- DB::beginTransaction();
- try {
- // 更新提现记录状态为失败
- $info->status = self::STATUS_FAIL;
- $info->remark = $failureMessage;
- $info->save();
- // 冻结余额退回可用余额,并记录退款日志
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $info, $default_amount, '三方提现', '提现失败退款');
- DB::commit();
- $result['text'] = $failureMessage;
- } catch (Exception $e) {
- DB::rollBack();
- // 回滚失败,需要记录告警,人工干预
- Log::error('提现失败回滚异常: ' . $e->getMessage(), [
- 'member_id' => $memberId,
- 'order_no' => $order_no,
- 'amount' => $amount
- ]);
- $result['text'] = '提现失败,请联系客服处理退款!';
- }
- }
- return $result;
- }
- /**
- * @description: 接收三方订单
- * @param {*} $params
- * @return {*}
- */
- public static function receiveOrder($params)
- {
- if (ZimuPayService::getAppId() !== '' && ($params['appId'] ?? '') === ZimuPayService::getAppId()) {
- $info = self::findOne(['order_no' => $params['mchOrderNo'] ?? '']);
- if (!$info || $info->type != self::TYPE_PAYOUT || !ZimuPayService::isPayoutChannel($info->channel)) {
- Log::error('ZIMU提现/代付回调订单不存在或类型不匹配', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'order_id' => $info->id ?? null,
- 'order_type' => $info->type ?? null,
- 'channel' => $info->channel ?? null,
- ]);
- return false;
- }
- if (!ZimuPayService::verifyNotify($params)) {
- Log::error('ZIMU提现/代付回调验签失败', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'app_id' => $params['appId'] ?? '',
- 'signature' => ZimuPayService::notifySignatureDiagnostics($params),
- ]);
- return false;
- }
- if (bccomp(ZimuPayService::amount($info->amount), ZimuPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- Log::error('ZIMU提现/代付回调金额不一致', [
- 'mch_order_no' => $params['mchOrderNo'] ?? '',
- 'order_amount' => $info->amount,
- 'callback_amount' => $params['amount'] ?? null,
- ]);
- return false;
- }
- self::onSubmitZimuPayout($params, $info);
- return true;
- }
- if (NoPayService::getWithdrawMerchantId() !== '' && ($params['appId'] ?? '') === NoPayService::getWithdrawMerchantId()) {
- $info = self::findOne(['order_no' => $params['merchantOrderNo'] ?? '']);
- if (!$info || $info->type != self::TYPE_PAYOUT || !NoPayService::isWithdrawChannel($info->channel)) {
- Log::error('NO钱包提现回调订单不存在或类型不匹配', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'order_id' => $info->id ?? null,
- 'order_type' => $info->type ?? null,
- 'channel' => $info->channel ?? null,
- ]);
- return false;
- }
- if (!NoPayService::verifyWithdrawNotify($params)) {
- Log::error('NO钱包提现回调验签失败', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'app_id' => $params['appId'] ?? '',
- 'signature' => NoPayService::withdrawNotifySignatureDiagnostics($params),
- ]);
- return false;
- }
- if (bccomp(NoPayService::amount($info->amount), NoPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- Log::error('NO钱包提现回调金额不一致', [
- 'merchant_order_no' => $params['merchantOrderNo'] ?? '',
- 'order_amount' => $info->amount,
- 'callback_amount' => $params['amount'] ?? null,
- ]);
- return false;
- }
- self::onSubmitNoPayout($params, $info);
- return true;
- }
- if (($params['userCode'] ?? '') === JdPayService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['customerOrderCode'] ?? ''])
- ?: static::$MODEL::where('pay_no', $params['orderCode'] ?? '')->first();
- if (!$info || $info->type != self::TYPE_PAYOUT) {
- return false;
- }
- if (!JdPayService::verifyRemitNotify($params)) {
- return false;
- }
- if (bccomp(JdPayService::amount($info->amount), JdPayService::amount($params['amount'] ?? 0), 2) !== 0) {
- return false;
- }
- self::onSubmitJdPayout($params, $info);
- return true;
- }
- // 判断商户号是否一致
- if (($params['merchantNum'] ?? '') == QianBaoService::getMerchantId()) {
- $info = self::findOne(['order_no' => $params['orderNo']]);
- if ($info) {
- // 判断金额是不是正确认
- if ($info->amount != $params['amount']) {
- return false;
- }
- // 验证签名
- $sign = QianBaoService::verifyNotifySign($params['state'], $params['orderNo'], $params['amount']);
- if ($params['sign'] != $sign) {
- return false;
- }
- // 代付
- if ($info->type == self::TYPE_PAYOUT) {
- self::onSubmitPayout($params, $info);
- }
- // 代收
- if ($info->type == self::TYPE_PAY) {
- }
- }
- }
- }
- /**
- * @description: 处理代付订单
- * @param {*} $params
- * @return {*}
- */
- public static function onSubmitJdPayout($params, $info)
- {
- if ($info->status != self::STATUS_PROCESS) {
- return;
- }
- $memberId = $info->member_id;
- $amount = JdPayService::amount($params['amount'] ?? $info->amount);
- $data = [];
- $chat_id = $info->member_id;
- $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
- DB::beginTransaction();
- try {
- $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
- if (!$locked || $locked->status != self::STATUS_PROCESS) {
- DB::rollBack();
- return;
- }
- if ((string)$params['status'] === JdPayService::REMIT_STATUS_SUCCESS) {
- $data['status'] = self::STATUS_SUCCESS;
- $res = static::$MODEL::where(['id' => $info->id])->update($data);
- AdminRealtime::record('payment_orders', $info->id);
- WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
- if ($res) {
- $text = "✅ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款地址:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现成功,金额已到账,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- } elseif ((string)$params['status'] === JdPayService::REMIT_STATUS_FAIL) {
- $data['status'] = self::STATUS_FAIL;
- $res = static::$MODEL::where(['id' => $info->id])->update($data);
- AdminRealtime::record('payment_orders', $info->id);
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
- if ($res) {
- $text = "❌ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款地址:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现失败,金额已返回钱包,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- }
- DB::commit();
- } catch (Exception $e) {
- DB::rollBack();
- Log::error('JD提现回调处理异常: ' . $e->getMessage(), $params);
- }
- }
- public static function onSubmitNoPayout($params, $info)
- {
- $notification = null;
- try {
- DB::transaction(function () use ($params, $info, &$notification) {
- $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
- if (!$order || $order->status != self::STATUS_PROCESS) {
- return;
- }
- $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
- if ((string)$params['state'] === NoPayService::STATE_SUCCESS) {
- $order->status = self::STATUS_SUCCESS;
- $order->save();
- WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
- $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
- } elseif ((string)$params['state'] === NoPayService::STATE_FAIL) {
- $order->status = self::STATUS_FAIL;
- $order->save();
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, NoPayService::amount($order->amount), '三方提现', '提现失败退款');
- $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \nNO钱包账号:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
- } else {
- $order->save();
- }
- }, 3);
- if ($notification !== null) {
- self::notifyUser($info->member_id, $notification);
- }
- } catch (Exception $e) {
- Log::channel('payment_error')->error('NO提现回调处理异常', [
- 'order_id' => $info->id,
- 'params' => $params,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- public static function onSubmitZimuPayout($params, $info)
- {
- $notification = null;
- $successStatus = ZimuPayService::isCashChannel($info->channel)
- ? ZimuPayService::CASH_STATUS_SUCCESS
- : ZimuPayService::WITHDRAW_STATUS_SUCCESS;
- $failStatus = ZimuPayService::isCashChannel($info->channel)
- ? ZimuPayService::CASH_STATUS_FAIL
- : ZimuPayService::WITHDRAW_STATUS_FAIL;
- try {
- DB::transaction(function () use ($params, $info, &$notification, $successStatus, $failStatus) {
- $order = PaymentOrder::where('id', $info->id)->lockForUpdate()->first();
- if (!$order || $order->status != self::STATUS_PROCESS) {
- return;
- }
- $order->callback_data = json_encode($params, JSON_UNESCAPED_UNICODE);
- if ((string)$params['status'] === $successStatus) {
- $order->status = self::STATUS_SUCCESS;
- $order->save();
- WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $order);
- $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
- $notification = "✅ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现成功,金额已到账,请注意查收!";
- } elseif ((string)$params['status'] === $failStatus) {
- $order->status = self::STATUS_FAIL;
- $order->save();
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $order, ZimuPayService::amount($order->amount), '三方提现', '提现失败退款');
- $accountLabel = ZimuPayService::isCashChannel($order->channel) ? '收款账号' : '808钱包地址';
- $notification = "❌ 提现通知 \n提现平台:{$order->bank_name} \n收款人:{$order->account} \n{$accountLabel}:{$order->card_no} \n提现金额:{$order->amount} \n提现失败,金额已返回钱包,请注意查收!";
- } else {
- $order->save();
- }
- }, 3);
- if ($notification !== null) {
- self::notifyUser($info->member_id, $notification);
- }
- } catch (Exception $e) {
- Log::channel('payment_error')->error('ZIMU提现/代付回调处理异常', [
- 'order_id' => $info->id,
- 'params' => $params,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- public static function onSubmitPayout($params, $info)
- {
- $memberId = $info->member_id;
- $amount = $params['amount'];
- $data = [];
- $result = [];
- $chat_id = $info->member_id;
- $data['callback_data'] = json_encode($params, JSON_UNESCAPED_UNICODE);
- DB::beginTransaction();
- try {
- // 只处理“处理中”的代付单,避免重复回调重复退款
- $locked = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
- if (!$locked || $locked->status != self::STATUS_PROCESS) {
- DB::rollBack();
- return;
- }
- if ($params['state'] == 1) {
- $data['status'] = self::STATUS_SUCCESS;
- $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
- AdminRealtime::record('payment_orders', $info->id);
- WithdrawFundsService::settle(WithdrawFundsService::PAYMENT_ORDERS, $locked);
- if ($res) {
- $text = "✅ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款卡号:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现成功,金额已到账,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- } else {
- $data['status'] = self::STATUS_FAIL;
- $res = static::$MODEL::where(['order_no' => $params['orderNo']])->update($data);
- AdminRealtime::record('payment_orders', $info->id);
- // 冻结余额退回可用余额,并记录退款日志
- WithdrawFundsService::release(WithdrawFundsService::PAYMENT_ORDERS, $locked, $amount, '三方提现', '提现失败退款');
- if ($res) {
- $text = "❌ 提现通知 \n";
- $text .= "提现平台:{$info->bank_name} \n";
- $text .= "收款人:{$info->account} \n";
- $text .= "收款卡号:{$info->card_no} \n";
- $text .= "提现金额:{$info->amount} \n";
- $text .= "提现失败,金额已返回钱包,请注意查收!";
- self::notifyUser($chat_id, $text);
- }
- }
- DB::commit();
- } catch (Exception $e) {
- DB::rollBack();
- // 回滚失败,需要记录告警,人工干预
- Log::error('提现失败回滚异常: ' . $e->getMessage(), $params);
- }
- }
- /**
- * @description: 查询支付订单
- * @param {*} $id
- * @return {*}
- */
- public static function singlePayOrder($id)
- {
- $msg = [];
- $msg['code'] = self::NOT;
- $info = self::findOne(['id' => $id]);
- if ($info && (int)$info->type === self::TYPE_PAY && in_array((int)$info->status, self::PAY_OPEN_STATUSES, true)) {
- if (NoPayService::isRechargeChannel($info->channel)) {
- $ret = NoPayService::queryPayOrder($info->order_no, (string)$info->member_id);
- Log::channel('payment')->info('NO支付查询订单', $ret);
- if (($ret['code'] ?? -1) == 0) {
- $item = $ret['data'] ?? [];
- if ((string)($item['state'] ?? '') === NoPayService::STATE_SUCCESS) {
- $processed = self::applyPayCallback(
- $info,
- NoPayService::amount($info->amount),
- NoPayService::STATE_SUCCESS,
- NoPayService::STATE_SUCCESS,
- NoPayService::STATE_FAIL,
- $ret
- );
- $msg['code'] = $processed ? self::YES : self::NOT;
- $msg['msg'] = $processed ? '支付成功' : '订单已处理';
- } elseif ((string)($item['state'] ?? '') === NoPayService::STATE_FAIL) {
- self::applyPayCallback(
- $info,
- NoPayService::amount($info->amount),
- NoPayService::STATE_FAIL,
- NoPayService::STATE_SUCCESS,
- NoPayService::STATE_FAIL,
- $ret
- );
- $msg['msg'] = '支付失败';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
- }
- return $msg;
- }
- if (ZimuPayService::isRechargeChannel($info->channel)) {
- $ret = ZimuPayService::queryPayOrder($info->order_no);
- Log::channel('payment')->info('ZIMU支付查询订单', $ret);
- if (($ret['code'] ?? -1) == 0) {
- $item = $ret['data'] ?? [];
- if ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_SUCCESS) {
- $processed = self::applyPayCallback(
- $info,
- ZimuPayService::amount($info->amount),
- ZimuPayService::PAY_STATUS_SUCCESS,
- ZimuPayService::PAY_STATUS_SUCCESS,
- ZimuPayService::PAY_STATUS_FAIL,
- $ret
- );
- $msg['code'] = $processed ? self::YES : self::NOT;
- $msg['msg'] = $processed ? '支付成功' : '订单已处理';
- } elseif ((string)($item['status'] ?? '') === ZimuPayService::PAY_STATUS_FAIL) {
- self::applyPayCallback(
- $info,
- ZimuPayService::amount($info->amount),
- ZimuPayService::PAY_STATUS_FAIL,
- ZimuPayService::PAY_STATUS_SUCCESS,
- ZimuPayService::PAY_STATUS_FAIL,
- $ret
- );
- $msg['msg'] = '支付失败';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . ($ret['msg'] ?? '');
- }
- return $msg;
- }
- if (JdPayService::isChannel($info->channel)) {
- $ret = JdPayService::queryPayOrder($info->pay_no ?? '', $info->order_no);
- Log::channel('payment')->info('JD支付查询订单', $ret);
- if (($ret['code'] ?? 0) == 200) {
- $item = $ret['data'] ?? [];
- if ((string)($item['status'] ?? '') === JdPayService::PAY_STATUS_SUCCESS) {
- $processed = self::applyPayCallback($info, JdPayService::amount($info->amount), JdPayService::PAY_STATUS_SUCCESS,
- JdPayService::PAY_STATUS_SUCCESS, JdPayService::PAY_STATUS_FAIL, $ret);
- $msg['code'] = $processed ? self::YES : self::NOT;
- $msg['msg'] = $processed ? '支付成功' : '订单已处理';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . ($ret['message'] ?? '');
- }
- return $msg;
- }
- $ret = SanJinService::queryOrder($info->order_no);
- Log::error('三斤支付查询订单:', $ret);
- if ($ret['code'] == 0) {
- $item = [];
- $item['state'] = $ret['data']['state'];
- if ($ret['data']['state'] == 1) {
- $processed = self::applyPayCallback($info, (string)$info->amount, '1', '1', null, $ret);
- $msg['code'] = $processed ? self::YES : self::NOT;
- $msg['msg'] = $processed ? '支付成功' : '订单已处理';
- } else {
- $msg['msg'] = '支付中';
- }
- } else {
- $msg['msg'] = '查询失败:' . $ret['message'];
- }
- } else {
- $msg['msg'] = '该状态无法查询';
- }
- return $msg;
- }
- private static function assertJdBalanceEnough($amount, array $context = []): void
- {
- $ret = JdPayService::balance();
- Log::channel('payment')->info('JD余额查询', $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? 0) != 200) {
- $logContext = $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD余额查询失败', $logContext);
- Log::error('JD余额查询失败', $logContext);
- throw new Exception($ret['message'] ?? 'JD余额查询失败', HttpStatus::CUSTOM_ERROR);
- }
- $balance = $ret['data']['balance'] ?? null;
- if ($balance === null || bccomp((string)$balance, JdPayService::amount($amount), 2) < 0) {
- $logContext = $context + [
- 'amount' => $amount,
- 'balance' => $balance,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('JD商户余额不足', $logContext);
- Log::error('JD商户余额不足', $logContext);
- throw new Exception('JD商户余额不足', HttpStatus::CUSTOM_ERROR);
- }
- }
- private static function assertZimuBalanceEnough($amount, array $context = []): void
- {
- $ret = ZimuPayService::balance();
- Log::channel('payment')->info('ZIMU余额查询', $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ]);
- if (($ret['code'] ?? -1) != 0) {
- $logContext = $context + [
- 'amount' => $amount,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('ZIMU余额查询失败', $logContext);
- Log::error('ZIMU余额查询失败', $logContext);
- throw new Exception($ret['msg'] ?? 'ZIMU余额查询失败', HttpStatus::CUSTOM_ERROR);
- }
- $balance = $ret['data']['balance'] ?? null;
- if ($balance === null || bccomp((string)$balance, ZimuPayService::amount($amount), 2) < 0) {
- $logContext = $context + [
- 'amount' => $amount,
- 'balance' => $balance,
- 'response' => $ret,
- ];
- Log::channel('payment_error')->error('ZIMU商户余额不足', $logContext);
- Log::error('ZIMU商户余额不足', $logContext);
- throw new Exception('ZIMU商户余额不足', HttpStatus::CUSTOM_ERROR);
- }
- }
- private static function notifyUser($chatId, string $text): void
- {
- if ((int)User::where('member_id', $chatId)->value('from') !== -1) {
- return;
- }
- try {
- self::sendMessage($chatId, $text);
- } catch (\Throwable $e) {
- Log::channel('payment_error')->error('支付订单用户通知失败', [
- 'chat_id' => $chatId,
- 'error' => $e->getMessage(),
- ]);
- }
- }
- public static function syncPayOrder()
- {
- $list = static::$MODEL::where('state', 0)->where('type', self::TYPE_PAY)->take(100)->get();
- // foreach($list->toArray() as $k => $v){
- // $item= [];
- // if($v['status'] == self::STATUS_SUCCESS){
- // $item['state'] = 1;
- // static::$MODEL::where(['id'=>$v['id']])->update($item);
- // }else{
- // $ret = SanJinService::queryOrder($v['order_no']);
- // var_dump($ret);
- // if($ret['code'] == 0){
- // $item['state'] = $ret['data']['state'];
- // static::$MODEL::where(['id'=>$v['id']])->update($item);
- // }
- // }
- // }
- }
- }
|