2017-01-09 39 views
1

檢索API調用令牌時面臨問題。這是我的代碼帶有PHP curl的Gmail API訪問令牌

$authUrl = "https://accounts.google.com/o/oauth2/token"; 

$curl = curl_init(); 

curl_setopt($curl, CURLOPT_URL, $authUrl); 
curl_setopt($curl, CURLOPT_POST, TRUE); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'code' => $code, 
    'client_id' => CLIENT_ID, 
    'client_secret' => CLIENT_SECRET, 
    'redirect_uri' => $redirectURL, 
    'grant_type' => 'authorization_code' 
)); 

$http_data = curl_exec($curl); 
curl_close($curl); 

var_dump($http_data); 

$ http_data表示無效請求。

我的任務是讓我的Gmail帳戶中的所有電子郵件,我認爲我需要訪問令牌。請指教。

Thanx提前。

+0

[OAuth 2.0在PHP中使用捲曲]可能重複(http://stackoverflow.com/questions/25423924/oauth-2-0-in-php-using-curl) – DaImTo

+0

仍然會收到invalid_request錯誤。我的代碼有問題。 – Arpit

回答

0

首先,您似乎將所有參數作爲HTTP GET字符串的一部分添加,這是一個HTTP POST調用。此外,您似乎忘記了包含您從第一部分認證流程獲得的代碼

這是驗證碼,它用於請求刷新 令牌。它在html的正文中顯示給用戶,以及頁面標題中的 。要獲取刷新令牌,您需要將 認證碼發送回Google。注意:這是一個HTTP帖子,您不能將 放在瀏覽器中,該瀏覽器將會是HTTP Get。注: grant_type = authorization_code

https://accounts.google.com/o/oauth2/token 
code={Your code from the first part of flow}&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code 

注意你使用Google APIs PHP Client library將處理所有這一切都爲你考慮?

代碼從我的Google 3 legged Oauth2 flow文章中翻錄。

+0

$ authUrl =「https://accounts.google.com/o/oauth2/token」; $ curl = curl_init(); curl_setopt_array($捲曲,陣列( CURLOPT_POST =>真, CURLOPT_POSTFIELDS =>數組( '代碼'=> $代碼, 'CLIENT_ID'=> CLIENT_ID, 'client_secret'=> CLIENT_SECRET, 'REDIRECT_URI'= > getRedirectUri(), 'grant_type'=> 'authorization_code' ) CURLOPT_URL => $ authUrl, CURLOPT_SSL_VERIFYPEER =>假, CURLOPT_RETURNTRANSFER =>真 )); $ http_data = curl_exec($ curl); curl_close($ curl); – Arpit

+0

使用上述代碼獲取令牌。但得到空白的迴應。這裏$ code是4/EfvRZ7kEGBOK7TXfuYba4mDAdRUakUbd5is4IdEYJ8Q#請指教代碼有什麼問題。抱歉無法格式化代碼。 – Arpit

+0

編輯你的問題,並做出任何你需要的改變 – DaImTo