我有一个Youtube Analyitics电子表格,从这一集的脚本IT修改过来!
http://www.youtube.com/watch?v=VVhsK5jH6u8
有没有办法存储刷新令牌而不是访问令牌,以便电子表格可以持久访问?我从OAuth Playground获得了刷新令牌,但仅使用刷新令牌替换访问令牌似乎不起作用。 很多人使用这个电子表格,我想尽可能避免每小时的身份验证。
谢谢!
答案 0 :(得分:1)
在此处查看此代码示例 - https://github.com/entaq/GoogleAppsScript/blob/master/IO2013/YouTubeAnalytics/oauth2.gs
我已经改进了那里的OAuth库,以便在它到期时自动刷新令牌。这种方式非常可扩展,您不必“引导”并存储任何东西。
重要位 -
function attemptTokenRefresh_() {
var refreshToken = UserProperties.getProperty(refreshTokenPropertyName);
if (!refreshToken) {
Logger.log('No refresh token available to refresh with ' + tokenKey);
return false;
}
var requestData = {
method: 'post',
payload: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}
};
Logger.log('Attempting token refresh');
var response = UrlFetchApp.fetch(TOKEN_URL, requestData).getContentText();
storeOAuthValues_(response);
return true;
}
function storeOAuthValues_(response){
var tokenResponse = JSON.parse(response);
var accessToken = tokenResponse.access_token;
// expires_in is in seconds and Date.now is ms
var endMs = Date.now() + tokenResponse.expires_in * 1000;
var refreshToken = tokenResponse.refresh_token;
//store the token for later retrival
UserProperties.setProperty(oauthTokenPropertyName, accessToken);
if (refreshToken) { //on a refresh call we wont get a new refresh token, lets not wipe prev one out
UserProperties.setProperty(refreshTokenPropertyName, refreshToken);
}
UserProperties.setProperty(oauthTokenExpiresPropertyName, endMs);
}