2014-09-12 161 views
1

我一直在尝试使用Google Oauth2获取访问令牌和刷新令牌的最后几天,但没有获取任何地方。使用CURL获取Google Client API访问令牌

该文档是垃圾,我找不到任何可用的示例。

我刚刚开始使用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 --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." 
} 

为什么仅仅获取访问令牌非常困难?

UPDATE

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

我看了这个帖子Not receiving Google OAuth refresh token我已经取消了对我的应用程序的访问来重新生成刷新令牌,但使用此代码显示关于无效代码的错误

+0

只是一个想法,但省略了最后'/'从'redirect_uri'。或者以某种方式逃避。 – loveNoHate 2014-09-12 12:20:34

+0

没有任何区别 – AdRock 2014-09-12 12:37:34

+0

你做了什么? – loveNoHate 2014-09-12 12:41:42

回答

1

我现在已经使用Curl修复了此问题。似乎没有任何理由说明为什么上面的代码不能像继续尝试一样工作,它最终在撤销对应用程序的访问,authing应用程序,获取代码并在Curl请求中使用代码后生效。

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