Reputation: 1
I am trying to create a simple API call to create a Google Calendar Event with a Google Meet link in it but it seems I am unable to do so.
I looked up the Calendar API Documentation and have seen various examples but it still doesn't work for me. I am using a Service Account on NodeJS and a React frontend. Here below is the source code of my project.
const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');
var express = require('express');
var router = express.Router();
const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.addons.execute', 'https://www.googleapis.com/auth/calendar.settings.readonly', 'https://www.googleapis.com/auth/calendar.events'];
const GOOGLE_PRIVATE_KEY = "MY_PRIVATE_KEY"
const GOOGLE_CLIENT_EMAIL = "MY_SERVICE_ACCOUNT"
const GOOGLE_PROJECT_NUMBER = "MY_PROJECT_NUMBER"
const GOOGLE_CALENDAR_ID = "MY_CALENDAR_ID"
const jwtClient = new google.auth.JWT(
GOOGLE_CLIENT_EMAIL,
null,
GOOGLE_PRIVATE_KEY,
SCOPES,
"MY_PERSONAL_EMAIL"
);
const calendar = google.calendar({
version: 'v3',
project: GOOGLE_PROJECT_NUMBER,
auth: jwtClient
});
const auth = new GoogleAuth({
keyFile: 'credentials.json',
scopes: 'https://www.googleapis.com/auth/calendar', //full access to edit calendar
});
auth.getClient();
router.get("/demo", (req, res) => {
var event = {
'summary': 'My first event!',
'location': 'Hyderabad,India',
'description': 'First event with nodeJS!',
'start': {
'dateTime': '2022-06-28T09:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'end': {
'dateTime': '2022-06-29T17:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'attendees': [],
'reminders': {
'useDefault': false,
'overrides': [
{ 'method': 'email', 'minutes': 24 * 60 },
{ 'method': 'popup', 'minutes': 10 },
],
},
"conferenceData": {
'createRequest': {
"requestId": getRandomString(),
"conferenceSolution": {
"key": {
"type": "hangoutsMeet",
}
},
}
}
};
calendar.events.insert({
auth: auth,
calendarId: GOOGLE_CALENDAR_ID,
requestBody: event,
conferenceDataVersion: 1,
}, function (err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.data);
res.jsonp("Event successfully created!");
});
})
Upvotes: 0
Views: 946
Reputation: 156
Did you solve the Issue?
I also looked into this part because of a side project, and I'll share the code I've had success with.
I'm not sure which part is different when I look at it.
I hope this code helps.
/* index.js */
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const { v4: uuidv4 } = require('uuid');
const express = require('express');
const app = express()
// OAuth scope
const SCOPES = ['https://www.googleapis.com/auth/calendar.events'];
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
/* Reads previously authorized credentials from the save file. */
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
return null;
}
}
/* Serializes credentials to a file compatible with GoogleAUth.fromJSON. */
async function saveCredentials(client) {
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile(TOKEN_PATH, payload);
}
/* Load or request or authorization to call APIs. */
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}
/**
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
async function inserEvent(auth) {
const calendar = google.calendar({version: 'v3', auth});
const event = {
summary: 'Demo',
description: 'Demo for Google Meet',
start: {
dateTime: '2022-11-20T09:00:00+09:00',
timeZone: 'Asia/Seoul',
},
end: {
dateTime: '2022-11-20T09:30:00+09:00',
timeZone: 'Asia/Seoul',
},
conferenceData: {
createRequest: {
conferenceSolutionKey: {type: 'hangoutsMeet'},
requestId: uuidv4(),
},
},
attendees: [
{email: '${email1}'}, /* insert email */
{email: '${email2}'}, /* insert email */
],
reminders: {
useDefault: false,
overrides: [
{method: 'email', minutes: 60},
{method: 'popup', minutes: 10},
],
},
};
calendar.events.insert({
auth: auth,
calendarId: 'primary',
resource: event,
conferenceDataVersion: 1,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created, google meet link : %s', event.data.hangoutLink);
});
}
app.get("/demo", (rqe, res) => {
authorize().then(inserEvent).catch(console.error);
res.send('Good');
})
app.listen(3000, () => {
console.log('listening on port 3000');
})
Upvotes: 1