laowu 3 dagen geleden
bovenliggende
commit
31e5e31356

+ 131 - 0
app/Http/Controllers/Api/BotImPayController.php

@@ -0,0 +1,131 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Http\logic\api\BotImPayLogic;
+use App\Http\logic\api\BotImPayCashierLogic;
+use App\Inter\PayMentInterFace;
+use App\Notification\TelegramBot;
+use App\Services\BotImPayService;
+use App\Util;
+use App\Utility\SetNXLock;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Redis;
+
+class BotImPayController implements PayMentInterFace
+{
+    /**
+     * 代收下单
+     */
+    public function pay_order(
+        $userId, $payAmt, $userName, $userEmail, $userPhone,
+        $GiftsID, $buyIP, $AdId, $eventType, $pay_method = ''
+    ) {
+        $logic = new BotImPayLogic();
+        try {
+            $res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
+        } catch (\Exception $exception) {
+            Redis::set("PayErro_BotImPay", 1);
+            Redis::expire("PayErro_BotImPay", 600);
+            Util::WriteLog('BotImPay_error', $exception->getMessage() . json_encode($logic->result ?? []));
+            TelegramBot::getDefault()->sendProgramNotify("BotImPay Except ", $exception->getMessage(), $exception);
+            return apiReturnFail($logic->getError());
+        }
+
+        if (!empty($res) && isset($res['code']) && $res['code'] == 200) {
+            $data = [
+                'content'  => $res['data']['order_data'] ?? '',
+                'money'    => $payAmt,
+                'prdOrdNo' => $res['data']['order_no'] ?? '',
+            ];
+            return apiReturnSuc($data);
+        }
+
+        if ($res == false) {
+            return apiReturnFail($logic->getError() ?: 'Payment failed');
+        }
+
+        Redis::set("PayErro_BotImPay", 1);
+        Redis::expire("PayErro_BotImPay", 600);
+        $errMsg = $res['message'] ?? 'Unknown error';
+        TelegramBot::getDefault()->sendProgramNotify("BotImPay ReturnFail ", $errMsg . " | " . json_encode($res));
+        return apiReturnFail(['web.payment.paytype_error', $errMsg]);
+    }
+
+    /**
+     * 代收异步回调通知
+     */
+    public function notify(Request $request)
+    {
+        $post = $request->all();
+        Util::WriteLog('BotImPay', "BotImPay回调订单\n" . json_encode($post));
+
+        $service = new BotImPayService('BotImPay');
+        try {
+            $verify = $service->verifySign($post);
+        } catch (\Exception $e) {
+            Util::WriteLog('BotImPay', '验签失败:' . $e->getMessage());
+            return 'fail';
+        }
+        if (!$verify) {
+            Util::WriteLog('BotImPay', '签名错误');
+            return 'fail';
+        }
+
+        $order_sn = $post['order_no'] ?? '';
+        if (empty($order_sn)) {
+            Util::WriteLog('BotImPay', '缺少订单号');
+            return 'fail';
+        }
+
+        $lockKey = 'pay_notify_BotImPay_' . $order_sn;
+        if (!SetNXLock::getExclusiveLock($lockKey, 60)) {
+            Util::WriteLog('BotImPay', '代收回调并发,订单已处理或处理中: ' . $order_sn);
+            return 'ok';
+        }
+
+        $logic = new BotImPayLogic();
+        try {
+            $ret = $logic->notify($post);
+            return $ret;
+        } catch (\Exception $exception) {
+            Redis::set("PayErro_BotImPay", 1);
+            Redis::expire("PayErro_BotImPay", 600);
+            TelegramBot::getDefault()->sendProgramNotify("BotImPay 订单回调执行异常 ", json_encode($post), $exception);
+            Util::WriteLog("BotImPay_error", $post);
+            return 'fail';
+        } finally {
+            SetNXLock::release($lockKey);
+        }
+    }
+
+    /**
+     * 代付异步回调通知
+     */
+    public function cash_notify(Request $request)
+    {
+        $post = $request->all();
+        Util::WriteLog('BotImPay', "BotImPay 提现回调\n" . json_encode($post));
+
+        $service = new BotImPayService('BotImPayOut');
+        try {
+            $verify = $service->verifySign($post);
+        } catch (\Exception $e) {
+            Util::WriteLog('BotImPay', '提现回调验签失败:' . $e->getMessage());
+            return 'FAIL';
+        }
+        if (!$verify) {
+            Util::WriteLog('BotImPay', '提现回调签名错误');
+            return 'FAIL';
+        }
+
+        $logic = new BotImPayCashierLogic();
+        try {
+            return $logic->notify($post);
+        } catch (\Exception $exception) {
+            TelegramBot::getDefault()->sendProgramNotify("BotImPay 提现异步回调执行异常 ", json_encode($post), $exception);
+            Util::WriteLog("BotImPay_error", $post);
+            return 'SUCCESS';
+        }
+    }
+}

