Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Google Calendar API from Node server

For some reason, I am having a really hard time accessing Google calendar.

I want to be able to add and remove events in a calendar from my Node.js server.

I am finding really conflicting information from the documents.

I followed - https://developers.google.com/identity/protocols/OAuth2ServiceAccount which gives a good guide on how to get an acccess token but then at the end it appears it is only for accessing Drive.

I then followed Google Calendar API v3 Access Not Configured which states you only need an API key but this appears as though it is all done from client side so maybe it's different?

I looked at https://developers.google.com/google-apps/calendar/quickstart/nodejs as well but that seems very complicated just to make a simple API call to a calendar. The sample code references files which isn't clear where they come from or how to structure them. E.g. var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';

I simple guide on how to achieve this would be hugely appreciated.

Thanks

like image 441
Stretch0 Avatar asked Jul 07 '17 03:07

Stretch0


People also ask

How do I access Google Calendar API?

Enable API accessIn the API Manager pane, click Library to see the list of available APIs. In the Google Apps APIs list, scroll down to click or search for Calendar API, then on the API page, click Enable.


1 Answers

I was in the same situation as you. Google does not have documentation for server-to-server authentication for nodejs client API. Ridiculous. Finally I found the solution here. Basically you need a service account key (JSON file usually) and google.auth.JWT server-to-server OAuth 2.0 client.

let google = require('googleapis');
let privatekey = require("./privatekey.json");
// configure a JWT auth client
let jwtClient = new google.auth.JWT(
       privatekey.client_email,
       null,
       privatekey.private_key,
       ['https://www.googleapis.com/auth/calendar']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
 if (err) {
   console.log(err);
   return;
 } else {
   console.log("Successfully connected!");
 }
});

Now just call calendar API like that:

let calendar = google.calendar('v3');
calendar.events.list({
   auth: jwtClient,
   calendarId: 'primary'//whatever
}, function (err, response) {

});
like image 136
ZuzEL Avatar answered Sep 27 '22 22:09

ZuzEL