Integrating Google Calendar API in Laravel

LaravelPHPWeb Development
Integrating Google Calendar API in Laravel

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 Google Cloud
  • Create a project
  • From the dashboard go to the Credentials section
  • Open the OAuth consent screen data and fill in the required data
  • Open the 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 and rename the downloaded file to client_secret.json

Enable API Access

  • To enable API access to the resources 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.12.1 command

  • Put the client_secret.json file in the storage folder.
  • Connect to the Google Calendar API using the Laravel application
  • Create a route for the connect operation in routes/web.php

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

  • 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.
  • Post the authorization code to the store function
  • Add a 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');


$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 access token to the client_secret_generated.json file.

  • Fetch the resources from the Google calendar
     
  • Add a 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);

<strong> }</strong>

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::ADMIN_DIRECTORY_RESOURCE_CALENDAR_READONLY);
$client->setAuthConfig(storage_path('keys/client_secret.json'));
$client->setAccessType('offline');
//$client->setApprovalPrompt('force');
$client->setPrompt('consent');
$redirect_uri = url('/google-calendar/auth-callback');
$client->setRedirectUri($redirect_uri);
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 tokens 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.\n";

} else {

    print "Upcoming events:\n";

    foreach ($events as $event) {

        $start = $event->start->dateTime;

        if (empty($start)) {

            $start = $event->start->date;

        }

        printf("%s (%s)\n", $event->getSummary(), $start);

    }

}

}

If you’re looking to integrate the Google Calendar API into your Laravel project, you may run into some challenges along the way. Fortunately,  2hats Logic Solutions we have experienced Laravel developers who can help you navigate Laravel development obstacles and get your project up and running smoothly.

Whether you’re a seasoned developer or just starting, integrating APIs can be a complex process. There are often many moving parts to keep track of, and even a small mistake can cause major headaches down the line. That’s why it’s always a good idea to seek out the help of experienced developers who have worked with these APIs before. 

Comments are closed.

2hats Logic HelpBot