1

我正在尝试遵循文档,但从未连接 0Auth2。顺便说一句,我正在从谷歌表格脚本页面手动运行脚本,我应该在哪里得到允许访问的提示?(我不了解所有这些 0Auth2 方案,并且我已经授权运行脚本并获得客户端 ID 和机密)...见下面我的日志和脚本例程(第一次拍照仍然是简约的,因为我没有' t 还没有通过 0Auth2 步骤 ;-) 。提前感谢您的任何提示。我认为这将是微不足道的,因为它是我自己的工作表和谷歌照片帐户......

日志:

[19-01-06 17:50:05:809 CET] starting
[19-01-06 17:50:05:810 CET] getPhotoService
[19-01-06 17:50:05:849 CET] false
[19-01-06 17:50:05:850 CET] redirectURI=https://script.google.com/macros/d/[REMOVED]/usercallback
[19-01-06 17:50:05:864 CET] Open the following URL and re-run the script: https://accounts.google.com/o/oauth2/auth?client_id=[removed].apps.googleusercontent.com&response_type=code&redirect_uri=https%3A%2F%2Fscript.google.com%2Fmacros%2Fd%2F[removed]%2Fusercallback&state=[removed]&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fphotoslibrary.readonly&login_hint=[removed]&access_type=offline&approval_prompt=force

脚本:

function getPhotoService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  Logger.log('getPhotoService');
  return OAuth2.createService('gPHOTOfj')

  // enable caching on the service, so as to not exhaust script's PropertiesService quotas
  .setPropertyStore(PropertiesService.getUserProperties())
  .setCache(CacheService.getUserCache())

  // Set the endpoint URLs, which are the same for all Google services.
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')

  // Set the client ID and secret, from the Google Developers Console.
  .setClientId(CLIENT_ID)
  .setClientSecret(CLIENT_SECRET)

  // Set the name of the callback function in the script referenced
  // above that should be invoked to complete the OAuth flow.
  .setCallbackFunction('authCallback')
  //.setCallbackFunction('https://script.google.com/macros/d/'+SCRIPT_ID+'/authCallback')

  // Set the property store where authorized tokens should be persisted.
  .setPropertyStore(PropertiesService.getUserProperties())

  // Set the scopes to request (space-separated for Google services).
  .setScope('https://www.googleapis.com/auth/photoslibrary.readonly')

  // Below are Google-specific OAuth2 parameters.

  // Sets the login hint, which will prevent the account chooser screen
  // from being shown to users logged in with multiple accounts.
  .setParam('login_hint', Session.getActiveUser().getEmail())

  // Requests offline access.
  .setParam('access_type', 'offline')

  // Forces the approval prompt every time. This is useful for testing,
  // but not desirable in a production application.
  .setParam('approval_prompt', 'force');
}

function authCallback(request) {
  Logger.log('Called back!');
  var photoService = getPhotoService();
  var isAuthorized = photoService.handleCallback(request);
  if (isAuthorized) {
    Logger.log('Authorisation Success!');
  } else {
    Logger.log('Authorisation Denied...!');
  }
}

// Modified from http://ctrlq.org/code/20068-blogger-api-with-google-apps-script
function photoAPI() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length); 
  albums_sh.clear(); var nrow = new Array(); var narray = new Array(); 
  Logger.log("starting");  

  var service = getPhotoService();
  Logger.log(service.hasAccess());
  Logger.log('redirectURI='+service.getRedirectUri());

  if (service.hasAccess()) {

    var api = "https://photoslibrary.googleapis.com/v1/albums";

    var headers = {
      "Authorization": "Bearer " + service.getAccessToken()
    };

    var options = {
      "headers": headers,
      "method" : "GET",
      "muteHttpExceptions": true
    };

    var response = UrlFetchApp.fetch(api, options);

    var json = JSON.parse(response.getContentText());

    for (var i in json.items) {
      nrow = []; nrow.push(json.items[i].id);  nrow.push(json.items[i].name); nrow.push(json.items[i].url); narray.push(nrow);
    }
    albums_sh.getRange(1,1,narray.length,narray[0].length).setValues(narray);


  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log("Open the following URL and re-run the script: " + authorizationUrl);
  }
}
4

1 回答 1

2

所以它有效,如果其他人想使用它。但它很慢(我有 500 张专辑......):

function photoAPI() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length); 
  albums_sh.clear();
  var narray = []; 

  var api = "https://photoslibrary.googleapis.com/v1/albums";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true };

  var param= "", nexttoken;
  do {
    if (nexttoken)
      param = "?pageToken=" + nexttoken; 
    var response = UrlFetchApp.fetch(api + param, options);
    var json = JSON.parse(response.getContentText());
    json.albums.forEach(function (album) {
      var data = [
        album.title,
        album.mediaItemsCount,
        album.productUrl
      ];
      narray.push(data);
    });
    nexttoken = json.nextPageToken;
  } while (nexttoken);
  albums_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}
于 2019-01-08T20:21:45.173 回答