PHP Guzzle Client错误响应/错误请求400 Google OAuth2令牌

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP Guzzle Client错误响应/错误请求400 Google OAuth2令牌脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Guzzle请求

try {
    $url = 'https://www.GOOGLEapis.COM/oauth2/v1/tokeninfo?';

    $client = new Client();
    $request = $client->createRequest('GET',$url);

    $query = $request->getQuery();
    $query['access_token'] = $access_token;

    $response = $client->send($request);

    $JSON = $response->json();

    if(!empty($json) && !isset($json['error'])) {
        return ($json['audience']==GOOGLE_CLIENT_ID);
    }

} catch(\Exception $e) {
    echo $e->getMessage();
}

Guzzle Response

Client error response
[status code] 400
[reason phrase] Bad Request
[url] https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxxx

简单的CURL请求

$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxxx';
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$url);
curl_setopt($curl_handle,CURLOPT_RETURNtransfer,true);
curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER,false); //disable SSL check
$json_response = curl_exec($curl_handle);
curl_close($curl_handle);
$response = json_decode($json_response);
return $response;

简单的CURL响应

stdClass Object
(
    [issued_to] => xxx-xxx.apps.googleusercontent.com
    [audience] => xxx-xxx.apps.googleusercontent.com
    [user_id] => xxx
    [scope] => https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me
    [expires_in] => 3581
    [access_type] => offline
)

我无法弄清楚我对Guzzle做错了什么,因为你可以看到我使用CURL得到了成功的结果但是在Guzzle上得到了Bad Request错误….任何想法?

更新:

我发现guzzle在响应代码为200 / OK时返回实际响应,否则它现在返回guzzle异常我无法弄清楚如何在出现错误时得到实际响应?

解决方法

我发现解决方案使用RequestException而不是Exception

try {
  //Google oAuth2 Code   
} catch(RequestException $e) {
  $response = $e->getResponse()->json(); //Get error response body
}

脚本宝典总结

以上是脚本宝典为你收集整理的PHP Guzzle Client错误响应/错误请求400 Google OAuth2令牌全部内容,希望文章能够帮你解决PHP Guzzle Client错误响应/错误请求400 Google OAuth2令牌所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。