Tag Archives: Google+

Login through Google+ and OAuth API

One of the common scenarios is to login through an external account like Google+, Twitter or Facebook.
In this code snippet I will show how to login using Google+ API

First you need to register your api at https://code.google.com/apis/console/, register the Google+ API Service and create a new application; in the “Redirect URI” you need to pass the path of the script and add the following: “googleplus.php?op=redirect” I will comment why is this later, after you see the code, you can fragment code into other more elegant paths/scripts.

From the generated application you will need the Redirection URI and the Client ID

Google OAuth works in the following way:

  1. Generate an URL using params of services you want to access (scope) and your Client ID and Redirection URI
  2. You need to redirect user to this URL
  3. After user has approved the use, you will be redirected with a hash params, so your server won’t see it, you can pass to your server through ajax or in this case through a GET request

In the code the “?op=redirect” will show just a white page with a javascript redirection to convert the hash location into a normal GET request; this will enable in the server to grab the access_token which you can use to verify through Google+ site if is valid.
This code part does it:

<?php
        $access_token = $_GET['access_token'];

	//do something with the token, first check is real
	$data = @file_get_contents("https://www.googleapis.com/plus/v1/people/me?access_token={$access_token}");
	if ($data) {
		print $data;
	} else {
		print "Token not valid!";
	}

The code is not prepared to handle error (will show as a $_GET['error'] after have redirected) so you need to handle that for your scenario.

Links:

 

Share