如何为Google Sheets API生成身份验证凭据?

时间:2018-09-26 20:43:39

标签: google-sheets-api

第1步(已完成):

按照指示,我已按照Google Node.js快速入门中的每个步骤进行操作: https://developers.google.com/sheets/api/quickstart/nodejs 它运行完美,没有任何错误。我的理解是,在运行index.js之后,将创建一个token.json。之后,我可以以某种方式将token.json用于将来的任何身份验证目的,而无需每次都使用凭据。如果在这个假设中我错了,请纠正我。我只是根据Google在先前给定的链接中所说的话做出这个假设-“授权信息存储在文件系统中,因此后续执行将不会提示授权。”

第2步(问题):

下面是Google Sheet API的文档页面提供的另一个代码段,用于读取多个范围数据: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchGet

但是,我不知道如何为authClient生成身份验证凭据。我想对token.json做些什么吗?如果是,那么使用token.json文件的协议是什么?

如有需要,请随时提出任何后续问题。

  enter code here// BEFORE RUNNING:
    // ---------------
    // 1. If not already done, enable the Google Sheets API
    //    and check the quota for your project at
    //    https://console.developers.google.com/apis/api/sheets
    // 2. Install the Node.js client library by running
    //    `npm install googleapis --save`

    const {google} = require('googleapis');
    var sheets = google.sheets('v4');

    authorize(function(authClient) {
      var request = {
        // The ID of the spreadsheet to retrieve data from.
        spreadsheetId: 'my-spreadsheet-id',  // TODO: Update placeholder value.

        // The A1 notation of the values to retrieve.
        ranges: [],  // TODO: Update placeholder value.

        // How values should be represented in the output.
        // The default render option is ValueRenderOption.FORMATTED_VALUE.
        valueRenderOption: '',  // TODO: Update placeholder value.

        // How dates, times, and durations should be represented in the output.
        // This is ignored if value_render_option is
        // FORMATTED_VALUE.
        // The default dateTime render option is [DateTimeRenderOption.SERIAL_NUMBER].
        dateTimeRenderOption: '',  // TODO: Update placeholder value.

        auth: authClient,
      };

      sheets.spreadsheets.values.batchGet(request, function(err, response) {
        if (err) {
          console.error(err);
          return;
        }

        // TODO: Change code below to process the `response` object:
        console.log(JSON.stringify(response, null, 2));
      });
    });

    function authorize(callback) {
      // TODO: Change placeholder below to generate authentication credentials. See
      // https://developers.google.com/sheets/quickstart/nodejs#step_3_set_up_the_sample
      //
      // Authorize using one of the following scopes:
      //   'https://www.googleapis.com/auth/drive'
      //   'https://www.googleapis.com/auth/drive.file'
      //   'https://www.googleapis.com/auth/drive.readonly'
      //   'https://www.googleapis.com/auth/spreadsheets'
      //   'https://www.googleapis.com/auth/spreadsheets.readonly'
      var authClient = null;

      if (authClient == null) {
        console.log('authentication failed');
        return;
      }
      callback(authClient);
    }

1 个答案:

答案 0 :(得分:0)

authClient参数应该代表什么?