laravel5.5+中curl发送https请求转换成GuzzleHttp请求
我的项目是一个小程序,里面跑了一个客服会话功能,之前看到群里有人问curl方式转成GuzzleHttp方式,所以我就测试了改一下,记录一下方便自己跟有需要的老铁查阅
环境依赖:
centos7
laravel5.8
Guzzle扩展包
测试项目:
微信小程序的POST发送https请求客服接口api
Guzzle扩展包官方手册:
https://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html#installation
直接进入代码:(我这里以POST为例)
curl方式:
function brequestAPI($json){
$access_token = SelectOption::Bdxcxtoken();
$url = "https://openapi.baidu.com/rest/2.0/smartapp/message/custom/send?access_token=".$access_token;
/*POST发送https请求客服接口api*/
//以'json'格式发送post的https请求
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($json)){
curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl);
echo 'success';
if($output == 0){
echo 'success';exit;
}
}
转
GuzzleHttp方式:
function brequestAPI($json){
$client = new \GuzzleHttp\Client;
$access_token = SelectOption::Bdxcxtoken();
$url = "https://openapi.baidu.com/rest/2.0/smartapp/message/custom/send?access_token=".$access_token;
/*POST发送https请求客服接口api*/
//以'json'格式发送post的https请求
$response = $client->post($url, ['form_params' => $json]);
var_dump(json_decode((string)$response->getBody(), true));
}
亲测可用,已在线上项目跑了,如有补充请在底下留言
相关文章