使用NodeJS在Heroku上验证Google Sheet API

pee*_*lte 4 google-api heroku google-docs-api node.js google-oauth

我按照此示例访问Google表格API:

https://developers.google.com/sheets/api/quickstart/nodejs

在示例代码中,以下方法用于获取新的oauth令牌.

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);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

这在我的本地计算机上工作正常(在终端中按提示手动访问页面,并在命令行中输入代码).但这似乎不切实际,并不适用于Heroku.有没有办法自动化这个?也许通过在nodeJS应用程序中获取URL(和令牌)并以某种方式存储它?

提前致谢.

pee*_*lte 8

好的,所以我最终使用的服务帐户密钥可以在https://console.developers.google.com上生成.这将生成一个JSON文件,您需要两个值:private_keyclient_email.

要在本地测试,可以下载dotenv npm模块,该模块允许您将Environment变量存储.env在项目根目录中的文件中.您的.env文件将如下所示:

GOOGLE_PRIVATE_KEY=<your-key-here-withouth-quotes>
GOOGLE_CLIENT_EMAIL=<your-email-here-withouth-quotes>
Run Code Online (Sandbox Code Playgroud)

在通过git部署heroku应用程序时,不要忘记将.env文件添加到.gitignore列表中.

我的auth.js文件看起来像这样:

const GoogleAuth = require('google-auth-library');

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];

function authorize() {
    return new Promise(resolve => {
        const authFactory = new GoogleAuth();
        const jwtClient = new authFactory.JWT(
            process.env.GOOGLE_CLIENT_EMAIL,
            null,
            process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'), 
            SCOPES
        );

        jwtClient.authorize(() => resolve(jwtClient));
    });
}

module.exports = {
    authorize,
}
Run Code Online (Sandbox Code Playgroud)

请注意私钥变量后面的替换功能.

我的app.js(主文件)看起来像这样:

require('dotenv').config();
const google = require('googleapis');
const sheetsApi = google.sheets('v4');
const googleAuth = require('./auth');

const SPREADSHEET_ID = 'Your-spreadsheet-ID';

googleAuth.authorize()
    .then((auth) => {
        sheetsApi.spreadsheets.values.get({
            auth: auth,
            spreadsheetId: SPREADSHEET_ID,
            range: "'Tab Name'!A1:H300",
        }, function (err, response) {
            if (err) {
                console.log('The API returned an error: ' + err);
                return console.log(err);
            }
            var rows = response.values;
            console.log(null, rows);
        });
    })
    .catch((err) => {
        console.log('auth error', err);
    });
Run Code Online (Sandbox Code Playgroud)

如果您收到以下错误:

The API returned an error: Error: The caller does not have permission

使用google_client_email分享您尝试加载的电子表格,然后重试.

如果一切都在本地工作,请通过访问您的heroku帐户并转到settings并单击reveal config vars并部署该应用程序,将环境变量添加到您的heroku应用程序中.如果一切顺利,您应该可以访问该文档.