+ 272 - 0
app/Http/logic/api/BotImPayCashierLogic.php

@@ -0,0 +1,272 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Estatisticas\RechargeWithDraw;
+use App\Http\helper\NumConfig;
+use App\Inter\CashierInterFace;
+use App\Models\PrivateMail;
+use App\Models\RecordUserDataStatistics;
+use App\Services\BotImPayService;
+use App\Services\PayConfig;
+use App\Services\StoredProcedure;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class BotImPayCashierLogic implements CashierInterFace
+{
+    const AGENT = 107; // BotImPay代付渠道值
+    protected $agent = 107;
+
+    /**
+     * PixType 到币种简称映射
+     * 3=BTC, 4=ETH, 5=USDT, 6=USDC
+     */
+    protected $currencyMap = [
+        3 => 'BTC',
+        4 => 'ETH',
+        5 => 'USDT',
+        6 => 'USDC',
+    ];
+
+    /**
+     * 提交代付申请
+     */
+    public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
+    {
+        $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)->first();
+        if (!$query) return 'fail';
+
+        $payConfigService = new PayConfig();
+        $config = $payConfigService->getConfig('BotImPayOut');
+
+        // 确定币种:根据 PixType 映射
+        $currency = $this->currencyMap[$PixType] ?? 'USDT';
+
+        // 构建代付请求参数(BotImPay: bank_code 固定 trc20)
+        $params = [
+            'mer_no'     => $config['mer_no'] ?? '',
+            'order_no'   => $OrderId,
+            'amount'     => number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
+            'currency'   => $currency,
+            'bank_code'  => 'trc20',
+            'name'       => $accountName ?: 'user',
+            'account'    => $PixNum ?: $email,
+            'phone'      => $phone ?: '0000000000',
+            'email'      => $email ?: '',
+            'notify_url' => $config['notify_url'] ?? '',
+        ];
+
+        $service = new BotImPayService('BotImPayOut');
+        $signedParams = $service->sign($params);
+
+        $url = ($config['apiUrl'] ?? 'https://api.botimpay.top') . '/open/api/order/out';
+
+        Log::info('BotImPay 提现参数:', $signedParams);
+
+        try {
+            $result = $service->curlPost($url, $signedParams);
+        } catch (\Exception $exception) {
+            Log::info('BotImPay 提现请求异常:', [$exception->getMessage()]);
+            Util::WriteLog('BotImPay_error', 'BotImPay 提现请求异常:' . $exception->getMessage());
+            return 'fail';
+        }
+
+        Log::info('BotImPay 提现结果:', [$result ?? "no result"]);
+
+        try {
+            $data = \GuzzleHttp\json_decode($result, true);
+        } catch (\Exception $e) {
+            Util::WriteLog("BotImPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
+            return 'fail';
+        }
+
+        // BotImPay 代付成功响应: code=200, data.sys_no 是系统流水号
+        if (isset($data['code']) && $data['code'] == 200) {
+            return $data;
+        }
+
+        // 同步失败处理
+        if ($query->State == 5) {
+            $WithDraw = $query->WithDraw + $query->ServiceFee;
+            $bonus = '30000,' . $WithDraw;
+            PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, 'Liquidation failure', $bonus);
+
+            $withdraw_data = [
+                'State'      => 6,
+                'agent'      => 1070,
+                'finishDate' => now(),
+                'remark'     => json_encode($data),
+            ];
+            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
+                ->where('OrderId', $query->OrderId)
+                ->update($withdraw_data);
+
+            $RecordData = ['after_state' => 6, 'update_at' => now()];
+            DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
+                ->where('type', 1)->where('RecordID', $RecordID)
+                ->update($RecordData);
+        }
+        return 'fail';
+    }
+
+    /**
+     * 代付异步回调处理
+     *
+     * BotImPay 代付回调格式(POST JSON):
+     * {
+     *   "mer_no": 3000, "order_no": "xxx",
+     *   "order_amount": "10.00", "order_reality_amount": "10.00",
+     *   "currency": "USDT", "result": "success", "sys_no": "212073",
+     *   "utr": "xxx", "sign": "xxx"
+     * }
+     */
+    public function notify($post)
+    {
+        if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
+
+        Util::WriteLog('BotImPay', 'BotImPay 提现回调:' . json_encode($post));
+
+        try {
+            $OrderId = $post['order_no'] ?? '';
+            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
+                ->where('OrderId', $OrderId)->first();
+
+            if (!$query) {
+                Util::WriteLog('BotImPay', '提现订单不存在: ' . $OrderId);
+                return 'SUCCESS';
+            }
+
+            if ($query->State != 5 && $query->State != 7) {
+                Util::WriteLog('BotImPay', $OrderId . '_订单状态已完成');
+                return 'SUCCESS';
+            }
+
+            $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
+                ->where('config_value', self::AGENT)
+                ->where('type', 'cash')
+                ->select('id')->first()->id ?? '';
+
+            $now = now();
+            $notify_data = [
+                'state'      => 1,
+                'finish_at'  => $now,
+                'casOrdNo'   => $post['sys_no'] ?? '',
+                'extra'      => \GuzzleHttp\json_encode($post),
+                'created_at' => $now,
+                'updated_at' => $now,
+                'order_sn'   => $OrderId,
+                'amount'     => $query->WithDraw,
+            ];
+
+            $result = $post['result'] ?? '';
+            $orderStatus = 0;
+            if ($result === 'success') {
+                $orderStatus = 1;
+            } elseif ($result === 'fail') {
+                $orderStatus = 2;
+            }
+
+            if (!$orderStatus) {
+                Util::WriteLog('BotImPay', 'BotImPay 提现处理中:' . $OrderId);
+                return 'SUCCESS';
+            }
+
+            Util::WriteLog('BotImPay', 'BotImPay 提现结果:' . $OrderId . '_' . $orderStatus);
+
+            $UserID = $query->UserID;
+            $TakeMoney = $query->WithDraw + $query->ServiceFee;
+            $withdraw_data = [];
+
+            switch ($orderStatus) {
+                case 1: // 提现成功
+                    Util::WriteLog('BotImPay', 'BotImPay提现成功');
+
+                    $withdraw_data = [
+                        'State'      => 2,
+                        'agent'      => $agentID,
+                        'finishDate' => $now,
+                    ];
+
+                    // 计算代付手续费
+                    $payConfigService = new PayConfig();
+                    $outConfig = $payConfigService->getConfig('BotImPayOut');
+                    $payRates = $outConfig['pay_rate'] ?? null;
+                    if (is_array($payRates)) {
+                        $pixType = $query->PixType ?? 5;
+                        $payRate = $payRates[$pixType] ?? ($payRates[5] ?? [1, 1]);
+                        $feePercent = $payRate[0] ?? 1;
+                        $feeFixed = $payRate[1] ?? 1;
+                        $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * $feePercent) / 100)
+                            + (int)($feeFixed * NumConfig::NUM_VALUE);
+                    }
+
+                    // 增加提现记录
+                    $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
+                        ->where('UserID', $UserID)->first();
+                    if ($first) {
+                        DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
+                            ->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
+                    } else {
+                        DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
+                            ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
+                        try { PrivateMail::praiseSendMail($UserID); } catch (\Exception $e) {}
+                    }
+
+                    // 免审状态更新
+                    $log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')
+                        ->where('order_sn', $OrderId)->first();
+                    if ($log) {
+                        DB::connection('write')->table('agent.dbo.withdrawal_position_log')
+                            ->where('order_sn', $OrderId)
+                            ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
+                    }
+
+                    try { StoredProcedure::addPlatformData($UserID, 4, $TakeMoney); } catch (\Exception $e) {
+                        Util::WriteLog('StoredProcedure', $e);
+                    }
+
+                    $ServiceFee = $query->ServiceFee;
+                    RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
+                    (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
+
+                    Redis::connection()->incr('draw_' . date('Ymd') . $UserID);
+                    PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
+                    break;
+
+                case 2: // 提现失败
+                    $msg = 'Encomenda rejeitada pelo banco';
+                    $bonus = '30000,' . $TakeMoney;
+                    PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
+                    Util::WriteLog('BotImPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
+                    $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => $post['result_mes'] ?? ''];
+                    $notify_data['state'] = 2;
+                    break;
+            }
+
+            $RecordData = [
+                'before_state' => $query->State,
+                'after_state'  => $withdraw_data['State'] ?? 0,
+                'RecordID'     => $query->RecordID,
+                'update_at'    => date('Y-m-d H:i:s'),
+            ];
+
+            DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
+                ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
+            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
+                ->where('OrderId', $query->OrderId)->update($withdraw_data);
+
+            if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
+                StoredProcedure::user_label($UserID, 2, $TakeMoney);
+            }
+
+            return 'SUCCESS';
+
+        } catch (\Exception $exception) {
+            Util::WriteLog('BotImPay', 'BotImPay异步业务逻辑处理失败:' . $exception->getMessage());
+            return 'SUCCESS';
+        }
+    }
+}

