fullcalendar - 如何使用 FullCalendar 将事件添加到 Google 日历?

标签 fullcalendar google-calendar-api

我正在尝试在我的 FullCalendar 中将事件添加到我的谷歌日历,按照下面的例子,
How to add events to Google Calendar using FullCalendar

但对我不起作用,如果有人知道该怎么做,请帮忙。

这是我的代码

 <!DOCTYPE html>
<html>
<head>
   <meta charset='utf-8'/>
   <link href='../fullcalendar.css' rel='stylesheet'/>
   <link href='../fullcalendar.print.css' rel='stylesheet' media='print'/>
   <script src='../lib/moment.min.js'></script>
   <script src='../lib/jquery.min.js'></script>
   <script src='../fullcalendar.min.js'></script>
   <script src='../gcal.js'></script>
   <script>

      $(document).ready(function () {

         $('#calendar').fullCalendar({

            selectable: true,
            selectHelper: true,
            var eventData, title;
            select: function(start, end) {
                title = prompt('Event Title:');
               },
               editable: true
            }


               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);  
                }
             }
               $('#calendar').fullCalendar('unselect');

         });

      });

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

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

   </script>

   <style>

      body {
         margin: 40px 10px;
         padding: 0;
         font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
         font-size: 14px;
      }

      #loading {
         display: none;
         position: absolute;
         top: 10px;
         right: 10px;
      }

      #calendar {
         max-width: 900px;
         margin: 0 auto;
      }

   </style>
</head>
<body>

<div id='loading'>loading...</div>

<div id='calendar'></div>

</body>
</html>

这是文件php
 <?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 realpath(dirname(__FILE__) . '/../google/autoload.php');// or wherever autoload.php is located
    $path = realpath(dirname(__FILE__) . '/../google/autoload.php');

    /************************************************
      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 = '1020443454327******'; // YOUR Client ID
    $service_account_name ='102044345*****'; // Email Address in the console account

    $key_file_location = realpath(dirname(__FILE__) . '/../google/Mi proyecto-edc74d9206de.p12'); // key.p12 to create in the Google API console
    echo "key".$key_file_location;

    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 = 'qv8rv593gn5g8pumu0bid6bco0@group.calendar.google.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);

?>

最佳答案

我找到了答案

https://developers.google.com/google-apps/calendar/v3/reference/events/insert#examples

1)

//Global variables to access the calendar
     clientId = 'Your cliendID',
     scopes = 'https://www.googleapis.com/auth/calendar',
     calendarId = 'Your google calendar id',
     eventsList = [];


//Autorice the user
    checkAuth();

      //authorization in google
      function checkAuth() {
         gapi.auth.authorize(
            {
               'client_id': clientId,
               'scope': scopes,
               'immediate': true
            }, handleAuthResult);
      }

      //checks if authorized
      function handleAuthResult(authResult) {

         if (authResult && !authResult.error) {
            loadCalendarApi();
         } else {
            handleAuthClick();
         }
      }

      //request credentials
      function handleAuthClick() {
         gapi.auth.authorize(
            {
               client_id: clientId,
               scope: scopes,
               immediate: false
            }, handleAuthResult);
         return false;
      }

     function loadCalendarApi() {

         gapi.client.load('calendar', 'v3', makeApiCall);

      }`


2)

// Load the API and make an API call.  Display the results on the screen.
      


function makeApiCall() {

         requestList = gapi.client.calendar.events.list({
            'calendarId': calendarId
         });

         console.log('--- eventsList ---');
         console.log(eventsList);
         uiCalendarConfig.calendars['myCalendar'].fullCalendar('removeEventSource', eventsList);
         eventsList = [];

         // Step 6: Execute the API request
         requestList
            .then(function (resp) {

               if (resp.result.error) {

                  reportError('Google Calendar API: ' + data.error.message, data.error.errors);

               } else if (resp.result.items) {

                  resp.result.items.forEach(function (entry, index) {
                     eventsList.push({
                        id: entry.id,
                        title: entry.summary,
                        start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
                        end: entry.end.dateTime || entry.end.date, // same
                        url: url,
                        location: entry.location,
                        description: entry.description
                     });
                  });

               }

               if (eventsList.length > 0) {
                  uiCalendarConfig.calendars['myCalendar'].fullCalendar('addEventSource', eventsList, true);
               }

            }, function (reason) {
               console.log('Error: ' + reason.result.error.message);
            });
      }`


3)

//insert into calendar



      function makeRpcRequest(eventData) {

         gapi
            .client
            .load('calendar', 'v3')
            .then(function () {
               request = gapi.client.calendar.events.insert({
                  'calendarId': calendarId,
                  'resource': eventData
               });

               request.then(function (resp) {

                  if (resp.result.error) {
                     reportError('Google Calendar API: ' + data.error.message, data.error.errors);
                  } else {

                     makeApiCall();
                     console.log(resp);
                     var creator = resp.result.creator.email;
                     var calendarEntry = resp.result.htmlLink;

                     console.log('--- Calendar entry successfully created by---');
                     console.log(creator);
                     console.log('--- dd ---');
                     console.log(calendarEntry);
                  }
               }, function (reason) {
                  console.log('Error: ' + reason.result.error.message);

               });
            });
      }`

 

关于fullcalendar - 如何使用 FullCalendar 将事件添加到 Google 日历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32589777/

相关文章:

javascript - Fullcalendar 为每一天添加自定义按钮

javascript - 如何设置 FullCalendar 的样式以更好地利用空间?

javascript - 在 fullcalendar 中如何禁止在我的自定义 View 中选择

php - fullCalendar 事件 post 方法到 MySQL

javascript - NodeJS、Google 日历 API 集成未经过身份验证并返回未定义,无论凭证和 token 是否存在

java - 如何与谷歌日历集成?

php - PHP MySQL 检索某个用户的信息

java - 如何使用 java 将 CSV 日历导入我的 Google 日历

java - 如何计算特定日历上仅今天的事件数?

.net - 使用 Google.Api OAuth 2 时拒绝访问路径 'C:\Windows\system32\config\systemprofile'