php鉴权使用方法


发布于 2025-04-03 / 8 阅读 / 0 评论 /
新建鉴权文件authorize/Authorize.php <?php namespace addon\lhhd_xdyxlm\app\service\admin\authorize; use think\facade\Db; use think\facade\Log; use think\fa

新建鉴权文件authorize/Authorize.php

<?php

namespace addon\lhhd_xdyxlm\app\service\admin\authorize;

use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\Response;

class Authorize
{
    const FAIL_SITE_CODE = '499';

    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取当前域名
        $domain = Request::domain();
        $domain = parse_url($domain, PHP_URL_HOST);

        // 请求授权验证
        $result = $this->checkAuthorization($domain);

        if ($result['code'] != 1000) {
            return json(['code' => 400, 'msg' => '未授权站点']);
        }

        $site_id = $request->header('site-id');
        $siteCheckResult = $this->checkAuthSite($result['data'], $site_id);
        if ($siteCheckResult["code"] == self::FAIL_SITE_CODE) {
            return $siteCheckResult;
        }

        return $next($request);
    }

    /**
     * 方法处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function methodHandle($request, \Closure $next)
    {
        // 获取当前域名
        $domain = Request::domain();
        $domain = parse_url($domain, PHP_URL_HOST);

        // 请求授权验证
        $result = $this->checkAuthorization($domain);
        if ($result['code'] != 1000) {
            return json(['code' => 400, 'msg' => '未授权站点']);
        } else {
            $site_id = $request->header('site-id');
            $siteCheckResult = $this->checkAuthSite($result['data'], $site_id);
            if ($siteCheckResult["code"] == self::FAIL_SITE_CODE) {
                return $siteCheckResult;
            }
            return json(['code' => 1000, 'msg' => '授权站点']);
        }
    }

    public function checkAuthSite($data, $site_id)
    {
        $data = json_decode($data, true);
        $keyBase64 = 'CGPna2RzE09mZlDwZl+JHIBWei2lsTxkKtqvcEyngGs=';
        $ivBase64 = 'OLwDmW0ClxrZhIBgeokj2A==';
        $key = base64_decode($keyBase64);
        $iv = base64_decode($ivBase64);
        $decrypted = $this->decryptData($data, $key, $iv);
        Log::write('debug', '授权信息解密' . json_encode($decrypted));
        $authList = Db::table('site')
            ->where('app', 'like', '%lhhd_xdyxlm%')
            ->where('initalled_addon', 'like', '%lhhd_xdyxlm%')
            ->limit($decrypted['quantity'])
            ->select()->toArray();
        $exist = false;
        if (count($authList) > 0) {
            foreach ($authList as $v) {
                if ($v['site_id'] == $site_id) {
                    $exist = true;
                    break;
                }
            }
        }
        if (!$exist) {
            return json(['code' => 499, 'msg' => '站点未授权']);
        }
    }

    function decryptData($encrypted, $key, $iv)
    {
        $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
//        $decrypted = openssl_decrypt($encrypted,'AES-256-CBC',$key,1,$iv);
        Log::write('--debug', "================dddd解密ddd: " . json_encode($decrypted));
        if ($decrypted === false) {
            // 记录 OpenSSL 错误信息
            $error = openssl_error_string();
            Log::write('error', "解密错误: " . json_encode($error));
        }
        Log::write('debug', '授权信息解密内部方法--' . $decrypted . '---');
        return $decrypted;
    }

    /**
     * 检查站点授权
     * @param string $domain
     * @return array
     */
    protected function checkAuthorization($domain)
    {
        $url = 'https://authapi.oeevc.com/Adminapp/manage/project/AuthorizationQuery';

        $data = [
            'Authorizeddomainname' => $domain,
            'projectID' => 'WeChatStoreSelection'
        ];

        // 初始化CURL
        $ch = curl_init();

        // 设置CURL选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false, // 禁用SSL验证
            CURLOPT_SSL_VERIFYHOST => false, // 禁用主机验证
            CURLOPT_TIMEOUT => 30, // 设置超时时间
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json'
            ]
        ]);

        // 执行请求
        $response = curl_exec($ch);

        // 获取错误信息和HTTP状态码
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // 记录调试信息
        \think\facade\Log::write("授权请求域名: {$domain}", 'debug');
        \think\facade\Log::write("授权请求数据: " . json_encode($data), 'debug');
        \think\facade\Log::write("授权响应状态: {$httpCode}", 'debug');
        \think\facade\Log::write("授权响应内容: {$response}", 'debug');
        if ($error) {
            \think\facade\Log::write("CURL错误: {$error}", 'error');
        }

        // 处理响应
        if ($error) {
            return [
                'code' => 1001,
                'message' => '请求授权服务器失败: ' . $error
            ];
        }

        $result = json_decode($response, true);
        if (!$result) {
            return [
                'code' => 1001,
                'message' => '解析授权响应失败'
            ];
        }

        return $result;
    }
}

路由route使用

//引用类
use addon\lhhd_xdyxlm\app\service\admin\authorize\Authorize;

Route::group('lhhd', function () {

     /***************** hello world **************/
    Route::get('hello_world', 'addon\lhhd_xdyxlm\app\adminapi\controller\hello_world\Index@index');
   
  
})->middleware([
   //其他
   Authorize::class,//使用鉴权
]);






方法使用

// 引入鉴权类
use addon\lhhd_xdyxlm\app\service\admin\authorize\Authorize;
// 在这里进行鉴权检查
      $this->authorize = new Authorize();
      $response= $this->authorize->methodHandle($this->request, function () {});
      $data = json_decode($response->getContent(), true);
      Log::write('debug', '获取佣金单管理列表 data-- ' . json_encode($data, true));
      if ($data && isset($data['data']['code'])&& ((string)$data['data']['code'])==Authorize::FAIL_SITE_CODE) {
         Log::write('debug', '站点鉴权未通过' . $data['data']['code']);
         return fail($data['data']['msg']);
      }



是否对你有帮助?

评论