+ 203 - 0
app/Http/logic/api/BotImPayLogic.php

@@ -0,0 +1,203 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Pay\AccountPayInfo;
+use App\dao\Pay\PayController;
+use App\Http\helper\CreateOrder;
+use App\Http\helper\NumConfig;
+use App\Jobs\Order;
+use App\Services\BotImPayService;
+use App\Services\CreateLog;
+use App\Services\OrderServices;
+use App\Services\PayConfig;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+
+class BotImPayLogic extends BaseApiLogic
+{
+    public $result;
+
+    /**
+     * 支付方式到 pay_code 的映射
+     * 16=BTC, 32=ETH, 1024=USDT, 2048=USDC
+     */
+    protected $payCodeMap = [
+        16   => '20303', // BTC
+        32   => '20304', // ETH
+        1024 => '20301', // USDT
+        2048 => '20307', // USDC
+    ];
+
+    /**
+     * 代收下单
+     */
+    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
+    {
+        $dao = new AccountPayInfo();
+        [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);
+
+        // 礼包类型验证
+        $PayVerify = new PayController();
+        $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount);
+        if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
+            $this->error = $PayVerify->getError();
+            return false;
+        }
+        if ($pay_amount < 0) {
+            $this->error = 'Payment error_4';
+            return false;
+        }
+
+        $service = new BotImPayService('BotImPay');
+        $config = $service->config;
+
+        $order_sn = CreateOrder::order_sn($userId);
+
+        // 生成订单信息
+        $logic = new OrderLogic();
+        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
+        $logic->orderCreate($order_sn, $amount, 'BotImPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);
+
+        // 确定 pay_code
+        $payCode = $this->payCodeMap[$pay_method] ?? ($config['pay_code'] ?? '20301');
+
+        // 构建支付请求参数(BotImPay 多一个 ip 字段)
+        $params = [
+            'mer_no'     => $service->merNo,
+            'order_no'   => $order_sn,
+            'amount'     => (string)$pay_amount,
+            'name'       => $userName ?: 'user',
+            'email'      => $userEmail ?: ($userId . '@unknown.com'),
+            'phone'      => $userPhone ?: '0000000000',
+            'currency'   => $config['currency'] ?? 'USDT',
+            'pay_code'   => $payCode,
+            'notify_url' => $config['notify_url'] ?? '',
+            'ip'         => $buyIP,
+        ];
+
+        // RSA签名
+        $signedParams = $service->sign($params);
+
+        // 生成用户请求信息日志
+        $request_extra = \GuzzleHttp\json_encode($signedParams);
+        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);
+
+        $url = $service->apiUrl . '/open/api/order/in';
+
+        $result = $service->curlPost($url, $signedParams);
+        $rresult = compact('result', 'signedParams', 'url');
+
+        Util::WriteLog('BotImPay', 'BotImPay支付请求' . $url . " | " . $request_extra);
+        Util::WriteLog('BotImPay', 'BotImPay支付结果' . json_encode($rresult));
+
+        try {
+            $data = \GuzzleHttp\json_decode($result, true);
+        } catch (\Exception $e) {
+            Util::WriteLog("BotImPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
+            $this->error = 'Payment processing error';
+            return false;
+        }
+
+        return $data;
+    }
+
+    /**
+     * 代收异步回调处理
+     *
+     * BotImPay 回调: { mer_no, order_no, pay_type_code, order_amount, order_reality_amount, status, sign }
+     */
+    public function notify($post)
+    {
+        $order_no = $post['order_no'] ?? '';
+
+        $order = DB::connection('write')->table('agent.dbo.order')
+            ->where('order_sn', $order_no)
+            ->first();
+
+        if (!$order) {
+            Util::WriteLog('BotImPay', '订单不存在: ' . $order_no);
+            return 'ok';
+        }
+
+        if (!empty($order->pay_at) || !empty($order->finished_at)) {
+            return 'ok';
+        }
+
+        $status = $post['status'] ?? '';
+        if ($status !== 'success') {
+            Util::WriteLog('BotImPay', "支付未完成订单: {$order_no}, status: {$status}");
+            return 'ok';
+        }
+
+        // 支付成功
+        $GiftsID = $order->GiftsID ?: '';
+        $userID = $order->user_id ?: '';
+        $AdId = $order->AdId ?: '';
+        $eventType = $order->eventType ?: '';
+
+        $orderAmount = (float)($post['order_reality_amount'] ?? $post['order_amount'] ?? 0);
+        $payAmt = $orderAmount;
+
+        $body = [
+            'payment_sn' => $post['sys_no'] ?? '',
+            'updated_at' => date('Y-m-d H:i:s'),
+            'pay_status' => 1,
+            'pay_at'     => date('Y-m-d H:i:s'),
+            'finished_at'=> date('Y-m-d H:i:s'),
+            'amount'     => (int) round($payAmt * NumConfig::NUM_VALUE),
+        ];
+
+        // 根据支付方式计算代收手续费: 费率% * 金额 + 固定$
+        $config = (new PayConfig())->getConfig('BotImPay');
+        $payRates = $config['pay_rate'] ?? null;
+        if (is_array($payRates)) {
+            $payMethod = $order->order_title ?? 1024;
+            $payRate = $payRates[$payMethod] ?? ($payRates[1024] ?? [3.5, 0]);
+            $feePercent = $payRate[0] ?? 3.5;
+            $feeFixed = $payRate[1] ?? 0;
+            $body['payment_fee'] = intval(($body['amount'] * $feePercent) / 100)
+                + (int)($feeFixed * NumConfig::NUM_VALUE);
+        }
+
+        try {
+            $service = new OrderServices();
+
+            if (intval($order->amount) != $body['amount']) {
+                $body['GiftsID'] = 0;
+                $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);
+                $Recharge = $payAmt;
+                $give = 0;
+                $favorable_price = $Recharge + $give;
+                $czReason = 1;
+                $cjReason = 45;
+            } else {
+                [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo(
+                    $GiftsID, $userID, $payAmt
+                );
+            }
+
+            [$Score] = $service->addRecord(
+                $userID, $payAmt, $favorable_price, $order_no, $GiftsID,
+                $Recharge, $czReason, $give, $cjReason, $AdId, $eventType,
+                $body['payment_fee'] ?? 0
+            );
+
+            Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_no]);
+        } catch (\Exception $exception) {
+            Util::WriteLog("BotImPay_error", $exception->getMessage());
+        }
+
+        $order_up = DB::connection('write')->table('agent.dbo.order')
+            ->where('order_sn', $order_no)
+            ->update($body);
+
+        if (!$order_up) {
+            Util::WriteLog('BotImPay', '订单更新失败: ' . $order_no);
+            return 'ok';
+        }
+
+        Util::WriteLog("BotImPay", 'success: ' . $order_no);
+        return 'ok';
+    }
+}

