We write about technical solutions for the roadblocks we face in everyday work and more on trends in technology. This will help some of you to tackle issues quickly and get some useful tips.

Google Calendar is being used by millions of people to track their events. The Google Calendar API is used to integrate your application with Google Calendar to find and view calendar events.

Complete the steps described in the rest of this page to integrate Google Calendar API in a Laravel application.

Generate API connection

Go to https://console.developers.google.com/ Create a project From the dashboard go to Credentials section Open OAuth consent screen data and fill in the required data Open Credentials tab and Select OAuth Client ID; Select application type as Web Application; Add site URL and redirect URL Click Create and the Client Keys will be now created Download the Client Secret JSON from the details rename the downloaded file to client_secret.json.

Enable API Access To enable API access to the resources to go to: ‘Library’ in the left menu Search and enable Admin SDK API and Google Calendar API

Install the Google Client Library using composer by

composer require google/apiclient:^2.0 command

Put the client_secret.json file to the storage folder. Connect to the Google Calendar API using the laravel application

1. Create a route for the connect operation in routes/web.php

Route::get(‘/google-calendar/connect’, ‘GoogleCalendarController@connect’);

2. Create GoogleCalendarController.php and create the connect function

public function connect() { $client = GoogleCalendar::getClient(); $authUrl = $client->createAuthUrl(); return redirect($authUrl); }

The connect function redirects to request authentication from the user.

Copy the authorization code from this link.

3. Post the authorization code to the store function.

Add route to post the code

Route::post(‘/google-calendar/connect’, ‘GoogleCalendarController@store’);

Add store function in GoogleCalendarController

public function store() { $client = GoogleCalendar::getClient(); $authCode = request('code'); // Load previously authorized credentials from a file. $credentialsPath = storage_path('keys/client_secret_generated.json'); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); // Store the credentials to disk. if (!file_exists(dirname($credentialsPath))) { mkdir(dirname($credentialsPath), 0700, true); } file_put_contents($credentialsPath, json_encode($accessToken)); return redirect('/google-calendar')->with('message', 'Credentials saved'); }

The store function generates and stores the accessTokens to the client_secret_generated.json file.

6) Fetch the resources from the google calendar

Add route to get the resource

Route::get(get-resource, ‘GoogleCalendarController@getResources’);

Add getResources function in GoogleCalendarController

public function getResources() { // Get the authorized client object and fetch the resources. $client = GoogleCalendar::oauth(); return GoogleCalendar::getResources($client); }

7) Create GoogleCalendar.php in App\Services Folder.

The main functionalities of the Google Calendar API are defined in this class.

Create getClient function. public function getClient() { $client = new Google_Client(); $client->setApplicationName(config('app.name')); $client->setScopes(Google_Service_Directory::CALENDAR_READONLY); $client->setAuthConfig(storage_path('keys/client_secret.json')); $client->setAccessType('offline'); return $client; } /** * Returns an authorized API client. * @return Google_Client the authorized client object */ public function oauth() { $client = $this->getClient(); // Load previously authorized credentials from a file. $credentialsPath = storage_path('keys/client_secret_generated.json'); if (!file_exists($credentialsPath)) { return false; } $accessToken = json_decode(file_get_contents($credentialsPath), true); $client->setAccessToken($accessToken); // Refresh the token if it's expired. if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents($credentialsPath, json_encode($client->getAccessToken())); } return $client; }

This function loads previously authorized token from a file, if it exists. The file client_secret_generated.json stores the user’s access and refresh tokens, and is created automatically when the authorization flow completes for the first time.

Create getResource function function getResource($client) { $service = new Google_Service_Calendar($client); // On the user's calenda print the next 10 events . $calendarId = 'primary'; $optParams = array( 'maxResults' => 10, 'orderBy' => 'startTime', 'singleEvents' => true, 'timeMin' => date('c'), ); $results = $service->events->listEvents($calendarId, $optParams); $events = $results->getItems(); if (empty($events)) { print "No upcoming events found.

"; } else { print "Upcoming events:

"; foreach ($events as $event) { $start = $event->start->dateTime; if (empty($start)) { $start = $event->start->date; } printf("%s (%s)

", $event->getSummary(), $start); } } }