2011-04-16 146 views
5

我需要獲取Google有效令牌才能使用Google API,但我的代碼不能使用 。你能請教我嗎?獲取Google API令牌

$client_id = '495225261106.apps.googleusercontent.com'; 
$client_secret = urlencode('MY_SECRET_CDE'); 
$redirect_uri = urlencode('http://MYPAGE.net/test.php'); 
//$grant_type = urlencode('authorization_code'); //it does not work either. 
$grant_type = 'authorization_code'; 

$post_string = "code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uri}&grant_type={$grant_type}"; 

//echo_key_value('post_string',$post_string); 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
$result = curl_exec($ch); // Execute the HTTP command 
$errmsg = curl_error($ch); 

if($errmsg) echo $errmsg; 

// 輸出: { 「錯誤」: 「invalid_grant」} //

謝謝!

+0

我想在javascript來實現此但遇到同樣的錯誤。我試過從命令行使用curl,但仍然沒有運氣。我已按照[本頁](http://code.google.com/apis/accounts/docs/OAuth2.html)上的指示操作,轉至T. – Abe 2011-05-19 21:34:51

回答

1

您可能會發現通過其中一個官方客戶端庫更容易使用Google API,尤其是OAuth內容。

下面是PHP的一個鏈接:http://code.google.com/p/google-api-php-client/

和鏈接上的OAuth 2.0文檔與庫(有一些很好的例子代碼):http://code.google.com/p/google-api-php-client/wiki/OAuth2

+0

我有同樣的問題,無效授權,我爲了調試目的,用瀏覽器發佈數據。使用他們的庫不能解釋爲什麼會出現錯誤 – 2012-02-10 00:16:00

1

在使用postfields之前,你不必把「curl_setopt($ ch,CURLOPT_POST,true);」嗎?我正在工作,除此之外,我沒有在我的祕密上使用urlencode,它是一樣的