+ 177 - 0
app/Services/BotImPayService.php

@@ -0,0 +1,177 @@
+<?php
+
+namespace App\Services;
+
+use App\Util;
+
+class BotImPayService
+{
+    public $config;
+    public $merNo;
+    public $apiUrl;
+    public $privateKey;
+    public $platformPublicKey;
+
+    public function __construct($configKey = 'BotImPay')
+    {
+        $payConfigService = new PayConfig();
+        $this->config = $payConfigService->getConfig($configKey);
+
+        $this->merNo = $this->config['mer_no'] ?? '';
+        $this->apiUrl = $this->config['apiUrl'] ?? 'https://api.botimpay.top';
+        $this->privateKey = $this->config['private_key'] ?? '';
+        $this->platformPublicKey = $this->config['platform_public_key'] ?? '';
+    }
+
+    /**
+     * 构建待签名数据(ASCII升序、QueryString格式、跳过sign和空值)
+     */
+    public function buildSignData(array $params): string
+    {
+        $signData = [];
+        foreach ($params as $key => $value) {
+            if ($key === 'sign') {
+                continue;
+            }
+            if ($value === null || $value === '' || (is_array($value) && empty($value))) {
+                continue;
+            }
+            if (is_array($value) || is_object($value)) {
+                $signData[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);
+            } else {
+                $signData[$key] = (string)$value;
+            }
+        }
+
+        ksort($signData);
+
+        $result = '';
+        foreach ($signData as $key => $value) {
+            $result .= '&' . $key . '=' . $value;
+        }
+
+        return substr($result, 1);
+    }
+
+    /**
+     * RSA SHA256 签名(使用商户私钥)
+     */
+    public function sign(array $params): array
+    {
+        $signData = $this->buildSignData($params);
+        $prvKeyPem = $this->convertPrivateKeyToPem($this->privateKey);
+
+        $signature = '';
+        $signed = openssl_sign($signData, $signature, $prvKeyPem, OPENSSL_ALGO_SHA256);
+
+        if (!$signed) {
+            throw new \Exception('BotImPay RSA签名失败');
+        }
+
+        $params['sign'] = base64_encode($signature);
+
+        Util::WriteLog('BotImPay_sign', "待签名字符串: " . $signData);
+        Util::WriteLog('BotImPay_sign', "签名结果: " . $params['sign']);
+
+        return $params;
+    }
+
+    /**
+     * RSA SHA256 验签(使用平台公钥)
+     */
+    public function verifySign(array $params): bool
+    {
+        $receivedSign = $params['sign'] ?? '';
+        if (empty($receivedSign)) {
+            Util::WriteLog('BotImPay', '验签失败:sign字段为空');
+            return false;
+        }
+
+        $signData = $this->buildSignData($params);
+        $pubKeyPem = $this->convertPublicKeyToPem($this->platformPublicKey);
+
+        $isVerified = openssl_verify(
+            $signData,
+            base64_decode($receivedSign),
+            $pubKeyPem,
+            OPENSSL_ALGO_SHA256
+        );
+
+        Util::WriteLog('BotImPay_verify', "验签数据: " . $signData);
+        Util::WriteLog('BotImPay_verify', "验签结果: " . ($isVerified === 1 ? '通过' : '失败'));
+
+        return $isVerified === 1;
+    }
+
+    /**
+     * 转换私钥为PEM格式
+     */
+    private function convertPrivateKeyToPem($privateKeyString)
+    {
+        if (strpos($privateKeyString, '-----BEGIN PRIVATE KEY-----') !== false) {
+            return $privateKeyString;
+        }
+        $key = trim($privateKeyString);
+        if (!preg_match('/^-----BEGIN/', $key)) {
+            if (base64_decode($key, true)) {
+                $key = base64_decode($key);
+            }
+            $key = "-----BEGIN PRIVATE KEY-----\n" . chunk_split(base64_encode($key), 64, "\n") . "-----END PRIVATE KEY-----";
+        }
+        return $key;
+    }
+
+    /**
+     * 转换公钥为PEM格式
+     */
+    private function convertPublicKeyToPem($publicKeyString)
+    {
+        if (strpos($publicKeyString, '-----BEGIN PUBLIC KEY-----') !== false) {
+            return $publicKeyString;
+        }
+        $key = trim($publicKeyString);
+        if (!preg_match('/^-----BEGIN/', $key)) {
+            if (base64_decode($key, true)) {
+                $key = base64_decode($key);
+            }
+            $key = "-----BEGIN PUBLIC KEY-----\n" . chunk_split(base64_encode($key), 64, "\n") . "-----END PUBLIC KEY-----";
+        }
+        return $key;
+    }
+
+    /**
+     * POST JSON请求
+     */
+    public function curlPost($url, $payload)
+    {
+        $timeout = 20;
+        $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
+
+        $headers = [
+            'Content-Type: application/json',
+        ];
+
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
+        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+        $result = curl_exec($ch);
+
+        if (curl_errno($ch)) {
+            $error = curl_error($ch);
+            Util::WriteLog('BotImPay_error', 'CURL Error: ' . $error);
+            curl_close($ch);
+            return false;
+        }
+
+        curl_close($ch);
+        return $result;
+    }
+}

