为什么服务帐户无法访问公共共享日历来列出事件?

问题描述 投票:0回答:1

我正在使用 deno 和 https://googleapis.deno.dev/ 尝试从公开共享的日历中获取一些事件。

基本上,这是代码:

import { Calendar, auth } from "https://googleapis.deno.dev/v1/calendar:v3.ts";

const serviceAccountConfig = await Deno.readTextFile(Deno.env.get('GOOGLE_APPLICATION_CREDENTIALS'));

const credentials = auth.fromJSON(JSON.parse(serviceAccountConfig));
const calendar = new Calendar(credentials);

const cal = await calendar.eventsGet('<my-public-calendar-id-here>');
console.log(cal);

但这就是我得到的:

error: Uncaught (in promise) GoogleApiError: 401: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
      throw new GoogleApiError(
            ^
    at request (https://googleapis.deno.dev/_/base@v1/mod.ts:27:13)
    at eventLoopTick (ext:core/01_core.js:183:11)
    at async Calendar.eventsGet (https://googleapis.deno.dev/v1/calendar:v3.ts:476:18)

我尝试检查我使用的谷歌服务帐户是否需要某些日历权限,但我没有找到任何权限。另外,这段代码应该在后端运行,所以我想我应该使用服务帐户,而不是用户令牌(并记住我想要获得的内容具有公共访问权限)。有什么建议吗?

google-api deno google-api-nodejs-client
1个回答
0
投票
  • 您没有正确构建服务对象。
  • 这不是有效的日历 ID。
  • 您没有构建正确的授权凭证。

我的代码。

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
    let client =  new google.auth.GoogleAuth({keyFile: CREDENTIALS_PATH, scopes: SCOPES});
    return client
}

/**
 * Lists the next 10 events on a public holiday calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function listEvents(auth) {
    const calendar = google.calendar({version: 'v3', auth});
    const res = await calendar.events.list({
        calendarId: 'en.danish#[email protected]',
        timeMin: new Date().toISOString(),
        maxResults: 10,
        singleEvents: true,
        orderBy: 'startTime',
    });
    const events = res.data.items;
    if (!events || events.length === 0) {
        console.log('No upcoming events found.');
        return;
    }
    console.log('Upcoming 10 events:');
    events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.