News Archive
PhpRiot Newsletter
Your Email Address:

More information

Using OAuth2 for Google APIs with PHP

Note: This article was originally published at Planet PHP on 29 March 2012.
Planet PHP

I've been working on something recently where I'm pulling information from lots of places onto a dashboard. Each API has its own little quirks so I'm trying to write up the ones that weren't idiot-proof, mostly so I can refer back to them later when I need to maintain my system!

I've written about Google and OAuth before, but that was OAuth v1.0, and they are introducing OAuth2 for their newer APIs; in this example I was identifying myself in order to use the Google Plus API (which turns out not to do anything you'd expect it to do, but that's a whole separate blog post!).

OAuth 1 vs OAuth 2

OAuth 2 doesn't need an extension or any particular library as it doesn't have the signing component that OAuth 1 had, and OAuth 2 also has fewer round trips. It does require SSL however, because the requests are in the clear.

As for pretty much everything, you first of all need to register for an API key; Google offers an APIs Console which is where you'll find and create all the details you need to use.

Use Identification

For a server-side application like this, we'll use the authorization grant flow of OAuth 2, which involves sending the user over to google to log in and grant access to our application (note there is no request token requirement in OAuth 2). We send them with our API key and a callback URL - google sends them back with a code. Here's my code which forwards the user to request access:

$url = ""; A $params = array("response_type" = "code", "client_id" = "", "redirect_uri" = "https://localhost/oauth2callback.php", "scope" = ""); A $request_to = $url . '?' . http_build_query($params); A header("Location: " . $request_to);

The user will be forwarded back to us at the URL we specified in the redirect_uri field, and when they arrive, they'll have a code parameter on the URL which we need to grab. We then use this code to get the actual access token to use with the service. Here's the code from my application which does this bit:

if(isset($_GET['code'])) { // try to get an access token $code = $_GET['code'

Truncated by Planet PHP, read more at the original (another 4361 bytes)