+ 4 - 0
app/Services/CashService.php

@@ -10,6 +10,7 @@ use App\Http\logic\api\AiPayCashierLogic;
 use App\Http\logic\api\PagYeepPayCashierLogic;
 use App\Http\logic\api\PagYeepPayCashierLogic;
 use App\Http\logic\api\AiNewPayCashierLogic;
 use App\Http\logic\api\AiNewPayCashierLogic;
 use App\Http\logic\api\SafePayCashierLogic;
 use App\Http\logic\api\SafePayCashierLogic;
+use App\Http\logic\api\BotImPayCashierLogic;
 
 
 
 
 class CashService
 class CashService
@@ -40,6 +41,9 @@ class CashService
             case SafePayCashierLogic::AGENT:
             case SafePayCashierLogic::AGENT:
                 return new SafePayCashierLogic();
                 return new SafePayCashierLogic();
 
 
+            case BotImPayCashierLogic::AGENT:
+                return new BotImPayCashierLogic();
+
         }
         }
     }
     }
 }
 }

+ 4 - 0
app/Services/PayMentService.php

@@ -16,6 +16,7 @@ use App\Http\Controllers\Api\AiPayController;
 use App\Http\Controllers\Api\PagYeepPayController;
 use App\Http\Controllers\Api\PagYeepPayController;
 use App\Http\Controllers\Api\SafePayController;
 use App\Http\Controllers\Api\SafePayController;
 use App\Http\Controllers\Api\AiNewPayController;
 use App\Http\Controllers\Api\AiNewPayController;
