Skip to content

Instantly share code, notes, and snippets.

@fady-nasser
Created August 27, 2022 07:18
Show Gist options
  • Save fady-nasser/edc39066615df81d50158d96e42cf388 to your computer and use it in GitHub Desktop.
Save fady-nasser/edc39066615df81d50158d96e42cf388 to your computer and use it in GitHub Desktop.
Google Calendar API Example
<script src="https://apis.google.com/js/api.js" id="calendarScript"></script>
<input
type="button"
value="Create Calendar Event"
onclick="addCalendarEvent()"
/>
function addCalendarEvent() {
var event = {
summary: "Google I/O 2015",
location: "800 Howard St., San Francisco, CA 94103",
description: "A chance to hear more about Google's developer products.",
start: {
dateTime: "2020-01-28T09:00:00-07:00",
timeZone: "America/Los_Angeles"
},
end: {
dateTime: "2020-01-28T17:00:00-07:00",
timeZone: "America/Los_Angeles"
},
recurrence: ["RRULE:FREQ=DAILY;COUNT=2"],
attendees: [{ email: "[email protected]"}],
reminders: {
useDefault: false,
overrides: [
{ method: "email", minutes: 24 * 60 },
{ method: "popup", minutes: 10 }
]
}
};
window.googleCalendar.createEvent(event);
}
window.addEventListener("load", function() {
let credentials = {
scope:
"https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events",
clientId:
"755605534058-mvo5t4ut6di8jj57t37uoohkppi7qrg7.apps.googleusercontent.com",
apiKey: "AIzaSyBK8Eo16V2bQYTYCP0ClJNKNOw7T308j44",
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"
]
};
window.googleCalendar = new googleCalendar(credentials);
});
class googleCalendar {
constructor(credentials) {
//load dependencies...
this.gapi = gapi;
this.gapi.load("client:auth2", init.bind(this));
let cal = this;
//create call stack...
this.callStack = {};
function init() {
//authorize api access...
this.gapi.client
.init({
apiKey: credentials.apiKey,
clientId: credentials.clientId,
scope: credentials.scope,
discoveryDocs: credentials.discoveryDocs
})
.then(function() {
cal.gapi.auth2.getAuthInstance().isSignedIn.listen(updateCallstack);
function updateCallstack() {
cal.callStack.func(cal.callStack.args);
}
});
}
}
userAuthStatus() {
if (!this.gapi.auth2.getAuthInstance().isSignedIn.get()) {
this.gapi.auth2.getAuthInstance().signIn();
}
return this.gapi.auth2.getAuthInstance().isSignedIn.get();
}
createEvent(event) {
if (this.userAuthStatus()) {
let request = this.gapi.client.calendar.events.insert({
calendarId: "primary",
resource: event
});
request.execute(function(e) {
alert("done");
console.log(e);
});
} else {
this.callStack.func = this.createEvent.bind(this);
this.callStack.args = event
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment