How can I have my server add events to a google calendar using the client library for PHP?

女生的网名这么多〃 提交于 2019-12-08 05:40:33

问题


I have very little experience working with the google api and I'm finding it difficult to find relevant information on certain subjects.

What I'm trying to do is create a calendar that requires no log in information from the user. I want my server to add events to the calendar based off of information in a database.

I have gone into my google calendars, created a new one, and worked up some code to add events to the calendar. Then I use the iframe code that google provides to embed the calendar into my site.

The problem I'm running into is that the server wants the user to be logged in as me to add events to the calendar. Since the server is the one adding the events, I'm not really sure how to work around this. I know I need to make/use a service account so my server can "delegate domain-wide authority", but I'm not sure how to do this using the client library for PHP. No examples are provided by google. I had to download a p12 file that my server needs to make these api calls, but I'm not sure how to point to the file using the client library. Is it possible to use the php client library to hook into a service account to make these api calls? If so, how?

Any help is greatly appreciated.


回答1:


I had the same problem and found the solution (in a round about way) here: Inserting Google Calendar Entries with Service Account

First thing is to set up your Google calendar correctly (see above mentioned post which describes it very well), then download the API code for the Calendar from here https://github.com/google/google-api-php-client It's the Download ZIP link on the right of that page.

Then here is some sample code which works for me (private keys replaced with xxxx where appropriate, but otherwise it's exactly what I'm using).

I'm now trying to find out how to read & clear a Google Calendar, which is proving even more challenging!

<?php
//
// built from example at:
// https://stackoverflow.com/questions/26064095/inserting-google-calendar-entries-with-service-account
//
$startdate = new DateTime('2015-01-29 10:00', new DateTimeZone('Europe/London'));
$startdate = $startdate->format('c');
$enddate = new DateTime('2015-01-29 10:00', new DateTimeZone('Europe/London'));
$enddate = $enddate->format('c');
//
// call function to add one event to the calendar (xxxxxxxxxxx@googlemail.com = the calendar owner)
//
calendarize('Test Appointment','Test appt description',$startdate,$enddate,'xxxxxxxxxxx@googlemail.com');

//-----------------------------------------------//
// funtion to add an event to my Google calendar //
//-----------------------------------------------//
function calendarize ($title, $desc, $start_ev_datetime, $end_ev_datetime, $cal_id) {
    session_start();
    require_once '../google-api-php-client-master/autoload.php';
    //Google credentials
    $client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
    $service_account_name = 'xxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com';
    $key_file_location = '../google-api-php-client-master/API Project-xxxxxxxxxx.p12';
    if (!strlen($service_account_name) || !strlen($key_file_location))
        echo missingServiceAccountDetailsWarning();
    $client = new Google_Client();
    $client->setApplicationName("Whatever the name of your app is");
    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'),
        $key
    );
    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
        try {
          $client->getAuth()->refreshTokenWithAssertion($cred);
        } catch (Exception $e) {
          var_dump($e->getMessage());
        }
    }
    $_SESSION['service_token'] = $client->getAccessToken();
    $calendarService = new Google_Service_Calendar($client);
    $calendarList = $calendarService->calendarList;
    //Set the Event data
    $event = new Google_Service_Calendar_Event();
    $event->setSummary($title);
    $event->setDescription($desc);
    $start = new Google_Service_Calendar_EventDateTime();
    $start->setDateTime($start_ev_datetime);
    $start->setTimeZone('Europe/London');
    $event->setStart($start);
    $end = new Google_Service_Calendar_EventDateTime();
    $end->setDateTime($end_ev_datetime);
    $end->setTimeZone('Europe/London');
    $event->setEnd($end);
    try {
      $createdEvent = $calendarService->events->insert($cal_id, $event);
    } catch (Exception $e) {
      var_dump($e->getMessage());
    }
    echo 'Event Successfully Added with ID: '.$createdEvent->getId();
}
?>



回答2:


Using OAuth2 to login and give your server rights to access your calendar account is really simple and well documented (with the google api php client). If you request offline access and store the refresh token, you can log in "as you" server-side at any time.

See Google Accounts Authentication and Authorization: Offline access



来源:https://stackoverflow.com/questions/27231460/how-can-i-have-my-server-add-events-to-a-google-calendar-using-the-client-librar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!