如何使用完整日历将活动添加到 Google 日历



我已经搜索了FullCalendar文档并用谷歌搜索了一下,但我无法找到如何使用FullCalendar将事件添加到Google日历。我尝试过将js Google API用于Google日历,但我对js很陌生,我还没有解决。所以我的问题是:我有一个网站,我在其中使用FullCalendar来管理Google日历,但我无法向其添加事件。有没有人可以帮助我,也许有一个完整的工作示例?非常感谢您的 precoius 帮助!

我遇到了同样的问题。我阅读了许多文档,最后我得到了一个有效的代码。我在这里分享给你:

这是如何从完整日历在Google Cal中实际添加事件(我非常喜欢):

首先:从完整日历获取自定义表单

 $('#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
 });

因此,当我选择时间范围时,我会制作一个模态框(以便我可以自己管理输入)。我在这里使用 start.format(),以便 DateTime 已经采用 GoogleFormat。

第二:创建表单

1/创建表单

(在模式窗口中)。它将包含谷歌日历的所有信息。

<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/我获取数据并将其推送到 AJAX 中的新页面

这样页面就不会重新加载...

<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);
    });
}   
});

.

最后,这里是将事件推送到谷歌CAL的代码

这个PHP代码要写在文件中calendrier_add.php:(当然,首先你必须在这里下载API:https://github.com/google/google-api-php-client:当心:autoload.php在src/Google中,root中的那个是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);
?>

我花了一些时间,但它对我来说效果很好。在我的脚本中,我可以通过更改日历 ID 在多个日历上写入。它现在应该添加到完整日历中,但我没有 GIT 帐户、节点或 NPM。

最后一件事

这可能很奇怪,但对我来说,完成这项工作的最佳方法也是将我的 API 控制台电子邮件帐户以全功率添加到日历的共享用户!(在我获得 10 个声誉之前无法发布图像...

我正在尝试使用"renderEvent"事件,新事件是在日历中创建的,但它不是固定的(即下次刷新页面时,事件不存在)。这是我的代码:

<HTML>
    <HEAD>
        <link href="fullcalendar.css" rel="stylesheet" type="text/css"/>
        <script src="lib/jquery-ui.custom.min.js" type="text/javascript"></script>
        <script src="lib/jquery.min.js" type="text/javascript"></script>
        <script src="lib/moment.min.js" type="text/javascript"></script>
        <script src="fullcalendar.js" type="text/javascript"></script>
        <script src='lang/it.js' type='text/javascript'></script>
        <script src="gcal.js" type="text/javascript"></script>
        <script type='text/javascript'>
            $(document).ready
            (
                function()
                {
                    $('#calendar').fullCalendar
                    (
                        {
                            googleCalendarApiKey: '<MY GOOGLE CALENDAR API KEY>',
                            header: { 
                                        left: 'title',
                                        center: '',     
                                        right: 'month,agendaWeek,agendaDay,today,prev,next'
                                    },  
                            events: {
                                        googleCalendarId: '<MY GOOGLE CALENDAR ID>',
                                        className: 'gcal-event' 
                                    },
                            selectable:     true,
                            selectHelper:   true,
                            editable:       true,
                            dayClick: function()
                            {
                                var eventTitle = prompt('Event Title:');
                                if (title)
                                {
                                    var newEvent =  {
                                                        title:  eventTitle,
                                                        start:  '2015-01-01',
                                                    };
                                    $('#calendar').fullCalendar
                                    (
                                        'renderEvent',
                                        newEvent,
                                        true
                                    );
                                }
                                $('#calendar').fullCalendar('unselect');
                            }
                        }
                    );
                }
            );
        </script>
        <TITLE>Calendario</TITLE>
    </HEAD>
    <BODY>
        <div id='calendar'></div>
    </BODY>
<HTML>

添加事件记录得相当好,请阅读以下内容:http://fullcalendar.io/docs/google_calendar/

我假设您无法添加事件,因为它们的 API 更改:

2014年11月17日,谷歌关闭了FullCalendar所依赖的日历API的V1和V2。请升级到最新版本的 FullCalendar 或至少用此文件替换 gcal.js(将工作到 FullCalendar v2.0.0)。此外,现在需要您自己的谷歌日历API密钥。

您使用的是最新版本吗?

相关内容

  • 没有找到相关文章