Home >PHP Framework >ThinkPHP >Detailed explanation of ThinkPHP6 combined with GuzzleHTTP to send HTTP requests

Detailed explanation of ThinkPHP6 combined with GuzzleHTTP to send HTTP requests

藏色散人
藏色散人forward
2021-05-14 15:05:585218browse

The following tutorial column will introduce you to ThinkPHP6 and GuzzleHTTP to send HTTP requests. I hope it will be helpful to friends in need! ThinkPHP6 combines GuzzleHTTP to send HTTP requests

thinkphp WeChat public account program actively calls the WeChat interface and needs access_token, and You need to proactively send a request to set up the official account menu.

Why choose GuzzleHTTP

Guzzle is a PHP HTTP client used to easily send requests and integrate into our WEB services.

接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
发送同步或异步的请求均使用相同的接口。
使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
中间件系统允许你创建构成客户端行为。

Guzzle Chinese documentation: https://guzzle-cn.readthedocs.io/zh_CN/latest/

Install GuzzleHTTP

1. Install composer

Because thinkphp6 uses composer to install , so composer has been installed in my environment, and the composer installation method is skipped here. Please use Baidu if necessary.

2. Install Guzzle

Enter the tp project directory
 cd /Applications/XAMPP/htdocs/tp1/tp

Execute the installation command

composer require guzzlehttp/guzzle
3.Open

extension=php_openssl.dll## in the php.ini document

#Send http get sample code

1. Introduce GuzzleHttp in the controller<pre class="brush:php;toolbar:false">use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException;</pre>2. The following sample program uses HTTP GET to obtain the access token of the WeChat public platform in tp6

       //微信公众平台获取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']);
        }

Send http post sample code

The usage is very simple, just look at the code.

    /**
     * 创建自定义菜单
     */
    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();
    }

Related recommendations:

The latest 10 thinkphp video tutorials

The above is the detailed content of Detailed explanation of ThinkPHP6 combined with GuzzleHTTP to send HTTP requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete