【问题标题】:Get Google Client API access token using CURL使用 CURL 获取 Google 客户端 API 访问令牌
【发布时间】:2014-11-06 14:53:41
【问题描述】:

过去几天我一直在尝试使用 Google Oauth2 获取访问令牌和刷新令牌,但没有得到任何结果。

文档很垃圾,我找不到任何有效的示例。

我刚刚开始使用 CURL 尝试获取访问代码和刷新令牌,但我不断收到响应错误。

我试过用这个

// init the resource
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_FAILONERROR, false);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'Content-length: 0'
));

curl_setopt($ch, CURLOPT_POSTFIELDS,
    'code=' . urlencode('AUTHORISATION_CODE') . '&' .
    'client_id=' . urlencode('MY_CLINET_ID.apps.googleusercontent.com') . '&' .
    'client_secret=' . urlencode('MY_CLIENT_SECRET') . '&' .
    'redirect_uri=http://www.example.com/' . '&' .
    'grant_type=authorization_code'
); 

// execute
$output = curl_exec($ch);

echo $output;

// free
curl_close($ch);

但我只是得到这个回应

{ 
   "error" : "invalid_request", 
   "error_description" : "Required parameter is missing: grant_type"
}

我已经尝试从命令行运行 CURL

curl --data "code=AUTHORISATION_CODE&client_id=MY_CLIENT_ID.apps.googleusercontent.com&client_secret=MY_CLIENT_SECRET&redirect_uri=http://www.example.com/&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token

但我只是得到不同的回应

{
  "error" : "invalid_client",
  "error_description" : "The OAuth client was not found."
}

为什么仅仅获得一个访问令牌就这么难?

更新

我不知道发生了什么,但我不再收到该错误,我得到一个访问令牌但没有刷新令牌

我查看了这篇帖子 Not receiving Google OAuth refresh token 并撤销了对我的应用程序的访问权限以重新生成刷新令牌,但使用此代码会显示有关无效代码的错误

【问题讨论】:

  • 只是一个想法,但从redirect_uri 中省略最后一个/。或者以某种方式逃避。
  • 没有任何区别
  • 你说的。我从 redirect_url 中删除了尾部斜杠,并编辑了 redirect_url 以在控制台中匹配
  • 嗯,尝试交换 redirect_urigrant_type
  • 还是不行。我刚刚取出了redirect_url,它甚至没有抱怨,它只是说grant_type 丢失

标签: php curl access-token google-api-client


【解决方案1】:

我现在已经使用 Curl 解决了这个问题。似乎没有任何理由说明上述方法不能正常工作,只是继续尝试,在撤销对应用程序的访问权限、验证应用程序、获取代码并在 Curl 请求中使用代码之后,它最终工作了。

这解决了我之前的问题YouTube API v3 keeps asking for authorisation every time

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 2015-10-30
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多