给定来自 google oauth 请求的离线代码,我如何使用 node.js 获取 google 日历信息?

Given an offline code from a google oauth request, how can I get google calendar information with node.js?

我将前端流程用于:

      let { code } = await this.auth2.grantOfflineAccess({
        prompt: "select_account"
      });

我有那个代码,然后我想访问用户日历。我试过了:

const { google } = require('googleapis')
const googleCalendar = google.calendar('v3')
let calendarList = await googleCalendar.calendarList.list({
  auth: code
})

但这似乎不起作用。那么如何使用离线 code 获取日历信息呢?

  • 您想使用通过授权代码检索到的访问令牌来使用日历 API。
  • 您已经可以使用日历 API,并且还可以检索授权码。
  • 您想使用带有 Node.js 的 googleapis 来实现此目的。

如果我的理解是正确的,这个修改怎么样?首先,请使用授权码检索访问令牌。然后,您可以使用 API 使用访问令牌。

修改后的脚本:

当您的脚本修改时,请修改如下。在使用此脚本之前,请设置变量 codeclient_idclient_secretredirect_uris

const { google } = require('googleapis')

// Please set the following variables.
const code = "###";
const client_id = "###";
const client_secret = "###";
const redirect_uris = "###";

// Retrieve access token.
const oauth2Client = new google.auth.OAuth2(
  client_id,
  client_secret,
  redirect_uris
);
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);

// Use Calendar API
const googleCalendar = google.calendar({ version: "v3" });
let calendarList = await googleCalendar.calendarList.list({
  auth: oauth2Client
});
console.log(calendarList.data);

注:

  • 授权码只能使用一次。所以请注意这一点。

参考:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。