Friday 4 March 2016

How to add event in google calendar using Laravel 5.1

Hi Everybody,

Today we will discuss about how to add event in google calendar using Laravel 5.1.

For anyone who would like to use Google API with a service account connection, here is what I have to done in order to make it work :

1- Call the following in command line : composer require google/apiclient

2- In your http://console.developers.google.com Create a new Client ID in Credentials, Select Service account and click on Create Client ID

3- Next, take the *.p12 file and place it somewhere in your laravel directory (in my case in assets).

4- Next, create a new Gooogle calendar (http://calendar.google.com) with any Google account and share it with your Service Account's Email Address created in step 3 and save it.

5- In the config folder, add a file name google.php, place and modify the following content :

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Client ID
    |--------------------------------------------------------------------------
    |
    | The Client ID can be found in the OAuth Credentials under Service Account
    |
    */
    'client_id' => 'something.apps.googleusercontent.com',

    /*
    |--------------------------------------------------------------------------
    | Service account name
    |--------------------------------------------------------------------------
    |
    | The Service account name is the Email Address that can be found in the
    | OAuth Credentials under Service Account
    |
    */
    'service_account_name' => 'something@developer.gserviceaccount.com',

    /*
    |--------------------------------------------------------------------------
    | Key file location
    |--------------------------------------------------------------------------
    |
    | This is the location of the .p12 file from the Laravel root directory
    |
    */
    'key_file_location' => '/resources/assets/filename.p12',
    'app_name'          => 'Application name',
    'client_secret'     => '3rULDQBNHOYAg0ySYpHW',

    'api_key'           => 'AIzaSyBdk8P_lLwpKQkKOamgnw',
];

6- In your application folder, I have added a file named GoogleCalendar.php in App\Services with the following content :

<?php namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

class GoogleCalendar {

    protected $client;

    protected $service;

    function __construct() {
        $client_id = Config::get('google.client_id');
        $service_account_name = Config::get('google.service_account_name');
        $key_file_location = base_path() . Config::get('google.key_file_location');
        $client_secret = Config::get('google.client_secret');
        $key = Config::get('google.api_key');//you can use later

        $this->client = new \Google_Client();
        $this->client->setApplicationName("Application name");
        $this->client->setClientId($client_id);
        $this->client->setClientSecret($client_secret);
        $this->client->setDeveloperKey($key);
        $this->client->setScopes(array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly'));
        /* If we have an access token */
        if (Cache::has('service_token')) {
            $this->client->setAccessToken(Cache::get('service_token'));
        }

        $key = file_get_contents($key_file_location);
        $scopes = array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly');
        $cred = new \Google_Auth_AssertionCredentials(
            $service_account_name,
            $scopes,
            $key
        );

        $this->client->setAssertionCredentials($cred);
        if ($this->client->getAuth()->isAccessTokenExpired()) {
            $this->client->getAuth()->refreshTokenWithAssertion($cred);
        }
        Cache::forever('service_token', $this->client->getAccessToken());
        $this->service = new \Google_Service_Calendar($this->client);
    }

    public function addEvent()
    {
        $service = new \Google_Service_Calendar($this->client);
        $event = new \Google_Service_Calendar_Event();
        $event->setSummary('Appointment');
        $event->setLocation('Somewhere');
        $start = new \Google_Service_Calendar_EventDateTime();
        $start->setDateTime('2016-02-29T13:00:00+05:30');
        $start->setTimeZone('America/Los_Angeles');
        $event->setStart($start);
        $end = new \Google_Service_Calendar_EventDateTime();
        $end->setDateTime('2016-02-29T14:00:00+05:30');
        $start->setTimeZone('America/Los_Angeles');
        $event->setEnd($end);
        $attendee1 = new \Google_Service_Calendar_EventAttendee();
        $attendee1->setEmail('rahul@headerlabs.com');
        // ...
        $attendees = array($attendee1
            //, ...
        );
        $event->attendees = $attendees;
        $createdEvent = $service->events->insert('primary', $event);
        echo $createdEvent->getId();
    }

}

7- Next add the following where you need to use Google Calendar
use App\Services\GoogleCalendar;
[...]
    public function functionName(GoogleCalendar $calendar)
    {
        $event_id = $calendar->addEvent();
    }


Thanks

2 comments: