无法生成 URL 以发送给请求访问特定非 public google sheet 的用户

Unable to generate URL to send to user for requesting access to a particular non-public google sheet

过去几天我一直在尝试解决这个问题,但我无法成功。 我需要生成一个 url,它要求用户允许阅读他们的特定 Google Sheet,如果他们同意,我将有权阅读 sheet .

我已经反复阅读 Google Sheet API here, and the Google REST API for Node here,但我无法将其应用于我的特定案例。

我能够成功使用 REST API 指南读取用户 Google 驱动器中所有文件的元详细信息,但我真正需要的是读取(并且只读取,没有其他许可)只有一个 google sheet。根据 Sheet API,正确的范围是 https://spreadsheets.google.com/feeds,但这就是我可以从 API 使用的所有信息,因为代码只写在 [=33] =]/.NET。

我在论坛上搜索了答案,但大多数都非常过时且不适用,我发现 post 建议使用 node-google-spreadsheets,但文档没有提供足够的信息来说明如何实际使用它。我在下面附上了我的代码。连同关于我在哪里遇到问题的注释。我将不胜感激任何帮助,因为我已经筋疲力尽地试图让它发挥作用。谢谢 (:

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var GoogleSpreadsheets = require('google-spreadsheets');


var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']; //This scope works just fine when reading metadata, but to readspreedsheets, I think the correct one is: https://spreadsheets.google.com/feeds
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'drive-nodejs-quickstart.json';

fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }

  authorize(JSON.parse(content), listFiles);
});


/*************************************No Idea where to put this code:  

var oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// Assuming you already obtained an OAuth2 token that has access to the correct scopes somehow...
oauth2Client.setCredentials({
    access_token: ACCESS_TOKEN,
    refresh_token: REFRESH_TOKEN
});

GoogleSpreadsheets({
    key: '<spreadsheet key>',
    auth: oauth2Client
}, function(err, spreadsheet) {
    spreadsheet.worksheets[0].cells({
        range: 'R1C1:R5C5'
    }, function(err, cells) {
        // Cells will contain a 2 dimensional array with all cell data in the
        // range requested.
    });
});



************************************************************/


function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}


function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}


function listFiles(auth) {
  var service = google.drive('v3');
  service.files.list({
    auth: auth,
    pageSize: 10,
    fields: "nextPageToken, files(id, name)"
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var files = response.files;
    if (files.length == 0) {
      console.log('No files found.');
    } else {
      console.log('Files:');
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        console.log('%s (%s)', file.name, file.id);
      }
    }
  });
}

Edit1:在 Sumnu2 的帮助下,我合并了 google-spreadsheets(之前已注释掉)。当我尝试 运行 应用程序时,出现以下错误:未授权查看 sheet。这是有道理的,因为 sheet 是私有的,我需要生成一个 link 允许我访问它。我已经 post 编辑了 haste bin 上的代码 here

好的,我设法解决了。问题是我没有调用正确的范围,并将错误的回调函数传递给 authorize 方法。这是正确的代码:

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var GoogleSpreadsheets = require('google-spreadsheets');
var secrets = require('./client_secret.json');

var SCOPES = ['https://spreadsheets.google.com/feeds', 'https://spreadsheets.google.com/feeds/worksheets/key/private/basic',
             ];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'drive-nodejs-quickstart.json';

fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }

  authorize(JSON.parse(content), getSheet);
});



function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
   oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}


function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

function getSheet(auth) {
GoogleSpreadsheets({
    key: '<SpreadSheetKey>',
    auth: oauth2Client
}, function(err, spreadsheet) {
    if (err) {
        console.log('--------------err: ');
        console.log(err);
        return;
    } else {
        console.log('--------------reading sheet: ');  

        spreadsheet.worksheets[0].cells({

        }, function(err, cells) {
              console.log('================MADE IT HERE!!!!!!!!!!!!!!');

              if (err) {
                  console.log(err);
                  return;
              }

              for(var prop in cells) {
                  console.log('for loop');
                  var value = cells[prop];
                  console.log(prop, value);
              }

    });

    }
})
}