我使用谷歌API客戶端的谷歌分析使用OAuth 2.0谷歌的OAuth:無法獲取刷新令牌與授權碼
我讀這得到刷新令牌,但不會出現它:https://developers.google.com/identity/protocols/OAuth2WebServer#offline
我只得到這個代替:
{
"access_token": "ya29.twHFi4LsiF-AITwzCpupMmie-fljyTIzD9lG8y_OYUdEGKSDL7vD8LPKIqdzRwvoQAWd",
"token_type": "Bearer",
"expires_in": 3599,
"id_token": "very long string"
}
下面是代碼:
的Javascript(獲取Authorizat離子碼):的作品
gapi.analytics.ready(function() {
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: '257497260674-ji56vq885ohe9cdr1j6u0bcpr6hu7rde.apps.googleusercontent.com',
});
gapi.analytics.auth.on('success', function(response) {
var code = response.code;
$.ajax({
url: "getTokensFromCode.php",
method: "GET",
data: {
"code": code
},
success: function (tokens) {
// I can't get refresh token here, only get "access_token" and "id_token"
console.log(tokens);
}
});
});
});
PHP(交換授權代碼標記):不起作用
// I get the authorization code in Javascript
$code = $_GET['code'];
$redirectURI = "postmessage";
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectURI);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($code);
$tokens = $client->getAccessToken();
echo $tokens;
我需要在JavaScript中刷新令牌,這就是爲什麼我在Javascript中獲得授權代碼併發出Ajax請求來獲取刷新令牌的原因。
我需要授予訪問權限一次,並且無需再次登錄(我需要向我的網站的訪問者顯示數據)而始終獲取分析數據。這就是爲什麼我要'refresh_token'('access_token'只能持續1小時)。 爲了在第一次登錄後獲得'refresh_token',我試過了這個: '$ client-> setAccessType('offline'); $ client-> setApprovalPrompt('force');' – enguerran
我撤銷了訪問並再次登錄,它沒有給我一個'refresh_token'。無論如何,我認爲JS-Ajax-PHP沒有用,我會嘗試一個完整的PHP解決方案,如Google文檔所示。我嘗試過這種方法,因爲我想用Javascript中的'refresh_token',但正如你所說的那樣,反正它不安全。 – enguerran