Google and Oauth2

This week I had to work with the Google api for a project and I’m caught my attention the systems that they have for authenticate and use your services. It seems perfect. Unfortunately its documentation is just the opposite, so I will explain the steps that I had to do for if someone helps you.

Before continue, tell that you have two ways for use the Google api in your application php. The first is using the class that Google have implemented and published in your repository. The other option is write your own code using only that the services that you need.

Personally, If you have time, I recommend look that us class because, although its documentation is practically null, some times interesting things are discovered.

Unfortunately, the time is gold, and I decided choose the second option that, although it seems less good, us can help to understand how the system works.

Well, lets start with an example for better understanding. Imagine that you like put in your web a button of login that connect with the Google api (exist codes in the network more simple for embed this process in your web but this is an example for understand how works the Google api). For works well, the process need complete next steps:

Graphic process of request information to Google api

  1. The user click login button for identified in our web application with Google account.
  2. Our web application, request permission for access to info about the user.
  3. The Google api request permission to user for our web application access to user data.
  4. When the user accept, the Google api send to our web application a code with that get a valid token.
  5. With this code, our web application request a valid token for access to user data.
  6. The Google api return a valid token with that it we can get information.
  7. Our web application, request the user data attached the token returned before.
  8. The Google api return the user data.
  9. And the process is finished. You can view a graphic with the process on lateral image for best understanding.

Sign up web application in api GoogleSo return to example before. For complete the last process, first you need register your web application in Google (the process is more similar to register a application in Facebook api but Google, fortunately, not build a lot of walls how Facebook to hour to register a application. Unlike Facebook, the process is simple and easy). As a note, saying that you need take special care to write callback url because two reasons. First because Google use this field (and other more) how field security, when you send a request for a valid token “if the callback dispatched is different that they are registered, the process is invalid”. The other reason is more obviously, is because the callback is the url that Google return the user when him accept that your application access to user data.

After register, you need remember, the client id and client secret (also callback that you are write).

services api GoogleNext, you need activate services that you need use from Google. To do this, go to “services” tab and active the services that do you need and that’s all. For most services, will have no problems but for some services (how Blogger api services) you have fill a full form (like a visit to the pope of Rome they were) explaining your intentions, while on other services, you need directly use your credit card (how the Maps api) if you do a intensive use. My advice is that you only active the services that you need and read by careful the limits that have the services that use if you not like a future surprises (they are adjacently of the button of activation that have each service).

We must also take into consideration that in this list don’t show all services available and that others services are activate by default because they are free and they not have any limitations. Only need to add to the list of services that our application are going to use and that’s all, but I’m moving forward. I will explain this theme in more detail after.

When we registered our application, only need program the process for obtain a valid token, so we can request queries to Google api without send continuously our application identified or the user identified data.

For obtain a valid token, we need to send a GET request to https://accounts.google.com/o/oauth2/auth with next parameters:

Parameter Description
response_type Indicate to Google that they have return a authorization code. This code our are necessary for request a valid token. The value of this parameter is always “code”.
client_id The client id of your application. We obtained earlier when we registered our application in Google.
redirect_uri The url callback that we indicate when registered the application. You need have careful when write this url. You need write exactly how you wrote when registered the application in Google. If you no write exactly, Google not leaves continue and show error “Invalid callback”.
scope This is the list of permissions that Google will ask to user if him permit access to our application.
You can add all services that you have activate when registered our application but exist some services (how for example, the access of webmaster tools) that not necessary activate.
For know how activate this services, you need search in the documentation of each service, which scope identified the service that your need use and add to our list of services that we application use. For example, the identification scope of analytics service is “https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics”
state This field is a string that may contain the value we want. This string, Google returns in the first response so we can use, for example, if you have more logins buttons to Google in different locations our web, know what is the button that the user activate and actuate as the case. Is required write something, you not forget.
Download index.php
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
<?php
define('CLIENTID','xxxxxxxxxxxx.apps.googleusercontent.com');
define('CLIENTSECRET','xxxxxxxxxxxxxxxxxxxxxxx');
define('URLCALLBACK', 'http://xxxxx.com/googcallback.php');
define('URL','http://xxxxx.com/');
 
