无法生成要发送给用户的 URL,以请求访问特定的非公共 google 表格



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

我已经在这里阅读并重新阅读了Google Sheet API,在这里阅读并重新阅读了Google REST API for Node,但是我无法将其应用于我的特定情况。

我能够成功地使用 REST API 指南来阅读有关用户 Google 云端硬盘中所有文件的元详细信息,但我实际需要的是阅读(并且只阅读,没有其他权限)一张谷歌表格。根据表 API,正确的范围是https://spreadsheets.google.com/feeds,但这是我可以从 API 使用的所有信息,因为代码仅用 Java/.NET 编写。

我已经在论坛上搜索了答案,但其中大多数都非常过时且不适用,我发现这篇文章建议使用 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);
      }
    }
  });
}

编辑1:在Sumnu2的帮助下,我合并了google-spreadsheets(之前注释掉了)。当我尝试运行该应用程序时,出现以下错误:无权查看工作表。这是有道理的,因为工作表是私有的,我需要生成一个允许我访问它的链接。我已经在这里发布了匆忙垃圾桶的代码

好的,我设法解决了它。问题是我没有调用正确的作用域,并将错误的回调函数传递给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);
              }
    });
    }
})
}

相关内容

  • 没有找到相关文章

最新更新