+use App\Http\Controllers\Api\BotImPayController;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Redis;
 use Illuminate\Support\Facades\Redis;
@@ -48,6 +49,9 @@ class PayMentService
             case 'SafePay':
             case 'SafePay':
                 return new SafePayController();
                 return new SafePayController();
 
 
+            case 'BotImPay':
+                return new BotImPayController();
+
             case 'apple':
             case 'apple':
                 return new AppleStorePayController();
                 return new AppleStorePayController();
 
 

+ 34 - 0
config/payTest.php

@@ -43,4 +43,38 @@ return [
         'platform_public_key' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnyULwz2hGQzuxBgazlpR74V0giZv8xAJKJ8DzoBzs8GevOMBAVHY7/lcUs/LiMsZTis7OFDFV6Uqz+kaww9O40P7XZF3Qhh9KzgE+9ehqj6EQOvHEDXnmeakwHP3vCHlfmaToxvj7DUjPOLE+Yvgp89cbj7D0bc8n7YbKYlQHVwIDAQAB',
         'platform_public_key' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnyULwz2hGQzuxBgazlpR74V0giZv8xAJKJ8DzoBzs8GevOMBAVHY7/lcUs/LiMsZTis7OFDFV6Uqz+kaww9O40P7XZF3Qhh9KzgE+9ehqj6EQOvHEDXnmeakwHP3vCHlfmaToxvj7DUjPOLE+Yvgp89cbj7D0bc8n7YbKYlQHVwIDAQAB',
     ],
     ],
 
 
