下面給大家介紹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(); }