Browse Source

新的支付 但是好像不太好用

Tree 1 month ago
parent
commit
9897841637

+ 148 - 0
app/Http/Controllers/Api/PagYeepPayController.php

@@ -0,0 +1,148 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Http\logic\api\PagYeepPayLogic;
+use App\Http\logic\api\PagYeepPayCashierLogic;
+use App\Inter\PayMentInterFace;
+use App\Notification\TelegramBot;
+use App\Services\PagYeepPay;
+use App\Services\PayConfig;
+use App\Services\PayUtils;
+use App\Util;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class PagYeepPayController implements PayMentInterFace
+{
+    private $retryTimes = 0;
+
+    public function pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
+    {
+        $logic = new PagYeepPayLogic();
+        try {
+            $res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
+        } catch (\Exception $exception) {
+            Redis::set("PayErro_PagYeepPay", 1);
+            Redis::expire("PayErro_PagYeepPay", 600);
+            Util::WriteLog('PagYeepPay_error', $exception->getMessage() . json_encode($logic->result ?? []));
+
+            TelegramBot::getDefault()->sendProgramNotify("PagYeepPay Except ", $exception->getMessage(), $exception);
+            return apiReturnFail($logic->getError());
+        }
+
+        if (!empty($res) && isset($res['code']) && $res['code'] == 0) {
+            $data = [
+                'content' => $res['data']['cashierUrl'],
+                'money' => $payAmt,
+                'prdOrdNo' => $res['data']['mchOrderNo'],
+            ];
+            return apiReturnSuc($data);
+        } else if ($res == false) {
+            return apiReturnFail($logic->getError());
+        } else {
+            if ($this->retryTimes > 0) {
+                Redis::set("PayErro_PagYeepPay", 1);
+                Redis::expire("PayErro_PagYeepPay", 600);
+                TelegramBot::getDefault()->sendProgramNotify("PagYeepPay RetrunFail ", $logic->getError() . " | " . json_encode($res));
+                return apiReturnFail($logic->getError());
+            } else {
+                $this->retryTimes++;
+                return $this->pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
+            }
+        }
+    }
+
+    // 支付异步回调
+    public function notify(Request $request)
+    {
+        // PagYeepPay回调格式(POST form表单):
+        // version, orgNo, custId, custOrderNo, prdOrdNo, payAmt, ordStatus, sign
+        
+        $post = $request->all();
+        $payload = json_encode($post, JSON_UNESCAPED_UNICODE);
+
+        Util::WriteLog('PagYeepPay', "PagYeepPay支付回调\n" . $payload);
+
+        // 验证签名
+        $service = new PagYeepPay();
+        
+        try {
+            $verify = $service->verifySign($post);
+        } catch (\Exception $e) {
+            Util::WriteLog('PagYeepPay', '验签失败:' . $e->getMessage());
+            return 'SC000000';  // 仍然返回成功,避免重复回调
+        }
+
+        if (!$verify) {
+            Util::WriteLog('PagYeepPay', '签名错误');
+            return 'SC000000';  // 仍然返回成功,避免重复回调
+        }
+
+        // 提取商户订单号
+        $order_sn = $post['custOrderNo'] ?? '';
+        if (empty($order_sn)) {
+            Util::WriteLog('PagYeepPay', '缺少订单号');
+            return 'SC000000';
+        }
+
+        $logic = new PagYeepPayLogic();
+        try {
+            $redis = Redis::connection();
+            $ret = $logic->notify($post);
+            if ($ret == 'SC000000') {
+                $redis->set("pagyeepay_notify_" . $order_sn, $order_sn, 3600 * 24);
+            }
+            return $ret;
+        } catch (\Exception $exception) {
+            Redis::set("PayErro_PagYeepPay", 1);
+            Redis::expire("PayErro_PagYeepPay", 600);
+            TelegramBot::getDefault()->sendProgramNotify("PagYeepPay 订单回调执行 异常 ", json_encode($post), $exception);
+            Util::WriteLog("PagYeepPay_error", $exception->getMessage());
+            return 'SC000000';
+        }
+    }
+
+    public function sync_notify(Request $request)
+    {
+       echo "Success";
+    }
+
+    // 提现异步回调
+    public function cash_notify(Request $request)
+    {
+        $post = $request->all();
+        $payload = json_encode($post, JSON_UNESCAPED_UNICODE);
+
+        Util::WriteLog('PagYeepPay', "PagYeepPay cash 异步回调\n" . $payload);
+
+        // 使用 PagYeepPayOut 配置进行验签
+        $payConfigService = new PayConfig();
+        $config = $payConfigService->getConfig('PagYeepPayOut');
+        $service = new PagYeepPay();
+        $service->config = $config;
+        $service->key = $config['key'] ?? '';
+        
+        try {
+            $verify = $service->verifySign($post);
+        } catch (\Exception $e) {
+            Util::WriteLog('PagYeepPay cash', '验签失败:' . $e->getMessage());
+            return 'SC000000';
+        }
+
+        if (!$verify) {
+            Util::WriteLog('PagYeepPay cash', '签名错误');
+            return 'SC000000';
+        }
+
+        $logic = new PagYeepPayCashierLogic();
+        try {
+            return $logic->notify($post);
+        } catch (\Exception $exception) {
+            TelegramBot::getDefault()->sendProgramNotify("PagYeepPay 提现异步回调执行 异常 ", json_encode($post), $exception);
+            Util::WriteLog("PagYeepPay_error", $post);
+            return 'SC000000';
+        }
+    }
+}

+ 298 - 0
app/Http/logic/api/PagYeepPayCashierLogic.php

@@ -0,0 +1,298 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Estatisticas\RechargeWithDraw;
+use App\dao\Pay\AccountPayInfo;
+use App\Http\helper\NumConfig;
+use App\Inter\CashierInterFace;
+use App\Models\PrivateMail;
+use App\Models\RecordUserDataStatistics;
+use App\Services\PagYeepPay;
+use App\Services\PayConfig;
+use App\Services\PayUtils;
+use App\Services\StoredProcedure;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class PagYeepPayCashierLogic implements CashierInterFace
+{
+    const AGENT = 103; // PagYeepPay代付渠道值
+    protected $agent = 103;
+
+    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';    // 订单不存在
+
+        $dao = new AccountPayInfo();
+        [$userPhone, $userName, $userEmail] = $dao->payInfo($query->UserID);
+
+        // 使用PagYeepPay服务类进行签名(PagYeepPayOut配置)
+        $service = new PagYeepPay();
+        $payConfigService = new PayConfig();
+        $config = $payConfigService->getConfig('PagYeepPayOut');
+        $service->config = $config;
+        $service->key = $config['key'] ?? '';
+        $service->orgNo = $config['orgNo'] ?? '';
+        $service->custId = $config['custId'] ?? '';
+        
+        // PagYeepPay支付方式映射(根据文档:CASH / CASH_APP / APPLE_PAY)
+        $payOutTypes = [
+            1 => 'ecashapp',  // CashApp
+            2 => 'paypal'     // PayPal
+        ];
+        
+        // 根据PixType选择账号和代付方式
+        // PixType: 1=CashApp, 2=PayPal
+        $account = '';
+        $payOutType = $payOutTypes[$PixType] ?? 'ecashapp';
+        
+        if ($PixType == 1) {
+            if ($PixNum && strpos($PixNum, '$') !== 0) {
+                $PixNum = '$' . $PixNum;
+            }
+            $account = $PixNum;  // CashApp标签,如: $abcd1234
+        } elseif ($PixType == 2) {
+            $account = $email;   // PayPal邮箱,如: 1111@gmail.com
+        }
+
+        // 构建提现请求参数(根据文档)
+        $params = [
+            "version" => $config['version'] ?? "2.1",  // 版本号
+            "orgNo" => $service->orgNo,  // 机构编号
+            "custId" => $service->custId,  // 商户编号
+            "custOrdNo" => $OrderId,  // 商户代付订单号
+            "country" => "US",  // 国家
+            "currency" => "USD",  // 货币
+            "casAmt" => (int) $amount,  // 代付金额(分)
+            "callBackUrl" => $config['callBackUrl'],
+            "payoutType" => 'EPS',  // 代付方式
+            "accountName" => $accountName ?: 'U'.$query->UserID,  // 收款人姓名
+            "cardType" => $payOutType,
+            "cardNo" => $account,
+            "phone" => $userPhone,
+            "email" => $userEmail,
+
+        ];
+
+        // 如果有回调地址配置
+        if (!empty($config['callBackUrl'])) {
+            $params["callBackUrl"] = $config['callBackUrl'];
+        }
+
+        // 使用PagYeepPay的签名方法
+        $signedParams = $service->sign($params);
+
+        $url = $config['apiUrl'].'/establish/consumption.ac';
+
+        Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现请求: ' . $url . ' | 参数: ' . json_encode($signedParams));
+        
+        try {
+            // 使用独立的 curlPost 方法发送请求
+            $result = $service->curlPost($url, $signedParams);
+        } catch (\Exception $exception) {
+            Util::WriteLog('PagYeepPay_payout_error', '提现请求异常:' . $exception->getMessage());
+            return 'fail';
+        }
+
+        Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现结果: ' . ($result ?? "no result"));
+
+        try {
+            // 解析返回结果(可能是form表单格式或JSON格式)
+            parse_str($result, $data);
+            if (empty($data)) {
+                $data = \GuzzleHttp\json_decode($result, true);
+            }
+        } catch (\Exception $e) {
+            Util::WriteLog("PagYeepPay_payout_error", ['解析失败', $result, $e->getMessage()]);
+            return 'fail';
+        }
+
+        // 根据文档,返回码000000表示成功
+        if (isset($data['code']) && $data['code'] == '000000') {
+            Util::WriteLog('PagYeepPay_payout', "提现订单创建成功: {$OrderId}");
+            return $data;
+        } else {
+            // 提现失败处理
+            Util::WriteLog('PagYeepPay_payout_error', "提现失败: {$OrderId} | " . json_encode($data));
+            
+            if ($query->State == 5) {
+                // 同步失败,发送邮件给玩家,退还金币
+                $msg = $data['msg'] ?? 'Transfer failed';
+                $WithDraw = $query->WithDraw + $query->ServiceFee;
+                $bonus = '30000,' . $WithDraw;
+
+                PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
+
+                $withdraw_data = [
+                    'State' => 6, 
+                    'agent' => $this->agent, 
+                    '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';
+        }
+    }
+
+    public function notify($post)
+    {
+        if (!is_array($post)) {
+            // 可能是form表单格式
+            parse_str($post, $post);
+            if (empty($post)) {
+                $post = \GuzzleHttp\json_decode($post, true);
+            }
+        }
+        
+        Util::WriteLog('PagYeepPay', 'PagYeepPay 提现回调:' . json_encode($post));
+
+        try {
+            // 根据文档,回调参数:custOrderNo, prdOrdNo, payAmt, ordStatus, casDesc, utr, sign
+            $OrderId = $post['custOrderNo'] ?? '';
+            $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
+
+            if (!$query) {
+                Util::WriteLog('PagYeepPay_payout','提现订单不存在: ' . $OrderId);
+                return 'SC000000';
+            }
+
+            if ($query->State != 5 && $query->State != 7) {
+                Util::WriteLog('PagYeepPay_payout', $OrderId . '_提现订单状态已完成');
+                return 'SC000000';
+            }
+
+            $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['prdOrdNo'] ?? '',  // 平台代付订单号
+                'extra' => \GuzzleHttp\json_encode($post),
+                'created_at' => $now,
+                'updated_at' => $now,
+                'order_sn' => $OrderId,
+                'amount' => $query->WithDraw,
+            ];
+
+            // 根据文档,代付状态:07=清算完成(成功), 08=清算失败
+            $orderStatus = 0;
+            $ordStatus = $post['ordStatus'] ?? '';
+            if ($ordStatus == '07') {
+                $orderStatus = 1;  // 提现成功
+            } elseif ($ordStatus == '08') {
+                $orderStatus = 2;  // 提现失败
+            }
+
+            if (!$orderStatus) {
+                Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现处理中:' . $OrderId . ', 状态: ' . $ordStatus);
+                return 'SC000000';
+            }
+
+            Util::WriteLog('PagYeepPay_payout', 'PagYeepPay提现回调:' . $OrderId . ', 状态: ' . $ordStatus . ', 处理结果: ' . $orderStatus);
+            
+            $UserID = $query->UserID;
+            $TakeMoney = $query->WithDraw + $query->ServiceFee;
+
+            switch ($orderStatus) {
+                case 1: // 提现成功
+                    Util::WriteLog('PagYeepPay', 'PagYeepPay提现成功');
+
+                    $withdraw_data = [
+                        'State' => 2,
+                        'agent' => $agentID,
+                        'finishDate' => $now
+                    ];
+
+                    // 增加提现记录
+                    $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) {
+                            // 忽略邮件发送失败
+                        }
+                    }
+
+                    // 免审的时候,修改免审状态
+                    $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
+                    if ($withdrawal_position_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 $exception) {
+                        Util::WriteLog('StoredProcedure', $exception);
+                    }
+
+                    $ServiceFee = $query->ServiceFee;
+                    // 增加用户提现值
+                    RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
+
+                    // 数据统计后台 -- 提现记录添加
+                    (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);
+
+                    $redis = Redis::connection();
+                    $redis->incr('draw_' . date('Ymd') . $UserID);
+                    break;
+
+                case 2: // 提现失败
+                    $msg = $post['casDesc'] ?? 'Encomenda rejeitada pelo banco';
+                    $bonus = '30000,' . $TakeMoney;
+                    PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
+                    
+                    Util::WriteLog('PagYeepPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
+                    $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => $msg];
+                    $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);
+            }
+            
+            Util::WriteLog('PagYeepPay_payout', "提现回调处理完成: {$OrderId}");
+            
+            return 'SC000000';
+
+        } catch (\Exception $exception) {
+            Util::WriteLog('PagYeepPay_payout_error', 'PagYeepPay提现回调处理失败:' . $exception->getMessage() . "\n" . $exception->getTraceAsString());
+            return 'SC000000';
+        }
+    }
+
+}