+    // BotImPay 支付渠道(RSA SHA256签名,crypto代收)
+    'BotImPay' => [
+        'mer_no'             => '3005',
+        'apiUrl'             => 'https://api.botimpay.top',
+        'currency'           => 'USDT',
+        'notify_url'         => env('APP_URL', '') . '/api/botimpay/notify',
+        'pay_rate'           => [
+            16   => [1, 0],    // BTC:  1% + $0
+            32   => [1, 0],    // ETH:  1% + $0
+            1024 => [1, 0],    // USDT: 1% + $0
+            2048 => [1, 0],    // USDC: 1% + $0
+        ],
+        // 商户私钥
+        'private_key'        => 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL1QKQMQ8mQAloE8CGGho3RCI0WgtkoAcdy/27EarDs0PBuiGS4i4unYZ2nIrBenuw+XX4K4vizh+CX1Q4hPOqAqBF6a4SgIilFTG0q6mlYYFYnNdWI+t6JjmJtoLYs3EK0SkLkYTKy6TLS++p35L+crglboAWsyFb9oR9wVJisvAgMBAAECgYBI9KNZcyZ2M2PM2f3A4jHDk9lT8+NMEW/PyoA3eDf3eOHRJF7f0MHxrFvuAE+RrioAkC1Wiyt+0HZ46lPkK+RDOgSimv6qK/oT5UGlVQZqZlxLalgQ1Wi0ujqp+wAleTHK6F6InnjupaGwo5jy8Z1GDUkz40eycUDmXPrTBDu3wQJBAPhYCXAMe1UI4FhXUBkU8IjWr1UPDHYkliwj8OegEoNydH90SPvt7qpc8EFN75aK+HwzvjLEQvd8qPJqdMdm0j0CQQDDJj6gzaYGatGQZp5dSWVuF9TOzldEycL2glPXTAcAF9BaQKzL1RTXvPEeIoTsK4tntmEduiOtoVzeIlRrW6XbAkEAx93SeqMQ/zbNl0tt40G+8+IT6djappp7YbrrPv7M541NxOXJdzfeRK3XjjczA22E3jCmeiUJ4DQrpC2ZHoHZ4QJBAJizynnlsa5/03Ac/HqeviHBwCH7UEphXo+qN5TWxvuJpt2Ykh4FpIOUM1CTTlPHVxRWn/O0/coV5Cdl0Y0Yb9UCQB6vthenO4t4qbLy/Hdm83EFJzGmLtdskpU7Rs8qlG1RgVyUgTGv15rlnBFEb3qaYqihYfw5Epxux1GEakhkJsk=',
+        // 平台公钥(回调验签)
+        'platform_public_key' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHCMT8mq2XZPoLii5wYVgg9NlMZadXhwyxJZ5duAX4hxXT1OiPpHkj2PpNyMhcBhn+O8p4FjWGUrTRoL29b0X/IlEuGD+u6QosimqYta4l6S47tNyTUqh9zrPmlXn6qow1JY9rL2eSs30NdvB0oFcitSsn68kNcRUDZ9FGtOZiRQIDAQAB',
+    ],
+
+    // BotImPay 代付渠道配置(RSA SHA256签名)
+    'BotImPayOut' => [
+        'mer_no'             => '3005',
+        'apiUrl'             => 'https://api.botimpay.top',
+        'currency'           => 'USDT',
+        'notify_url'         => env('APP_URL', '') . '/api/botimpay/payout_notify',
+        'pay_rate'           => [
+            3 => [1, 1],    // BTC:  1% + $1
+            4 => [1, 1],    // ETH:  1% + $1
+            5 => [1, 1],    // USDT: 1% + $1
+            6 => [1, 1],    // USDC: 1% + $1
+        ],
+        'private_key'        => 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL1QKQMQ8mQAloE8CGGho3RCI0WgtkoAcdy/27EarDs0PBuiGS4i4unYZ2nIrBenuw+XX4K4vizh+CX1Q4hPOqAqBF6a4SgIilFTG0q6mlYYFYnNdWI+t6JjmJtoLYs3EK0SkLkYTKy6TLS++p35L+crglboAWsyFb9oR9wVJisvAgMBAAECgYBI9KNZcyZ2M2PM2f3A4jHDk9lT8+NMEW/PyoA3eDf3eOHRJF7f0MHxrFvuAE+RrioAkC1Wiyt+0HZ46lPkK+RDOgSimv6qK/oT5UGlVQZqZlxLalgQ1Wi0ujqp+wAleTHK6F6InnjupaGwo5jy8Z1GDUkz40eycUDmXPrTBDu3wQJBAPhYCXAMe1UI4FhXUBkU8IjWr1UPDHYkliwj8OegEoNydH90SPvt7qpc8EFN75aK+HwzvjLEQvd8qPJqdMdm0j0CQQDDJj6gzaYGatGQZp5dSWVuF9TOzldEycL2glPXTAcAF9BaQKzL1RTXvPEeIoTsK4tntmEduiOtoVzeIlRrW6XbAkEAx93SeqMQ/zbNl0tt40G+8+IT6djappp7YbrrPv7M541NxOXJdzfeRK3XjjczA22E3jCmeiUJ4DQrpC2ZHoHZ4QJBAJizynnlsa5/03Ac/HqeviHBwCH7UEphXo+qN5TWxvuJpt2Ykh4FpIOUM1CTTlPHVxRWn/O0/coV5Cdl0Y0Yb9UCQB6vthenO4t4qbLy/Hdm83EFJzGmLtdskpU7Rs8qlG1RgVyUgTGv15rlnBFEb3qaYqihYfw5Epxux1GEakhkJsk=',
+        'platform_public_key' => 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHCMT8mq2XZPoLii5wYVgg9NlMZadXhwyxJZ5duAX4hxXT1OiPpHkj2PpNyMhcBhn+O8p4FjWGUrTRoL29b0X/IlEuGD+u6QosimqYta4l6S47tNyTUqh9zrPmlXn6qow1JY9rL2eSs30NdvB0oFcitSsn68kNcRUDZ9FGtOZiRQIDAQAB',
+    ],
+
 ];
 ];

+ 4 - 0
routes/api.php

@@ -391,6 +391,10 @@ Route::any('/pkpay/payout_notify', 'Api\PKpayController@cash_notify');
 Route::any('/safepay/notify', 'Api\SafePayController@notify');
 Route::any('/safepay/notify', 'Api\SafePayController@notify');
 Route::any('/safepay/payout_notify', 'Api\SafePayController@cash_notify');
 Route::any('/safepay/payout_notify', 'Api\SafePayController@cash_notify');
 
 
+// BotImPay支付渠道
+Route::any('/botimpay/notify', 'Api\BotImPayController@notify');
+Route::any('/botimpay/payout_notify', 'Api\BotImPayController@cash_notify');
+
 Route::any('/all2pay/notify', 'Api\ALL2payController@notify');
 Route::any('/all2pay/notify', 'Api\ALL2payController@notify');
 Route::any('/all2pay/sync_notify', 'Api\ALL2payController@sync_notify');
 Route::any('/all2pay/sync_notify', 'Api\ALL2payController@sync_notify');
 Route::any('/all2pay/cash_notify', 'Api\ALL2payController@cash_notify');
 Route::any('/all2pay/cash_notify', 'Api\ALL2payController@cash_notify');