0

我有一个从 Script IT 的这一集修改的 Youtube Analyitics 电子表格!

http://www.youtube.com/watch?v=VVhsK5jH6u8

有没有办法存储刷新令牌而不是访问令牌,以便电子表格可以具有持久访问权限?我从 OAuth Playground 获得了刷新令牌,但仅用刷新令牌替换访问令牌似乎不起作用。许多人使用此电子表格,如果可能,我想避免每小时进行一次身份验证。

谢谢!

4

1 回答 1

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);
}
于 2013-10-08T14:48:42.317 回答