Google Calendar OAuth2 – PHP 32


Google Calendar

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.

phpOauthredirect

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 "";
    }    


    // 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


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

32 thoughts on “Google Calendar OAuth2 – PHP

  • Bas

    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. 🙂

  • Amin

    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.

    • Linda Lawton

      try this:

      • 1. Make sure that you made a Client ID for web application and are not trying to use Public API access
      • 2. APIs & Auths -> APis -> click the Calendar API link -> go to the Quotas tab -> change per user limit to 10 if it will let you it may not without enabling billing

      Make sure that you aren’t sending your requests to fast, it sounds like you are hitting the flood protection slow it down.

  • Galuh

    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

  • Jakob Hedlund

    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

    • Jakob Hedlund

      Nevermind, I didn’t understand that the redirection page had to be the same as the php-file. Got it working now, thanks!

  • Bagya

    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…

  • Jakob

    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

  • Bob

    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

  • Sovan Krusna

    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″

  • Renan Serrão Nogueira

    Hello Linda!
    Could you give me a better example of the Redirect URI? I’m getting the error: Redirect URI must be absolute

  • Tatys

    Thank you very much, I have weeks trying to enter the Google APIs Clendar, Very simple and detailed tutorial. Thank you.

  • Steve

    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!

  • Ramiro

    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 ?