+ 244 - 0
app/Http/logic/api/PagYeepPayLogic.php

@@ -0,0 +1,244 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Pay\AccountPayInfo;
+use App\dao\Pay\PayController;
+use App\Facade\TableName;
+use App\Http\helper\CreateOrder;
+use App\Http\helper\NumConfig;
+use App\Jobs\Order;
+use App\Notification\TelegramBot;
+use App\Services\OrderServices;
+use App\Services\PayConfig;
+use App\Services\PagYeepPay;
+use App\Services\CreateLog;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+
+class PagYeepPayLogic extends BaseApiLogic
+{
+    public $result;
+
+    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 PagYeepPay();
+        $config = $service->config;
+
+        $order_sn = CreateOrder::order_sn($userId);
+
+        // 生成订单信息(PagYeepPay金额单位:分)
+        $logic = new OrderLogic();
+        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
+        $logic->orderCreate($order_sn, $amount, 'PagYeepPay', $userId, $pay_method, $GiftsID, $AdId, $eventType);
+
+        // 支付方式映射(根据文档:CASH_APP、APPLE_PAY等)
+        $payMethods = [
+            1 => '1204',
+//            2 => '1207',
+            4 => '1205',
+//            8 => 'GOOGLE_PAY'
+        ];
+
+        $payType = @$payMethods[$pay_method] ?: '1204';
+
+        // 构建支付请求参数(根据文档)
+        $params = [
+            "version" => $config['version'] ?? "2.1",  // 接口版本号
+            "orgNo" => $config['orgNo'],  // 机构编号
+            "custId" => $config['custId'],  // 商户编号
+            "custOrderNo" => $order_sn,  // 商户订单号
+//            "tranType" => 1,
+            "clearType" => "01",
+            "tranType" => $payType,  // 支付类型
+            "payAmt" => (int) round($pay_amount * 100),  // 支付金额(单位:分)
+
+            "backUrl" => $config['notify'] ?? '',  // 支付结果异步通知地址
+            "frontUrl" => $config['return'] ?? '',  // 支付成功返回地址
+            "goodsName" => "Gift",
+            "orderDesc" => "Gift Goos",
+            "buyIp" => $buyIP,
+            "userName" => $userName,
+            "userEmail" => $userEmail,
+            "userPhone" => $userPhone,
+            "countryCode" => "US",
+            "currency" => "USD",  // 货币
+        ];
+
+        // 签名
+        $signedParams = $service->sign($params);
+
+        // 生成用户请求信息日志
+        $request_extra = \GuzzleHttp\json_encode($signedParams);
+        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);
+
+        $url = $service->apiUrl.'/establish/defray.ac';
+
+        $result = $service->curlPost($url, $signedParams);
+        $rresult = compact('result', 'signedParams', 'url');
+        
+        Util::WriteLog('PagYeepPay', 'PagYeepPay支付请求' . $url . " | " . $request_extra);
+        Util::WriteLog('PagYeepPay', 'PagYeepPay支付结果' . json_encode($rresult));
+        
+        try {
+            // 解析返回结果(可能是form表单格式或JSON格式)
+//            parse_str($result, $res);
+//            if (empty($res)) {
+                $res = \GuzzleHttp\json_decode($result, true);
+//            }
+        } catch (\Exception $e) {
+            Util::WriteLog("PagYeepPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
+            $this->error = 'Payment processing failed';
+            return false;
+        }
+
+        // 根据文档,返回码000000表示成功
+        if (isset($res['code']) && $res['code'] == '000000') {
+            // 转换为统一格式供控制器使用
+            return [
+                'code' => 0,  // 统一成功码
+                'data' => [
+                    'cashierUrl' => @$res['busContent']['url'],  // 支付链接(如果有)
+                    'mchOrderNo' => $order_sn,  // 商户订单号
+                    'orderNo' => $res['prdOrdNo'] ?? '',  // 平台订单号
+                    'amount' => $pay_amount,
+                    'currency' => 'USD',
+                    'status' => 'initiated',
+                ]
+            ];
+        } else {
+            $this->error = $res['msg'] ?? 'Payment failed';
+            Util::WriteLog('PagYeepPay_error', 'Payment failed: ' . json_encode($res));
+            return false;
+        }
+    }
+
+    public function notify($post)
+    {
+        try {
+            if (!is_array($post)) {
+                // 可能是form表单格式
+                parse_str($post, $post);
+                if (empty($post)) {
+                    $post = \GuzzleHttp\json_decode($post, true);
+                }
+            }
+
+            Util::WriteLog('PagYeepPay', "PagYeepPay异步回调处理\n" . json_encode($post, JSON_UNESCAPED_UNICODE));
+
+            // 根据文档,回调参数:
+            // version, orgNo, custId, custOrderNo, prdOrdNo, payAmt, ordStatus, sign
+            $order_sn = $post['custOrderNo'] ?? '';  // 商户订单号
+
+            $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();
+
+            if (!$order) {
+                Util::WriteLog('PagYeepPay', '订单不存在: ' . $order_sn);
+                return 'SC000000';  // 根据文档,返回SC000000表示成功
+            }
+
+            // 订单已处理,直接返回成功
+            if ((!empty($order->pay_at) || !empty($order->finished_at))) {
+                Util::WriteLog('PagYeepPay', '订单已处理: ' . $order_sn);
+                return 'SC000000';
+            }
+
+            $body = [
+                'payment_sn' => $post['prdOrdNo'] ?? '',  // 平台订单号
+                'updated_at' => date('Y-m-d H:i:s'),
+            ];
+
+            $ordStatus = $post['ordStatus'] ?? '';  // 订单状态
+            $GiftsID = $order->GiftsID ?: '';
+            $userID = $order->user_id ?: '';
+            $AdId = $order->AdId ?: '';
+            $eventType = $order->eventType ?: '';
+            // 金额单位:分
+            $payAmt = intval($post['payAmt'] ?? 0);
+            $payAmtYuan = $payAmt / 100;  // 转换为元
+
+            // 根据文档,订单状态:01=成功, 02=失败, 其他=处理中
+            switch ($ordStatus) {
+                case '01':  // 支付成功
+                    $body['pay_status'] = 1;
+                    $body['pay_at'] = date('Y-m-d H:i:s');
+                    $body['finished_at'] = date('Y-m-d H:i:s');
+                    $body['amount'] = $payAmt;  // 已经是分
+                    $config = (new PayConfig())->getConfig('PagYeepPay');
+                    $body['payment_fee'] = $body['amount'] * ($config['payin_fee'] ?? 0);
+                    
+                    try {
+                        // 获取金额
+                        $service = new OrderServices();
+
+                        if (intval($order->amount) != $body['amount']) {
+                            // 金额不匹配,按实际支付金额处理
+                            $body['GiftsID'] = 0;
+                            $body['amount'] = $payAmt;
+                            $Recharge = $payAmtYuan;
+                            $give = 0;
+                            $favorable_price = $Recharge + $give;
+                            $czReason = 1;
+                            $cjReason = 45;
+                        } else {
+                            [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmtYuan);
+                        }
+
+                        // 增加充值记录
+                        [$Score] = $service->addRecord($userID, $payAmtYuan, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType);
+                        // 成功处理回调
+                        Order::dispatch([$userID, $payAmtYuan, $Score, $favorable_price, $GiftsID, $order_sn]);
+
+                        Util::WriteLog("PagYeepPay", "订单处理成功: {$order_sn}, 用户: {$userID}, 金额: {$payAmtYuan}, 到账: {$Score}");
+
+                    } catch (\Exception $exception) {
+                        Util::WriteLog("PagYeepPay_error", "订单处理异常: " . $exception->getMessage());
+                        throw $exception;
+                    }
+
+                    break;
+                    
+                case '02':    // 支付失败
+                    $body['pay_status'] = 2;
+                    Util::WriteLog('PagYeepPay', "订单支付失败: {$order_sn}, 状态: 02");
+                    break;
+                    
+                default:          // 其他状态(处理中)
+                    Util::WriteLog('PagYeepPay', "订单处理中: {$order_sn}, 状态: {$ordStatus}");
+                    return 'SC000000';  // 返回成功
+            }
+
+            $order_up = DB::connection('write')->table('agent.dbo.order')
+                ->where('order_sn', $order_sn)
+                ->update($body);
+
+            if (!$order_up) {
+                Util::WriteLog('PagYeepPay', '订单更新失败: ' . $order_sn);
+                return 'SC000000';  // 仍然返回成功
+            }
+
+            Util::WriteLog("PagYeepPay", "订单回调处理完成: {$order_sn}");
+
+            return 'SC000000';
+
+        } catch (\Exception $exception) {
+            Util::WriteLog("PagYeepPay_error", "回调异常: " . $exception->getMessage() . "\n" . $exception->getTraceAsString());
+            throw $exception;
+        }
+    }
+}

