详解ThinkPHP6结合GuzzleHTTP发送HTTP请求

 3597

下面给大家介绍ThinkPHP6 结合GuzzleHTTP发送HTTP请求,希望对需要的朋友有所帮助!


背景

thinkphp微信公众号程序主动调用微信的接口需要用到access_token,以及需要主动发送请求设置公众号菜单。

为什么选择GuzzleHTTP

Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。

发送同步或异步的请求均使用相同的接口。

使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。

抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。

中间件系统允许你创建构成客户端行为。

Guzzle中文文档:https://guzzle-cn.readthedocs.io/zh_CN/latest/


安装GuzzleHTTP

1、安装composer

因为thinkphp6采用composer安装,所以我的环境上已经装好了composer,此处略过安装composer方法。需要请自行百度。


2、安装Guzzle

进入到tp项目目录

cd /Applications/XAMPP/htdocs/tp1/tp

执行安装命令

composer require guzzlehttp/guzzle

3、在php.ini文档中打开 extension=php_openssl.dll


发送http get示例代码

1、在controller中引入GuzzleHttp

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

2、下面的示例程序是在tp6中采用HTTP GET获取微信公众平台的access token

//微信公众平台获取access token url
$url = 'https://api.weixin.qq.com/cgi-bin/token?';
//获取access token时需要携带的参数
$params = array(
    'grant_type' => 'client_credential',
    'appid' => config('app.WECHAT.APPID'),
    'secret' => config('app.WECHAT.SECRET')
);
$resp = null;
try {
    //使用GuzzleHTTP发送get请求
    $client = new Client();
    $resp = $client->request('GET', $url.http_build_query($params));
} catch (GuzzleException $e){
    print($e);
}
 
if (empty($resp)) {
    return null;
}
//获取微信公众平台的response
$data = json_decode($resp->getBody(), true);
if (isset($data['errcode']) && $data['errcode'] != 0) {
    throw new \think\Exception ($data['errmsg'], $data['errcode']);
}


发送http post示例代码

用法非常简单,直接看代码吧。

/**
 * 创建自定义菜单
 */
public function menu()
{
    require __DIR__ . '/../../vendor/autoload.php';
    //构建HTTP post JSON body数据
    $data = array(
        'button' => array(
            array(
                'type' => 'click',
                'name' => '主菜单1',
                'sub_button' => array(
                    array(
                        'type' => 'click',
                        'name' => '子菜单1',
                        'key' => self::MENU_MAIN_1_CHILD_1
                    ),
                    array(
                        'type' => 'view',
                        'name' => '百度',
                        'url' => 'https://www.baidu.com'
                    )
                )
            ),
            array(
                'type' => 'click',
                'name' => '主菜单2',
                'sub_button' => array(
                    array(
                        'type' => 'click',
                        'name' => '子菜单1',
                        'key' => self::MENU_MAIN_2_CHILD_1
                    ),
                    array(
                        'type' => 'view',
                        'name' => 'QQ',
                        'url' => 'http://www.qq.com'
                    )
                )
            ),
            array(
                'type' => 'click',
                'name' => '主菜单3',
                'key' => self::MENU_MAIN_3
            )
        )
    );
    //构造请求json body和header数据
    $options = json_encode($data, JSON_UNESCAPED_UNICODE);
    $jsonData = [
        'body' => $options,
        'headers' => ['content-type' => 'application/json']
    ];
 
    $resp = null;
    try {
        $client = new Client();
        //生成微信公众号菜单需要调用的微信接口url
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $this->_getAccessToken();
        //发送http post请求
        $resp = $client->post($url, $jsonData);
    } catch (GuzzleException $e){
        print($e);
    }
 
 
    if (empty($resp)) {
        return null;
    }
 
    echo $resp->getBody();
}


本文网址:https://www.zztuku.com/detail-8872.html
站长图库 - 详解ThinkPHP6结合GuzzleHTTP发送HTTP请求
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