Guzzle是一个PHP的HTTP客户端用于发get post请求的
Guzzle中文文档:https://guzzle-cn.readthedocs.io/zh_CN/latest/
composer require guzzlehttp/guzzle
extension=php_openssl.dll
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
下面的示例程序是在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();
}