if (isset($_GET['error']) && $_GET['error']){
	$error = $_GET['error'];
 
	header('Location: '.URL.'error.php?errorg='.$error);
	die();
} elseif (isset($_GET['code']) && $_GET['code']) {
	$code = $_GET['code'];
 
	header('Location: '.URL.'googcallback.php?code='.$code);
	die();
} else {
	$scope = 'https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+';
	$scope .= 'https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+';
	$scope .= 'https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly+';
 
	$url = "https://accounts.google.com/o/oauth2/auth?scope=$scope&state=%2Fprofile&redirect_uri=".URLCALLBACK."&response_type=code&client_id=".CLIENTID;
 
	header('Location: '.$url);
	die();
}
?>

When you send the request to Google api, if all works well, they return by GET method a code (in variable “code”) with that you request a valid token. For request a valid token you must send POST request to https://accounts.google.com/o/oauth2/token adding next parameters:

Parameter Description
code The code returned in last request. This code is for only one use so if you do not make the request correctly or the connection is cut before finish the process, you must request a new code starting over.
client_id The same client id before.
client_secret The client secret copied before, when you registered the application on Google.
redirect_uri The url callback written when you registered the application.
grant_type This field is not specified much in Google documentation. It just has to have a value of “authorization_code”

If all process is finished well, the api return a JSON file with the token and other attributes of this field such the type of token, when the token expires and a id of this.

The value most important of all is the token, because is necessary for send sentences to Google api. The other values is only if you like send sentences for a long period of time (because the token have a date expire and when they arrives, you need request a new valid token).

So next, I write an example code in php for request a valid token to Google api.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
define('CLIENTID','xxxxxxxxxxxx.apps.googleusercontent.com');
define('CLIENTSECRET','xxxxxxxxxxxxxxxxxxxxxxx');
define('URLCALLBACK', 'http://xxxxx.com/googcallback.php');
define('URL','http://xxxxx.com/');
 
function request_token($code){
//Request the token to Google with the code received
	$tokendata = array();
 
	$ch = curl_init('https://accounts.google.com/o/oauth2/token');
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "code=".$code."&client_id=".CLIENTID."&client_secret=".CLIENTSECRET."&redirect_uri=".URLCALLBACK."&grant_type=authorization_code");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); 
	$result_curl = curl_exec($ch);
	$error_curl = curl_error($ch);
	curl_close($ch);
 
	$res = json_decode($result_curl);
 
	if ($res->access_token){
		$tokendata['token_access']=$res->access_token;
	}
	if ($res->token_type){
		$tokendata['token_type']=$res->token_type;
	}
	if ($res->expires_in){
		$tokendata['token_expires_in']=$res->expires_in;
	}
	if ($res->id_token){
		$tokendata['token_id']=$res->id_token;
	}
	return $tokendata;
}
 
$code='';
$param='';
$tokendata = array();
 
if(isset($_GET['code']) && $_GET['code']){
	$code = $_GET['code'];
}
 
if ($code){
	$tokendata = request_token($code);
}
?>

So with this, we have all necessary for request sentences to Google api. You must have got that all responses of Google api are in JSON format so that I recommend read the documentation about the service that you use for know how process the responses correctly.

Next, I write a example for how obtain a e-mail about the user logged in our application with a Google account.

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
<?php
define('TOKENGOOGLE','xxxxxxxxxxxx');
 
function get_userEmail($token){
	$email = '';
 
	$url = 'https://www.googleapis.com/oauth2/v1/userinfo';
	$url .= '?access_token='.$token;
 
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); 
	$result_curl = curl_exec($ch);
	$error_curl = curl_error($ch);
	curl_close($ch);
 
	$res = json_decode($result_curl);
 
	if ($res->email){
		$email = $res->email;
	}
	return $email;
}
 
$email = get_userEmail(TOKENGOOGLE);
?>

And that’s all. I hope have been useful for all people that they are start in the Google api world. I’ve only written a little guide for starting. The Google api is more complex that you can show here. I will try to put more information as I’ve discovering, but if someone needs help to answer questions and help you can write and I try response as soon as possible.

Leave a Reply

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