【问题标题】:Unable to authorize using OAuth (Google API)无法使用 OAuth (Google API) 进行授权
【发布时间】:2015-07-03 17:05:28
【问题描述】:

我正在尝试使用 Curl 来授权使用 Oauth,但我收到了来自 Google 的“缺少必需参数:grant_type”响应。谁能告诉我我的代码有什么问题?

$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: www.googleapis.com', 'Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('client_id' => 'xxxxxxxxxxx.apps.googleusercontent.com', 'client_secret' => 'xxxxxxxxxx', 'refresh_token' => $auth->refresh_token, 'grant_type' => 'refresh_token'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

【问题讨论】:

  • 使用 Google Oauth Playground 完成 Oauth 流程并记录 http 请求。然后让你的匹配。

标签: curl oauth oauth-2.0 google-oauth google-analytics-api


【解决方案1】:

您将一个数组传递给CURLOPT_POSTFIELDS,这会导致内容类型设置为multipart/form-data,因为它是在CURLOPT_HTTPHEADER 选项之后应用的。您需要先将http_build_query 应用于数组,这将导致内容类型为application/x-www-form-urlencoded。所以使用:

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('client_id' => 'xxxxxxxxxxx.apps.googleusercontent.com', 'client_secret' => 'xxxxxxxxxx', 'refresh_token' => $auth->refresh_token, 'grant_type' => 'refresh_token')));

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多