Skip to content

Instantly share code, notes, and snippets.

@subrotoice
Last active February 25, 2025 13:58
Show Gist options
  • Save subrotoice/2253fa644128bab0fd12d6102466fe66 to your computer and use it in GitHub Desktop.
Save subrotoice/2253fa644128bab0fd12d6102466fe66 to your computer and use it in GitHub Desktop.
Google Calender API
// Refresh Token: A long-lived token that is used to obtain a new access token without requiring user re-authentication.
// Access Token: A short-lived token (usually expires in 1 hour) that allows your application to access Google APIs on behalf of a user. It must be included in API requests as an Authorization header (e.g., Bearer <access_token>). Once expired, a new access token must be obtained using the refresh token.
// Step1: Get Authentication code (client_id, redirect_uri, state(custom_info))
https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/calendar%20https://www.googleapis.com/auth/calendar.events&access_type=offline&include_granted_scopes=true&response_type=code&state=11181&redirect_uri=https://vioniko.com/calendar/&client_id=346714970482-fe89v693ot2oos92ujeb6o14nkmvrai2.apps.googleusercontent.com&prompt=select_account
// Step2: Redirect url make auth code to refresh token
if (isset($_GET['code']) and $_GET['code'] != '') {
$userId = $_GET['state'];
$calenderapi = mysql_fetch_array(mysql_query("SELECT * FROM calenderapi WHERE userid=$userId", $conexion));
?>
<script>
var settings = {
"url": "https://oauth2.googleapis.com/token",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"code": "<?= $_GET['code'] ?>",
"client_id": "<?= $calenderapi['clientid'] ?>",
"client_secret": "<?= $calenderapi['clientsecret'] ?>",
"redirect_uri": "https://vioniko.com/calendar/",
"grant_type": "authorization_code"
}
};
$.when($.ajax(settings)).then(function(response, textStatus, jqXHR) {
var refresh_token = response.refresh_token;
// console.log(response);
// console.log(refresh_token);
if (refresh_token != null) {
var url = "ajaxLoad.php?refresh_token=" + refresh_token + "&userId=" + <?= $_GET['state'] ?>;
$.get(url, function(response) {
// var obj = jQuery.parseJSON(response);
// console.log(response);
window.location.replace("https://vioniko.com/agenda/agenda_config.php?lang=es&calender=1");
});
} else {
$('.info').html("<h4 style='color: red;'>Refresh Token already exist. First you have to remove it.</h4>")
console.log("No Refresh Token");
}
});
</script>
// Step3: Refresh token -> Access Token(Event creationg)
<?php
$calenderapi = mysql_fetch_array(mysql_query("SELECT * FROM calenderapi WHERE userid=$usu_valido" , $conexion));
?>
var start = forma.fecha_evento.value + 'T' + (parseInt(forma.hora.value)).toString() + ':' + forma.minuto.value + ':00';
var end = forma.fecha_evento.value + 'T' + (parseInt(forma.hora.value)+1).toString() + ':' + forma.minuto.value + ':00';
var message = forma.texto_evento.value;
if(document.forma.tipo_evento.value == '24') {
var settings = {
"url": "https://oauth2.googleapis.com/token",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"client_id": "<?=$calenderapi['clientid']?>",
"client_secret": "<?=$calenderapi['clientsecret']?>",
"refresh_token": "<?=$calenderapi['refreshtoken']?>",
// "client_id": "346714970482-fe89v693ot2oos92ujeb6o14nkmvrai2.apps.googleusercontent.com",
// "client_secret": "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" ,
// "refresh_token": "1//04nD-p69ERXXHCgYIARAAGAQSNwF-L9IrPVLp0a9txsN38WvwqCPzxTN0k6LoiPb3MWPD17W8CuaZEdqGCp7fPWUAyRUszb3-gEc",
"grant_type": "refresh_token"
}
};
$.ajax(settings).done(function (response) {
var jsonData = JSON.stringify(response)
console.log(response.access_token);
// Email, Secret Key, Client ID, Client Secret, Refresh_token
var settings = {
// "url": "https://www.googleapis.com/calendar/v3/calendars/[email protected]/events?key=AIzaSyAr9q51AHnxdPxFjTChPYg1LZwk7q5y2S4",
"url": "https://www.googleapis.com/calendar/v3/calendars/<?=$calenderapi['email']?>/events?key=<?=$calenderapi['secretkey']?>",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + response.access_token
},
"data": JSON.stringify({
"start": {
"dateTime": start,
"timeZone": "<?=$calenderapi['timeZone']?>"
},
"end": {
"dateTime": end,
"timeZone": "<?=$calenderapi['timeZone']?>"
},
"summary": "<?=$rowPRO['nombre'].' '.$rowPRO['apellidos']?>",
"description": message,
"location": "Chicago"
}),
};
$.when( $.ajax( settings ) ).then(function( response, textStatus, jqXHR ) {
// alert( response.created ); // Alerts 200
var formData = $("#forma").serialize();
$.ajax({
url: "grabar_evento2.php",
type: "POST",
data: formData,
dataType: "html",
})
.done(function (response) {
var responseObj = jQuery.parseJSON(response);
$('.response').html( '<div class="alert alert-success" role="alert">'+ responseObj.message +'</div>' ).fadeTo('slow', 1);
if(responseObj.status=='created'){
$('<tr><td>'+ responseObj.date +'</td><td>'+ responseObj.time +'</td><td>'+ responseObj.type +'</td><td>'+ responseObj.text +'</td><td> </td><td> </td><td> </td></tr>').prependTo('table.infoTable>tbody');
}
})
.fail(function () {
alert("Ajax Submit Failed ...");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment