我有以下基本代码来读取一些日历事件。该日历是由普通私人 Google 用户公开共享的。
为了使用 google api,我设置了一个具有所有者角色的服务帐户,只是为了让事情变得简单。 通过使用 https://deno.land/x/google_deno_integration 我尝试确保我使用的是 OAuth2,并且根据此 answer 可以进行访问
import { GoogleAPI } from "https://deno.land/x/google_deno_integration/mod.ts";
const serviceAccountConfig = await Deno.readTextFile(Deno.env.get('GOOGLE_APPLICATION_CREDENTIALS'));
const credentials = JSON.parse(serviceAccountConfig);
const cal_id = 'my-cal-id';
const api = new GoogleAPI({
email: "[email protected]",
scope: ["https://www.googleapis.com/auth/calendar.events"],
key: credentials.private_key,
});
const calget = await api.get(`https://www.googleapis.com/calendar/v3/calendars/${cal_id}`);
console.log(calget);
不幸的是,这是我得到的答案:
$ deno run --allow-env --allow-read --allow-net index.2.ts
{
error: {
code: 403,
message: "Request had insufficient authentication scopes.",
errors: [
{
message: "Insufficient Permission",
domain: "global",
reason: "insufficientPermissions"
}
],
status: "PERMISSION_DENIED",
details: [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
reason: "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
domain: "googleapis.com",
metadata: {
service: "calendar-json.googleapis.com",
method: "calendar.v3.Calendars.Get"
}
}
]
}
}
我不知道我的服务帐户设置是否错误(这里是谷歌云的第一个小时用户),我正在做的事情是否可行,或者我没有考虑到它是否有问题。
是的,您可以使用服务帐户来读取公共日历。关键是它必须是公开的。这意味着您只能对其进行只读访问。
在下面的例子中。我正在阅读丹麦假期日历。
// npm install googleapis@105 @google-cloud/[email protected] --save
// npm install googleapis
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/calendar'];
const CREDENTIALS_PATH = 'C:\\Development\\FreeLance\\GoogleSamples\\Credentials\\ServiceAccountCred.json';
/**
* 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}`);
});
}
authorize().then(listEvents).catch(console.error);
我真的不知道为什么当你可以使用 API 密钥并获得相同的结果时,你会想要这样做
const {google} = require('googleapis');
const API_KEY = "[REDACTED]"
/**
* Lists the next 10 events on a public holiday calendar.
*/
async function listEvents() {
const calendar = google.calendar({version: 'v3', auth: API_KEY});
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}`);
});
}
listEvents().catch(console.error);