2014-12-04 70 views
5

我的最終目標是通過Google Gmail API向我發送電子郵件。代幣段數量錯誤(OAuth Google Api)

這是我的問題。

當我得到我的訪問令牌錯誤彈出

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Wrong number of segments in token: ' 

我讀到這裏Cloud endpoints oauth2 error「這並不意味着你的令牌無效」,但我發現了一個致命的錯誤打斷我的劇本。

我的訪問令牌看起來像這樣4/MqiIIl5K4S3D4iiieHshQt5D4M79oo07SbhMn22oe2o.cswa8t9ZuDAfJvIeHux6iLYXpNQmlAI

如果我刷新這個令牌的頁面我會得到另一個錯誤,這是

'Error fetching OAuth2 access token, message: 'invalid_grant: Invalid code.' 

這裏是我的代碼

<?php 

include_once "templates/base.php"; 
echo pageHeader("Simple API Access"); 

require_once realpath(dirname(__FILE__) . '/../autoload.php'); 


$client = new Google_Client(); 


$client_id = '114600397795-j5sn0gvsdrup0s8dcmsj49iojp3m9biu.apps.googleusercontent.com'; 
$client_secret = 'm3Dzankql_rs1OGICsA3Hbtc'; 
$redirect_uri = 'http://alupa.com/gmail/examples/simple-query.php'; 

$client->setClientId($client_id); 
$client->setClientSecret($client_secret); 
$client->setRedirectUri($redirect_uri); 

$client->addScope("https://www.googleapis.com/auth/gmail.readonly"); 
$client->addScope("https://mail.google.com/"); 

$apiKey = "AIzaSyCWXxrTshKsotxEYNZZCXxdVXhLeku55cw"; 
$client->setDeveloperKey($apiKey); 


if (isset($_GET['code'])) { 
    $client->authenticate($_GET['code']); 
    $_SESSION['access_token'] = $client->getAccessToken(); 
    //$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
    //header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); 
}else{ 

$client->setApplicationName("Client_Gmail_Examples"); 

} 


if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
    $client->setAccessToken($_SESSION['access_token']); 
} else { 
    $authUrl = $client->createAuthUrl(); 
} 

if ($client->getAccessToken()) { 
    $_SESSION['access_token'] = $client->getAccessToken(); 
    $token_data = $client->verifyIdToken()->getAttributes(); 
} 


?> 
<div class="box"> 
    <div class="request"> 
<?php 
if (isset($authUrl)) { 
    echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>"; 
} else { 
    echo "<a class='logout' href='?logout'>Logout</a>"; 
} 
?> 
    </div> 
</div> 

alupa.com是我的本地域,我沒有看到任何問題與

我使用原來的庫從谷歌https://github.com/google/google-api-php-client

+0

我有同樣的問題。令牌沒有全部數據。你解決了嗎? – 2015-02-15 11:29:55

回答

3

變化:

$token_data = $client->verifyIdToken()->getAttributes(); 

到:

$tuan = $client->getAccessToken(); 
$token_data = $client->verifyIdToken($tuan->id_token); 
1

您需要添加範圍的OpenID,然後你會得到一個id_token以及訪問令牌。然後,您使用ID標記與$ client-> verifyIdToken