Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
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
1 2 3 4 5 6 7 8 9 10 11 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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'); } |
- 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
1 2 3 4 5 6 7 8 9 10 11 | 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 AppServices Folder
The main functionalities of the Google Calendar API are defined in this class.
Create getClient function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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.