Google shows in documentation and guides how to use Google API and each part of it, such Google Calendar API. I was confused when I read guide to that API. I want to fetch events from my calendar to my application. The example shows only how to get data from the calendar with authorization. What If my client would want to see fetched data? He can’t authorize it because he doesn’t have my google account. I had to find a proper solution in this situation. After some research I had it.
How to fetch data from Google Calendar without user authorization?
To fetch data from calendar without any authorization form user you must have service account key. You can get it from Google’s Developers Console: https://console.developers.google.com. Please create a project as usually. Click on ‘Credentials’ bookmark.
Here, you can create API key that you need. Click on ‘Create credentials’ button and next on ‘Service account key’.
Now, from ‘Service account’ pick ‘New service account’. Set name of key and role. For first time select Project Owner that gives you full access to all resources. You can change it later. Next, you will see the ID of your service account. Set key type to JSON and click ‘Create’ button. The browser will start download JSON file with credentials. Copy it to the directory with your project that you working on. If you work with PHP use composer to download API Client.
1 2 3 4 5 |
{ "require": { "google/apiclient": "^2.0" } } |
Open Google Calendar and go to settings of calendar you will use in the project. In section ‘Share with specific people’ add the ID of your service account.
Next, create PHP file. You can use this example that prints events from your calendar.
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 |
<?php require_once __DIR__ . '/vendor/autoload.php'; define('APPLICATION_NAME', 'App'); define('CREDENTIALS_PATH', __DIR__ . '/path-to-file'); define('SCOPES', implode(' ', array( Google_Service_Calendar::CALENDAR_READONLY) )); $calendarId = 'calendar-id'; $optParams = array( 'maxResults' => 10, 'orderBy' => 'startTime', 'singleEvents' => TRUE, 'timeMin' => date('c'), ); $client = new Google_Client(); $client->setApplicationName(APPLICATION_NAME); $client->setAuthConfig(CREDENTIALS_PATH); $client->setScopes(SCOPES); $service = new Google_Service_Calendar($client); $events = $service->events->listEvents($calendarId, $optParams); foreach ($events->getItems() as $event) { $start = $event->start->dateTime; if (empty($start)) { $start = $event->start->date; } printf($event->getSummary() . " " . $start . "<br>"); } |
Change application, the path to credentials and calendar id. Calendar ID you can find in calendar setting in the section ‘Integrate calendar’.
Hope you find solutions to your problem as me. Good luck!
Be First to Comment