Are you trying to connect to Google Calendar API with PHP using Oauth2? Would you like to show users their Google Calendar using PHP? Do you need to access a users Google Calendar? In this tutorial I will show you how to use the Google PHP client library to access the Google Calendar API.
[wp_ad_camp_3]
Register your App
Before you can access any of the Google Apis you must first register your application with Google. I have a short tutorial that walks you through creating a new application Google Developers console. There is one thing you need to add when working with a web application the Redirect URIs needs to be the location of the php file. This setting is found in APIs & auth -> Credentials menu.
Make sure that you enable the Google Calendar API under APIS, and set a Product name and Email address.
PHP client library
The newest version of the Google PHP client library can be found on Github. google-api-php-client this client lib is updated regularly whenever anything changes. You will need to copy the entire src/Google directory to the directory of your application. I don’t recommend only taking the files that you need unless you really know what you are doing.
Oauth2
There are 3 steps to Oauth2 this is why it is called 3 legged authentication. In the first step you ask the user to give you access, second step the user gives you access, third and final step you exchange the access given to you by the user for the access to the data.
[wp_ad_camp_3]
The Code
setApplicationName("Client_Library_Examples"); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setAccessType('offline'); // Gets us our refreshtoken $client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly')); //For loging out. if (isset($_GET['logout'])) { unset($_SESSION['token']); } // Step 2: The user accepted your access now you need to exchange it. if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } // Step 1: The user has not authenticated we give them a link to login if (!isset($_SESSION['token'])) { $authUrl = $client->createAuthUrl(); print "Connect Me!"; } // Step 3: We have access we can now create our service if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); print "LogOut
"; $service = new Google_Service_Calendar($client); $calendarList = $service->calendarList->listCalendarList();; while(true) { foreach ($calendarList->getItems() as $calendarListEntry) { echo $calendarListEntry->getSummary()."
\n"; // get events $events = $service->events->listEvents($calendarListEntry->id); foreach ($events->getItems() as $event) { echo "-----".$event->getSummary()."
"; } } $pageToken = $calendarList->getNextPageToken(); if ($pageToken) { $optParams = array('pageToken' => $pageToken); $calendarList = $service->calendarList->listCalendarList($optParams); } else { break; } } } ?>
Conclusion
This is a very simple example of how to connect to the Google Calendar API using Oauth2. This example can be edited to use the other APIs by changing the service that is created.
Working Version of this script can be found here: Google Calendar OAuth2 PHP
You might want to consider simplifying the code by replacing the require_once statements by just one:
require_once ‘inc/google-api-php-client/autoload.php’;
and you can replace the code that sets the developer key, client id and such with just one line that includes the ‘client_secrets.json’ file that you can download from your Google Developers console:
$client->setAuthConfigFile(‘client_secrets.json’);
Finally you could expand the code a bit and go into the ‘refresh token’ and how one should use it. (That’s the part I’m at right now, so no example from me yet. 🙂
Good points all of them, I feel version 2 coming. I have considered releasing the code as part of a GitHub project then others can help improve the samples.
can you make this tutorial using chsarp dot net?
Hi Linda, i hope you can help me. Im trying to set up the Push notifications for Google Calendar, im working on https://developers.google.com/google-apps/calendar/v3/reference/events/watch and https://developers.google.com/oauthplayground, but with anyone i get a Unauthorized WebHook callback channel, i dont know what to do.
I have an APIkey, autorized using OAuth 2.0, add my own domain and autorized google API on developers.google.com.
I havent tried this yet but i found this it may help Google push notifications – Unauthorized WebHook callback channel
Hi linda.
thank you for your sample code,but I have a problem,I hope you can help me.
(403) There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.
I changed my api key and other keys(secret and ..)but It did not fix.
try this:
Make sure that you aren’t sending your requests to fast, it sounds like you are hitting the flood protection slow it down.
Where can i find the file: ‘CalendarHelper.php’ ?
I think that was an error in the sample. I have removed it.
Hi Linda, may i introduce myself. My name is Galuh.
thankyou for the sample code, but i have a problem and i hope you can help me solve the problem 🙂 .
Here is the problem Linda, when the Google request for permission i can’t click the accept button. can you help me solve the problem?
i have captured my video for you 🙂 pls follow this link https://vimeo.com/122394164
Double check that account has calendars, or try one of your other accounts. I have never seen that before.
Hi,
I used your tutorial and it works well, but after redirection to my specified redirect URI, how can I access the calendar data? Do you have an example for the redirection-page aswell or can you recommend any other tutorials for this? Would be very grateful for any help!
Thanks
Nevermind, I didn’t understand that the redirection page had to be the same as the php-file. Got it working now, thanks!
Hi
Thank you!! for your wonderful tutorial..The code is working but I got the calendar as some paragraph details…how can I view that result as calendar?
Please help me…
what do you mean by result as calendar? Do you mean graphically? your going to have to make a table or something I guess. The API just gets the data for you. You have to make it look nice yourself.
Thank You…!
Linda, great tutorial. Any chance of putting something together on the gmail api? Maybe using zend?
I could probably add the GMail api to my list but zend i cant help you with never used it sorry.
Hi Linda,
Thanks for the tutorial. I use your code to let my users add events from their Google Calendar to their calendar in my application. So basically I read the events from Google Cal with the help from your code, then I add it to my own database instead of displaying them like you do in the example above. It works pretty well but some of my users has contacted me saying that sometimes the events are added multiple times, everything from like 4 to 20 times. Could it have something to do with the while loop – that if the loading takes a while it starts over again? Or do you think it’s something else? Do you have a possible fix for this?
Thanks,
Jakob
I suppose it could, I have only tested it on my own data really. I might have to think of a better way of doing this, let me know if you come up with anything.
Thanks so much for this tutorial. I have been trying to connect to google for 2 weeks now (using the json file, and finally gave up on it), and this is the only resource I was able to use to successfully connect to google calendar and retrieve events. I wrote a php program to do all this using the xml feeds, which google is removing, so I have to switch to gcal api, so pardon me for not having a clue what I’m doing. I wonder why there is nothing on the web for how-to’s (at least that I can find)…
Anyway, I’m wondering if you could tell me if there is a way to add a form to this file to get user input? Right now I’m hard-coding date ranges… I tried creating a form in your file and submitted it to itself, but it just refreshed the page and asked me to connect again. I guess I could create a separate file with my form which then calls your file, that might work, but I want to generate the data to use for the form (e.g. a dropdown to select from list of calendars generated).
I also wonder why when you refresh it asks to connect again, I thought I was connected. I don’t know much about sessions, but you don’t lose cookies when you refresh, so why does it ask to connect again? Sorry again for not really understanding this aspect at all.
Thanks a bunch, and thanks again for the great instructions 🙂 Even if I can’t use a form, from this how-to, I can still hard-code to get everything I need, albeit in a round-about, and slightly more time consuming way. Brandy
Hello Linda! I used your code and got an error after i click allow permission. This is an error ”
Fatal error: Uncaught exception ‘GuzzleHttp\Ring\Exception\RingException’ with message ‘cURL error 60: SSL certificate problem: unable to get local issuer certificate’ in E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php:127 Stack trace: #0 E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\CurlFactory.php(91): GuzzleHttp\Ring\Client\CurlFactory::createErrorResponse(Array, Array, Array) #1 E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\CurlHandler.php(96): GuzzleHttp\Ring\Client\CurlFactory::createResponse(Array, Array, Array, Array, Resource id #70) #2 E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\CurlHandler.php(68): GuzzleHttp\Ring\Client\CurlHandler->_invokeAsArray(Array) #3 E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\Middleware.php(54): GuzzleHttp\Ring\Client\CurlHandler->__invoke(Array) #4 E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\ringphp\src\Client\Middleware.php(30): GuzzleHttp\Ring\Client\Middleware::GuzzleHttp\Ring\Cli in E:\xampp\htdocs\gcalendar\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 51″
Sorry i have never used guzzle you might want to try Googleing the error message “cURL error 60: SSL certificate problem”.
I’m developing with mamp pro for windows and I’m getting this same error. Did you figure it out?
Hello Linda!
Could you give me a better example of the Redirect URI? I’m getting the error: Redirect URI must be absolute
Redirect uri is basically the page that you are handling the response in. http:\\yourwebsite.com\oauth.php
Thank you very much, I have weeks trying to enter the Google APIs Clendar, Very simple and detailed tutorial. Thank you.
Dear Linda,
Thanks for your tutorial!
Unfortunately I am getting an error after clicking the “accept” button.
Fatal error: Class ‘Google_Service’ not found in /home/user/domains/domain.nl/private_html/dev/vendor/google/apiclient-services/src/Google/Service/Oauth2.php on line 32
Google research did not help so far.
The results tell me to set the autoload path correctly, this is however already set correctly. Other solutions are a new PHP version (already running PHP 5.6), use set_include_path or change composer.json. All with no result.
Your script has been placed in the vendor directory.
Your help is appreciated, thanks!
Hi Linda! I’m getting the error Parse error: syntax error, unexpected ‘[‘ in /vendor/guzzlehttp/psr7/src/functions.php on line 78 i dont use composer. How can i fix this ?
Sorry its been a while since i have worked with PHP you might want to try asking on Stackoverflow.
Hello Linda!! , your code worked perfectly.
Now I have another question … how can I do to create events using this same lib/API
try events.insert There is some sample code on that page for PHP should work fine.