PHP发送POST/GET请求插件guzzle安装使用/验证outh2.0/解决验证报错:Full authentication is required to access this resource

版权声明:廖圣平博客,未经博主允许不得转载。企鹅:1194008361 https://blog.csdn.net/qq_22823581/article/details/84990191

插件介绍

官网:
https://guzzle-cn.readthedocs.io/zh_CN/latest/index.html

安装guzzle

composer require guzzlehttp/guzzle

使用

场景:验证 access-token 是否有效;

Controller:

    $data = [
                'url'     => env('system.oauth_url') . '/users/info',
                'headers' => [
                    'Accept'        => 'application/json',
                    'Authorization' => 'Bearer ' . $token
                ]
            ];
            $res = Tool::sendRequest($data);
            if (empty($res['principal'])) {
                error('验证失败');
            }

Tool::function

头部引入:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
    public static function sendRequest(array $data)
    {
        try {
            $url = $data['url'];
            $client = new Client();
            $params = $data['params'] ?? [];
            $method = $data['request_method'] ?? 'POST';
            $timeout = $data['timeout'] ?? 10;
            $options = [
                'form_params' => $params,
                'timeout' => $timeout
            ];
            if (isset($data['headers'])) {
                $options['headers'] = $data['headers'];
            }
            $response = $client->request($method, $url, $options);
            $result = $response->getBody();
            return json_decode($result, true);
        } catch (ClientException $e) {
            return false;
        }
    }

没有更多推荐了,返回首页