Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

jquery - How to add events to Google Calendar using FullCalendar

I have searched through FullCalendar documentation and googled around but I haven't been able to find how to add events to Google Calendar using FullCalendar. I have tried using js Google APIs for Google Calendar but I am quite new to js and I have not resolved. So my question is: I have a website in which I used FullCalendar to manage a Google Calendar but I am not able to add events to it. Is there someone who can help me, maybe with a full working example? Many thanks for your precoius help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem. I read many documentation, and at last I got a working Code. I share it here whith you:

This is how to actually add an event in Google Cal from Fullcalendar (which I like very much) :

FIRST : GET A CUSTOM FORM from FullCalendar

 $('#calendar').fullCalendar({
    set all options : options,
    selectable: true,
    selectHelper: true,
    // here is the part :
    select: function(start, end) {
            modalbox(start.format(),end.format());
    },
    editable: true
 });

So, I make a modal Box when I select a time range (so that I can manage the inputs myself). I use here start.format() so that the DateTime is already in a GoogleFormat.

SECOND : CREATE YOUR FORM

1/ I create the form

(in modal window). It will contain all the info for Google Calendar.

<script type='text/javascript'>

$(function() {

function modalbox(start,end) {
    ID = "popup";
    // Title
    var pop_content = '<h2>New event:</h2>
    <form><div style="float:left;width:70%;text-align:right"><INPUT TYPE="TEXT" ID="title" style="width:200px;height:30px;line-height:30px;margin:5px;background-color:#EEF4F7" NAME="title" ><br>';
    // Place
    pop_content += '<div style="font-size:11px;color:gray;margin-top:10px">Place: <INPUT TYPE="TEXT" ID="where_event" style="width:200px;height:20px;line-height:20px;margin:3px;vertical-align:middle"  NAME="where_event"><br>';
    // Description
    pop_content += 'Content : <TEXTAREA ID="content_event" style="width:200px;height:60px;margin:3px;font-family:sans-serif;font-size:13px;vertical-align:middle" NAME="content_event"></TEXTAREA></div> </div>';
    // Submit       
    pop_content += '<INPUT type="submit" style="height:40px;width:90px" value="OK">';
    // Start and End of the event
    pop_content += '<INPUT TYPE="HIDDEN" ID="start" NAME="start" value="'+start+'"><INPUT type="HIDDEN" ID="end" NAME="end" value="'+end+'"></form>';

    /****** Some CSS effect *****************/
    $('#'+ID).fadeIn().css({'width': 500})
        .empty()
        .prepend('<a href="#" class="close"><img src="images/close.png" border="0" class="btn_close" title="Fermer" alt="Fermer" /></a>')
        .append(pop_content);   
    // Some CSS Adjust for centering the box
    var popMargTop = ($('#' + ID).height() + 80) / 2;
    var popMargLeft = ($('#' + ID).width() + 80) / 2;
    $('#' + ID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });
    //Effet fade-in du fond opaque
    $('body').append('<div id="fade"></div>'); //Ajout du fond opaque noir
    //Apparition du fond - .css({'filter' : 'alpha(opacity=80)'}) pour corriger les bogues de IE
    $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
    //Fade in the Popup and add close button
    }
    /********** end of CSS effects *************/

    });
    </script>

<div id="popup" class="popup_block"></div>

.

2/ I get the data and push it to a new page in AJAX

so that the page does not reload...

<script type='text/javascript'>

$(function() {
/*********** We get the form data ****************/ 
$('#popup').submit(function(event) {
    event.preventDefault(); // on stop le submit
    var title = $('#title').val();
    var start = $('#start').val();
    var end = $('#end').val();
    var where_event = $('#where_event').val();
    var content_event = $('#content_event').val();

    // because we want immediate reaction of FullCalendar, we render the created event on the FullCalendar, even if it's only temporarily
    if (title) {
        $('#calendar').fullCalendar('renderEvent',
            {
            title: title,
            start: start,
            end: end
            },
            true // make the event "stick"
        );
    // Now we push it to Google also :
    add_event_gcal(title,start,end,where_event,content_event);  
    }

    // Wether we had the form fulfilled or not, we clean FullCalendar and close the popup   
    $('#calendar').fullCalendar('unselect');
    $('#fade , .popup_block').fadeOut(function() {
        $('#fade, a.close').hide("normal");    
    });
});


/****** NOW WE ASK THE EVENT TO BE PUSHED TO GOOGLE **************/
function add_event_gcal(title,start,end,where_event,content_event) { 
    // I will create the eventInsert script in a new page, and I name it here :
    var url = "calendrier_add.php";
    var data = {'titre_event' :title, 'start' : start, 'end' :end, 'where_event' : where_event, 'content_event' : content_event};

    // I want to check in the page the result of what happened
    $('#gcal_loader').load(url,data,function(responseTxt,statusTxt,xhr){
            if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText);
    });
}   

});

