Google Calendar with php using the google calendar api 3

  Google, PHP

Writing events to a Calendar with PHP using the Google Calendar API 3 and a Service Account (no user)

Writing events to a Calendar with PHP using the Google Calendar API 3 and a Service Account (no user).

1. Download Google API’s PHP Client

First download the Google API’s PHP Client code by following these instructions:https://code.google.com/p/google-api-php-client/. Extract the contents of the archive and copy the resulting directory into your apps source directory (To be able to follow my example below rename the directory to ‘google-api-php-client’ and ensure that it contains a ‘src’ sub directory).

2. Enable the Google Calendar API v3 in the API’s Console

Go to https://cloud.google.com/console , select the project you are working on (or create a new one) click on ‘APIs and Auth’ and select ‘APIs’. Look down the list for ‘Calendar API’ and click on the button/switch on the right so that it turns green and says ‘ON’.

3. Get Credentials

In the cloud console (as above), click on ‘Registered apps’, and then ‘REGISTER APP’. Enter a name for your app and ensure that ‘Web Application’ is selected next to Platform.


Certificate Download

Expand the ‘Certificate’ section and click on the ‘Generate Certificate’ button. After a few seconds a ‘Certificate Generated’ dialog will be displayed. Click on the ‘Download private key’ button, this will trigger your browser to download a .p12 file named something like ‘dceffe6e95344eb64c88dd982bc8f1c01ed0aa6b-privatekey.p12’. Copy this file to a directory named ‘certificates’ in the root of your apps source directory.

Service Account Email

Click on the ‘View public key’ button (which will dismiss the dialog). An email address will have also been populated under ‘EMAIL ADDRESS’ in the console which will look something like:

65436475876998-siub68asyas87d87s@developer.gserviceaccount.com
(Make a note of this)

Client ID

Expand the ‘OAuth 2.0 Client ID’ section and copy the ‘CLIENT ID’ which will look something like:

65436475876998-siub68asyas87d87s.apps.googleusercontent.com
(Make a note of this)

5. app.yaml (or module_name.yaml) Modifications

UPDATE – 20/05/14 – Do not include this step, it is not required.

To make the certificate file accessible to your code you will need to add it as a static resource, as you application will be accessing it rather than users you need to ensure you add the ‘application_readable’ attribute (so that your app can access it) and the login: admin attribute (so that it is not publicly accessible).

- url: /certificates/*
static_dir: certificates/*
login: admin
application_readable: true

6. Calendar ID

Now you need to go and get the calendar’s ID, to do this go the calendar in Google Calendars and open its settings. On the ‘Calendar Details’ tab next to ‘Calendar Address’  there is a ‘Calendar ID displayed, which will look something like: sd7h90sdja97sdg9ahd0sa8bd@group.calendar.google.com

7. Calendar Permissions

Now you need to give your service account permissions on the calendar. On the ‘Share this Calendar’ tab, under ‘Share with specific people’. Enter the service account email address that you got in step 3 (in this example it is 65436475876998-siub68asyas87d87s@developer.gserviceaccount.com) and choose ‘Make changes to events’, then click Save (If you the calendar belongs to a user on a Google Apps domain you will need to ensure that permissions on the domain are setup correctly to allow external access).

8. Example Code

Replace the details in the code example below with the details that you have gathered in the previous steps above.

  • Lines 2 & 3 – Paths to the google-api-php-client you created earlier
  • Line 8 – Client ID
  • Line 11 – Service account ID
  • Line 15 – Service account email
  • Line 33 – Certificate file path
 // ...
    require_once "../google-api-php-client/src/Google_Client.php";
    require_once "../google-api-php-client/src/contrib/Google_CalendarService.php";
    //
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setApplicationName("your-app-name");
    $client->setClientId("asdohas8djasjd89absdo9p.apps.googleusercontent.com");
    $client->setAssertionCredentials(
        new Google_AssertionCredentials(
            "d98hg78as9dj-0askd9ajsd08a0sdjspdj9@developer.gserviceaccount.com",
            array(
                "https://www.googleapis.com/auth/calendar"
            ),
            file_get_contents("certificates/dceffe6e95344eb64c88dd982bc8f1c01ed0aa6b-privatekey.p12")
        )
    );
    //
    $service = new Google_CalendarService($client);
    //
    $event = new Google_Event();
    $event->setSummary('Event 1');
    $event->setLocation('Somewhere');
    $start = new Google_EventDateTime();
    $start->setDateTime('2013-10-22T19:00:00.000+01:00');
    $start->setTimeZone('Europe/London');
    $event->setStart($start);
    $end = new Google_EventDateTime();
    $end->setDateTime('2013-10-22T19:25:00.000+01:00');
    $end->setTimeZone('Europe/London');
    $event->setEnd($end);
    //
    $calendar_id = "sd7h90sdja97sdg9ahd0sa8bd@group.calendar.google.com";
    //
    $new_event = null;
    //
    try {
        $new_event = $service->events->insert($calendar_id, $event);
        //
        $new_event_id= $new_event->getId();
    } catch (Google_ServiceException $e) {
        syslog(LOG_ERR, $e->getMessage());
    }
    //
    $event = $service->events->get($calendar_id, $new_event->getId());
    //
    if ($event != null) {
        echo "Inserted:";
        echo "EventID=".$event->getId();
        echo "Summary=".$event->getSummary();
        echo "Status=".$event->getStatus();
    }
    //...

This should produce output that looks like:

NewEventID=n5m27gad3b0mvbc8gvbe79fb7g
Inserted:
EventID=n5m27gad3b0mvbc8gvbe79fb7g
Summary=Event 1
Status=confirmed

See https://developers.google.com/google-apps/calendar/ for more information on the Calendar API v3.

LEAVE A COMMENT