+ 4 - 0
app/Services/CashService.php

@@ -7,6 +7,7 @@ use App\Http\logic\api\WiwiPayCashierLogic;
 use App\Http\logic\api\WDPayCashierLogic;
 use App\Http\logic\api\CoinPayCashierLogic;
 use App\Http\logic\api\AiPayCashierLogic;
+use App\Http\logic\api\PagYeepPayCashierLogic;
 
 
 class CashService
@@ -28,6 +29,9 @@ class CashService
             case AiPayCashierLogic::AGENT:
                 return new AiPayCashierLogic();
 
+            case PagYeepPayCashierLogic::AGENT:
+                return new PagYeepPayCashierLogic();
+
         }
     }
 }

+ 160 - 0
app/Services/PagYeepPay.php

@@ -0,0 +1,160 @@
+<?php
+
+namespace App\Services;
+
+use App\Util;
+
+class PagYeepPay
+{
+    public $config;
+    public $key;
+    public $orgNo;
+    public $custId;
+    public $apiUrl;
+
+    public function __construct()
+    {
+        $payConfigService = new PayConfig();
+        $this->config = $payConfigService->getConfig('PagYeepPay');
+        
+        $this->key = $this->config['key'] ?? '';
+//        $this->orgNo = $this->config['orgNo'] ?? '';
+//        $this->custId = $this->config['custId'] ?? '';
+        $this->apiUrl = $this->config['apiUrl'] ?? '';
+    }
+
+    /**
+     * 签名 - PagYeepPay专用签名算法
+     * 
+     * 规则(根据文档):
+     * 1. 按参数名ASCII码从小到大排序(字典序)
+     * 2. 空值不参与签名
+     * 3. sign参数不参与签名
+     * 4. 拼接格式:key1=value1&key2=value2&key=商户密钥
+     * 5. 参数值使用原始值,不进行URL Encode
+     * 6. MD5后转大写
+     */
+    public function sign(array $params): array
+    {
+        // 移除sign和空值
+        $signParams = [];
+        foreach ($params as $key => $value) {
+            if ($key !== 'sign' && $value !== null && $value !== '') {
+                $signParams[$key] = $value;
+            }
+        }
+        
+        // 按ASCII码排序
+        ksort($signParams);
+        
+        // 拼接字符串:key1=value1&key2=value2(不进行URL Encode)
+        $stringA = '';
+        foreach ($signParams as $key => $value) {
+            if ($stringA !== '') {
+                $stringA .= '&';
+            }
+            $stringA .= $key . '=' . $value;
+        }
+        
+        // 拼接商户密钥:stringA&key=商户密钥
+        $stringSignTemp = $stringA . '&key=' . $this->key;
+        
+        // MD5并转大写
+        $sign = strtoupper(md5($stringSignTemp));
+        
+        // 将签名添加到参数中
+        $params['sign'] = $sign;
+        
+        Util::WriteLog('PagYeepPay_sign', "待签名字符串: " . $stringSignTemp);
+        Util::WriteLog('PagYeepPay_sign', "签名结果: " . $sign);
+        
+        return $params;
+    }
+
+    /**
+     * 验签 - PagYeepPay专用验签算法
+     */
+    public function verifySign(array $params): bool
+    {
+        if (!isset($params['sign'])) {
+            return false;
+        }
+        
+        $receivedSign = $params['sign'];
+        
+        // 移除sign和空值
+        $signParams = [];
+        foreach ($params as $key => $value) {
+            if ($key !== 'sign' && $value !== null && $value !== '') {
+                $signParams[$key] = $value;
+            }
+        }
+        
+        // 按ASCII码排序
+        ksort($signParams);
+        
+        // 拼接字符串(不进行URL Encode)
+        $stringA = '';
+        foreach ($signParams as $key => $value) {
+            if ($stringA !== '') {
+                $stringA .= '&';
+            }
+            $stringA .= $key . '=' . $value;
+        }
+        
+        // 拼接商户密钥
+        $stringSignTemp = $stringA . '&key=' . $this->key;
+        
+        // MD5并转大写
+        $calculatedSign = strtoupper(md5($stringSignTemp));
+        
+        Util::WriteLog('PagYeepPay_verify', "待验签字符串: " . $stringSignTemp);
+        Util::WriteLog('PagYeepPay_verify', "计算签名: " . $calculatedSign);
+        Util::WriteLog('PagYeepPay_verify', "接收签名: " . $receivedSign);
+        
+        return $calculatedSign === $receivedSign;
+    }
+
+    /**
+     * POST请求 - application/x-www-form-urlencoded
+     */
+    public function curlPost($url, $payload)
+    {
+        $timeout = 20;
+        
+        // PagYeepPay使用 application/x-www-form-urlencoded 格式,UTF-8编码
+        $data = http_build_query($payload, '', '&', PHP_QUERY_RFC3986);
+        
+        $headers = [
+            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
+        ];
+
+        $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);
+        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+        if (curl_errno($ch)) {
+            $error = curl_error($ch);
+            Util::WriteLog('PagYeepPay_error', 'CURL Error: ' . $error);
+            curl_close($ch);
+            return false;
+        }
+
+        if ($httpCode != 200) {
+            Util::WriteLog('PagYeepPay_error', 'HTTP Code: ' . $httpCode . " | Response: " . $result);
+        }
+
+        curl_close($ch);
+        return $result;
+    }
+}