.

AT LAST, HERE THE CODE TO PUSH THE EVENT INTO GOOGLE CAL

This PHP code is to be written in the file calendrier_add.php : (of course, first you had to download the API here : https://github.com/google/google-api-php-client : BEWARE : the autoload.php is in src/Google, the one in root is rooten...)

<?php

// variables can only be got with $_REQUEST ?
$titre_event = $_REQUEST['titre_event'];
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$allday = $_REQUEST['allday'];
$where_event = $_REQUEST['where_event'];
$content_event = $_REQUEST['content_event'];

/********************************************
        GOOGLE API CONNECTION
********************************************/

    /************************************************
      Make an API request authenticated with a service account.
     ************************************************/
    require_once 'fullcalendar/google-api-php-client-master/src/Google/autoload.php'; // or wherever autoload.php is located

    /************************************************
      The name is the email address value provided  as part of the service account (not your  address!)
      cf. : https://console.developers.google.com/project/<your account>
     ************************************************/
    $client_id = '12345467-123azer123aze123aze.apps.googleusercontent.com'; // YOUR Client ID
    $service_account_name = '12345467-123azer123aze123aze@developer.gserviceaccount.com'; // Email Address in the console account

    $key_file_location = 'fullcalendar/google-api-php-client-master/API_Project-35c93db58757.p12'; // key.p12 to create in the Google API console

    if (strpos($client_id, "googleusercontent") == false || !strlen($service_account_name) || !strlen($key_file_location)) {
        echo "no credentials were set.";
        exit;
    }

    /** We create service access ***/
    $client = new Google_Client();  

    /************************************************
    If we have an access token, we can carry on.  (Otherwise, we'll get one with the help of an  assertion credential.)
    Here we have to list the scopes manually. We also supply  the service account
     ************************************************/
    if (isset($_SESSION['service_token'])) {
            $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials(
        $service_account_name,
    array('https://www.googleapis.com/auth/calendar'), // ou calendar_readonly
    $key
);

    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();

/********************************************
        END OF GOOGLE API CONNECTION
********************************************/

/*********** AT LAAAAST, WE PUSH THE EVENT IN GOOGLE CALENDAR ***************/
// Get the API client and construct the service object.
$service = new Google_Service_Calendar($client);

// We get the calendar
$calendarId = 'Google_login@gmail.com'; // or whatever calendar you like where you have editable rights


    /************* INSERT ****************/
$event = new Google_Service_Calendar_Event(array(
    'summary' => $titre_event, 
    'location' => $where_event,
    'description' => $content_event,
    'start' => array(
        'dateTime' => $start, //'2015-06-08T15:00:00Z'
        'timeZone' => 'Europe/Paris',
    ),
    'end' => array(
        'dateTime' => $end,
        'timeZone' => 'Europe/Paris',
    ),
    /* in case you need that :
    'attendees' => array(
        array('email' => 'lpage@example.com'),
        array('email' => 'sbrin@example.com'),
    ),*/
    'reminders' => array(
        'useDefault' => FALSE,
        'overrides' => array(
            array('method' => 'email', 'minutes' => 20)
    ),
        ),
));

$event = $service->events->insert($calendarId, $event);
printf('Event created: %s', $event->htmlLink);

?>

I spent some time, but it works fine for me. In my script, I can write on multiple calendars just by changing calendarID. It should be added to Fullcalendar now, but I have no GIT account, Node or NPM.

ONE LAST THING

It may be strange, but the best way for me to make this work was also to ADD my API Console email account to the shared users of the calendar with full power!(can't post image until I got 10 reputations...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...