Add event to google calendar using Refresh token

I tried to search it , but did not find any working solution. so work around it and below is js google client code.

using refresh token user will not ask for login.

Here is working solution. assuming you have already refresh_token.

<script async defer src=”https://apis.google.com/js/api.js” ></script>
<script async defer src=”https://apis.google.com/js/api.js” onload=”this.onload=function(){};handleClientLoad()” onreadystatechange=”if (this.readyState === ‘complete’) this.onload()”>
</script>
<script>
//https://developers.google.com/api-client-library/javascript/reference/referencedocs

var clientid = ‘xxxx’;
var apikey = ‘xxxx’;
var cilentsecret =’xxxx’;
var refresh_token = ‘xxxx’;
var discoveryUrl = “https://content.googleapis.com/discovery/v1/apis/calendar/v3/rest”
var SCOPE = ‘https://www.googleapis.com/auth/calendar’;
var auth_url = ‘https://www.googleapis.com/oauth2/v4/token’;
var calid = ‘xxxx’; //calendar id

function loadClient() {
gapi.client.setApiKey(apikey);
return gapi.client.load(discoveryUrl)
.then(function() { console.log(“GAPI client loaded for API”);
//run add event
execute();

},function(err) { console.error(“Error loading GAPI client for API”, err); });
}

// Make sure the client is loaded before calling this method.
function execute() {
return gapi.client.calendar.events.insert({
“calendarId”: calid,
“resource”: {
‘summary’: ‘ from shamah server now it is all auto event title will be here 8:00 am ‘,
“end”: { “dateTime”: “2018-07-03T10:00:00-07:00”},
“start”: { “dateTime”: “2018-07-03T10:00:00-07:00”}
}
}).then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log(“Response”, response);
},
function(err) { console.error(“Execute error”, err); });
}

function handleClientLoad() {
// Load the API’s client and auth2 modules.
gapi.load(‘client:auth2’, initClient);
console.log(‘gapi: I am loaded’);
}

function initClient() {

gapi.client.init({
‘apiKey’: apikey,
‘discoveryDocs’: [discoveryUrl],
‘clientId’: clientid,
‘scope’: SCOPE
}).then(function () {

//send request to get new access token
var data = {
‘client_id’: clientid,
‘client_secret’: cilentsecret,
‘refresh_token’: refresh_token,
‘grant_type’: ‘refresh_token’
};
var args = {
‘path’ : auth_url,
‘method’: ‘POST’,
‘params’: data
}
var r=gapi.client.request(args);

r.execute(mightbenewtoken);

gapi.auth2.getAuthInstance();

});
}
function mightbenewtoken(r) {
console.log(‘response form reques token’);
console.log(r);
gapi.client.setToken(r);
console.log(‘new token set’);
//load lib
loadClient();

}

</script>

get app key etc value from google developer console.

Hope this helped!

Leave a Reply

Your email address will not be published. Required fields are marked *