+ 3 - 0
app/Services/PayMentService.php

@@ -13,6 +13,7 @@ use App\Http\Controllers\Api\WiwiPayController;
 use App\Http\Controllers\Api\WDPayController;
 use App\Http\Controllers\Api\CoinPayController;
 use App\Http\Controllers\Api\AiPayController;
+use App\Http\Controllers\Api\PagYeepPayController;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Redis;
@@ -36,6 +37,8 @@ class PayMentService
             case 'AiPay':
                 return new AiPayController();
 
+            case 'PagYeepPay':
+                return new PagYeepPayController();
 
             case 'apple':
                 return new AppleStorePayController();

+ 0 - 85
config/pay.php

@@ -1,85 +0,0 @@
-<?php
-
-// 支付配置
-
-return [
-
-    'fastPay' => [
-        'pay_url' => 'https://api.fastpag.com',
-        'appID' => '',
-        'secretKey' => '',
-        'payFastKey' => '',
-        'notify' => env('APP_URL', '').'/api/fastpay/notify',
-        'syncNotify' =>env('APP_URL', '').'/api/fastpay/sync_notify',
-        'cashierNotify' => env('APP_URL', '').'/api/fastpay/cash_notify',
-        'agentCashierNotify' => env('APP_URL', '').'/api/fastpay/cash_notify',
-    ],
-
-
-    // 新增的支付方式配置示例(如wiwipay)
-    'WiwiPay' => [
-        'key' => 'dkr3T8645AH28d81hL5722J7v72cqt6b',
-        'mchNo' => '2025109626',
-        'apiUrl' => 'https://www.wiwiusonepay.com/api/pay/create',
-        'currency' => 'usd',
-        'wayCode' => 'cashapp',
-        'signType' => 'MD5',
-        'payin_fee' => 0.15,
-        'notify' => env('APP_URL', '').'/api/wiwipay/notify',
-        'return' => env('APP_URL', '').'/api/wiwipay/return',
-    ],
-    'WiwiPayOut' => [
-        'key' => 'AX2w17jpU06y5bPQc3d33Z6F4XbfoHnN',
-        'mchNo' => '2025103753',
-        'apiUrl' => 'https://www.wiwiusonepayout.com/api/transfer/create',
-        'currency' => 'usd',
-        'wayCode' => 'cashapp',
-        'signType' => 'MD5',
-        'payout_fee' => 0.15,
-        'cashNotify' => env('APP_URL', '').'/api/wiwipay/payout_notify',
-        'cash_url' => env('APP_URL', '').'/api/payout/create'
-    ],
-    'WDPay' => [
-        'key' => '62b9986350334c29b415103e16ac52f8',
-        'customer' => 'usslot777',
-        'customerNo' => '1027007522',
-        'apiUrl' => 'https://pay.wonderspay.com/charging/create-pay-in',
-        'currency' => 'USD',
-        'wayCode' => 'cashapp',
-        'signType' => 'MD5',
-        'payin_fee' => 0.15,
-        'notify' => env('APP_URL', '').'/api/wdpay/notify',
-        'return' => env('APP_URL', '').'/api/wdpay/return',
-    ],
-    'WDPayOut' => [
-        'key' => '06845be73c704f579ce64d797019dbb0',
-        'customer' => 'usslot777',
-        'customerNo' => '1027017801',
-        'apiUrl' => 'https://transfer.wonderspay.com/charging/create-pay-out',
-        'currency' => 'USD',
-        'wayCode' => 'cashapp',
-        'signType' => 'MD5',
-        'payin_fee' => 0.15,
-        'cashNotify' => env('APP_URL', '').'/api/wdpay/payout_notify',
-        'return' => env('APP_URL', '').'/api/wdpay/return',
-    ],
-
-    'AiPay' => [
-        'mchNo' => 'USSLOT7778313769775',
-        'key' => 'MGJmNk7fvQbE0xXzvX44fKTs98SlmgmiwpJgZ/moTvk=',
-        'apiUrl' => 'https://api.7aipay.com',
-        'currency' => 'USD',
-        'paymentMethod' => '1101',
-        'payin_fee' => 0.15,
-        'notify' => env('APP_URL', '').'/api/aipay/notify',
-        'return' => env('APP_URL', '').'/api/aipay/return',
-    ],
-
-    'AiPayOut' => [
-        'mchNo' => 'TEST2311609409',
-        'key' => 'v6jtjhsrPOBFh2YRAN89TnaTRJXJ7LC9nfcHuZQneyI=',
-        'apiUrl' => 'https://api.7aipay.com',
-        'currency' => 'USD',
-        'cashNotify' => env('APP_URL', '').'/api/aipay/payout_notify',
-    ],
-];

+ 5 - 0
routes/api.php

@@ -314,6 +314,11 @@ Route::any('/aipay/notify', 'Api\AiPayController@notify');
 Route::any('/aipay/payout_notify', 'Api\AiPayController@cash_notify');
 Route::any('/aipay/return', 'Api\AiPayController@sync_notify');
 
+// PagYeepPay支付渠道
+Route::any('/pagyeepay/notify', 'Api\PagYeepPayController@notify');
+Route::any('/pagyeepay/payout_notify', 'Api\PagYeepPayController@cash_notify');
+Route::any('/pagyeepay/return', 'Api\PagYeepPayController@sync_notify');
+
 // CoinPay数字货币
 Route::any('/coinpay/notify', 'Api\CoinPayController@notify');
 Route::any('/coinpay/payout_notify', 'Api\CoinPayController@cash_notify');