【问题标题】:PHP Guzzle Client error response/Bad Request 400 Google OAuth2 TokenPHP Guzzle 客户端错误响应/错误请求 400 Google OAuth2 令牌
【发布时间】:2015-05-11 14:32:01
【问题描述】:

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();
}

口渴反应

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 错误......有什么想法吗?

更新:

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

【问题讨论】:

  • 在guzzle中,当你的url无效时会出现这种类型的错误。你在浏览器中测试过url吗?
  • 是的,正如我所说的相同细节,即 url 和凭据通过 cURL 工作正常,但使用 guzzle 时出错。
  • 同样的问题,只有 Guzzle 出现。
  • Guzzle (v3.9) oauth2 请求也存在同样的问题

标签: php oauth google-plus guzzle bad-request


【解决方案1】:

您似乎想在配置 guzzle 时设置 exceptions = false。在此处查看类似的答案:Guzzle: handle 400 bad request

$guzzle_config = array(
    'defaults' => array(
        'debug' => false,
        'exceptions' => false
        )
    );

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 2013-07-21
      • 2016-12-03
      • 2019-09-06
      • 2016-11-18
      相关资源
      最近更新 更多