At a basic level, the process is as follows:
- Your application requests access and gets an unauthorized request token from Google’s authorization server.
- Google asks the user to grant you access to the required data. If the user is not already logged in, Google prompts the user to log in. Google then displays an authorization page that allows the user to see what Google service data your application is requesting access to.
- Your application gets an authorized request token from the authorization server. Each request token is valid for only one hour.
- You exchange the authorized request token for an access token.
- You use the access token to request data from Google’s service access servers. By default, access tokens are long-lived. Each access token is specific to the user account specified in the original request for authorization, and grants access only to the services specified in that request. Your application should store the access token securely, because it’s required for all access to a user’s data.
First of all we need to register our web application with google. Here are some advantages of registering a web application with google. Registered applications:
- are recognized by Google. The Google “Access Consent” page, which asks users to grant/deny access to their account when requested by third-party applications, omits default text cautioning that the site is not trusted.
Here is an image which shows the caution text with yellow background

- can provide a better level of security for their users.
- get access to certain services (such as some Google Data API feeds) that require third-party applications to be registered.
Each oauth requests has to be signed. If you don’t know what is signing, just take the literal meaning of signing a cheque. It means you are authorizing a check with your identity. In a similar fashion, in online web signing an application can be done using RSA-SHA1 or HMAC-SHA1 signature. First one needs a digital signature which states that the specified signature belongs to you. If you are interested in knowing more about creating digital signature visit this link. Later one, that is HMAC-SHA1 do not need a digital signature. Instead, Google generates an Oauth consumer secret value for each domain that is registered. In detail how signatures and why it is created, we will discuss in few minutes.
We are going to add our domain to google. Click this link to go to google manage domains page.

Type your domain name in the format ‘www.example.com’ and click ‘Add Domain’. Now if you have a sub domain say ‘www.demo.example.com’, you need to add that separately. I am giving ‘www.demo.lookmywebpage.com’ as the application runs under this domain.
Now the same page reloads with ‘Manage www.demo.lookmywebpage.com’ link. Click the link. You will be redirected to ‘Verify Domain’ page.

Verification can be done in several ways. If the domain is verified by you before, using google webmaster tool, then this step would not be there. Default step to verify is to upload an html file starting with ‘google’ to domain root folder. In case of domains, upload the file to the root folder. In case of subdomains, upload the file to corresponding sub folder. Click on ‘Verify’. You will be taken to a page to agree to terms and conditions.

Click ‘I agree to the Terms of Service’. On next page, you can provide domain details.

‘Target URL Path prefix’ stands for the path under which your app resides. If you are giving a path as ‘www.example.com/apps’ and your google oauth request is coming from ‘www.example.com/demos’ it will throw an error. Give some details of your domain. This info will be displayed on google grant access page(‘Caution Text’ image)
Upload a certificate, if you are going to use RSA-SHA1. Since I do not have a certificate and I am going to use HMAC, I am not uploading anything here. Click on ‘Save’.
Now you have an active domain registered with google with a Consumer Key and Consumer Secret.

So now to our web pages
Step 1: Create ‘index.php’ with a simple hyperlink.
<a href="action.php">Login with Google</a>
So this is your login page.
Step 2: Now what the hell is happening in ‘action.php’. From the 5 steps discussed top of this post, we are going to do first step, Requesting unauthorized request token from Google Authorization Server.
<?php
//to store time stamp
$time = time();
//preparing the parameters that too in alphabetical order
//alphabetiacal order is to generate signature
$querystring =
'oauth_callback=' . urlencode('http://demo.lookmywebpage.com/google/oauth-gmail-data/home.php') .
'&oauth_consumer_key=' . urlencode('www.demo.lookmywebpage.com') .
'&oauth_nonce=' . urlencode(uniqid() . uniqid()) .
'&oauth_signature_method=HMAC-SHA1' .
'&oauth_timestamp=' . $time .
'&scope=' . urlencode('http://mail.google.com/mail/feed/atom');
//url to request for unauthorized request token
$url = 'https://www.google.com/accounts/OAuthGetRequestToken';
//creating base string
$basestring = 'GET&' . urlencode($url) . '&' . urlencode($querystring);
$consumersecret = ‘your-consumer-secret’;
$token = '';
$key = $consumersecret . '&' . $token;
$signature = base64_encode(hash_hmac('SHA1', $basestring, $key, true));
$url = 'https://www.google.com/accounts/OAuthGetRequestToken?' . $querystring . '&oauth_signature=' . urlencode($signature);
//fetching token and token secret
$response = file_get_contents($url);
//extracting token
$ltrimarray = explode("oauth_token=", $response);
$rtrimarray = explode("&", $ltrimarray[1]);
$oauth_token = $rtrimarray[0];
//extracting token secret
$ltrimarray = explode("oauth_token_secret=", $response);
$rtrimarray = explode("&", $ltrimarray[1]);
$oauth_token_secret = $rtrimarray[0];
//storing token secret to cookie to use in next page
setcookie("token_secret", $oauth_token_secret, time() + 3600);
//redirecting to google access/deny page
header('Location:https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=' . $oauth_token);
?>
Its difficult to explain everything after the code. So I have written some explanation as comments. Here I will explain some key points. ‘time()’ function returns current timestamp. Its stored to a variable $time as it is used in 2 places. We cannot use time() at both places as it may change. Our query string is prepared with the variable $querystring. You can understand full parameter list for getting unauthorized request token from this google page.
Let me now explain little bit about signature. In this case you are sending google a request with a url and some parameters. With these url and parameters you create one signature. Just consider a machine which outputs signature. Now here the input to the machine is your url and parameters in a standard format. That standard format is Basestring. Now the machine also needs 2 more main ingredients. One is key and other is algorithm. Key is your consumer secret given by google. Algorithm is SHA1. We are generating the signature using base64encoding and hmac function in php. Signature therefore will be always of fixed length. Once our request reaches google, google also generates signature with our request and if google’s signature and ours match, it means no tampering or security leaks have happened.
Step 2: Users have ‘Grant/Deny’ Access page now.

Once they grant access they will be redirected to your call back page(in our case home.php). So create home.php file and paste following code there.
<?php
$time = time();
//preparing query for authorized request token
$querystring =
'oauth_consumer_key=' . urlencode('www.demo.lookmywebpage.com') .
'&oauth_nonce=' . urlencode('4e18ada0d45784e18ada0d495c') .
'&oauth_signature_method=HMAC-SHA1' .
'&oauth_timestamp=' . $time .
'&oauth_token=' . urlencode($_GET["oauth_token"]) .
'&oauth_verifier=' . urlencode($_GET["oauth_verifier"]) .
'&oauth_version=' . urlencode('1.0');
//url to obtain authorized request token
$url = 'https://www.google.com/accounts/OAuthGetAccessToken';
//base string for generating signature
$basestring = 'GET&' . urlencode($url) . '&' . urlencode($querystring);
$consumersecret = 'your-consumer-secret';
//token secret from unauthorized request token
$token = $_COOKIE["token_secret"];
$key = $consumersecret . '&' . $token;
$signature = base64_encode(hash_hmac('SHA1', $basestring, $key, true));
$url = 'https://www.google.com/accounts/OAuthGetAccessToken?' . $querystring . '&oauth_signature=' . urlencode($signature);
//getting authorized request token
$response = file_get_contents($url);
$ltrimarray = explode("oauth_token=", $response);
$rtrimarray = explode("&", $ltrimarray[1]);
$oauth_token = $rtrimarray[0];
$ltrimarray = explode("oauth_token_secret=", $response);
$rtrimarray = explode("&", $ltrimarray[1]);
$oauth_token_secret = $rtrimarray[0];
setcookie("token_secret1", $oauth_token_secret, time() + 3600);
header('Location:mailinfo.php?oauth_token=' . $oauth_token);
?>
Nothing much to explain here. Same type of code to obtain access token.
Step 3: create a file ‘mailinfo.php’ and paste following code.
<?php
$time = time();
$querystring =
'oauth_consumer_key=' . urlencode('www.demo.lookmywebpage.com') .
'&oauth_nonce=' . urlencode('4e18ada0d45784e18ada0d495d') .
'&oauth_signature_method=HMAC-SHA1' .
'&oauth_timestamp=' . $time .
'&oauth_token=' . urlencode($_GET["oauth_token"]) .
'&oauth_version=' . urlencode('1.0');
$url = 'https://mail.google.com/mail/feed/atom/';
$basestring = 'GET&' . urlencode($url) . '&' . urlencode($querystring);
$consumersecret = 'your-consumer-secret';
$token = $_COOKIE["token_secret1"];
$key = $consumersecret . '&' . $token;
$signature = base64_encode(hash_hmac('SHA1', $basestring, $key, true));
$url = 'https://mail.google.com/mail/feed/atom/';
$querystring = str_replace("=", "=\"", $querystring);
$querystring = str_replace("&", "\", ", $querystring);
$querystring = $querystring . "\", oauth_signature=\"" . urlencode($signature) . "\"";
$r = 'Authorization: OAuth ' . $querystring;
$header = array($r); //create header array and add 'Expect:'
$options = array(CURLOPT_HTTPHEADER => $header, //use our authorization and expect header
CURLOPT_HEADER => false, //don't retrieve the header back from Twitter
CURLOPT_URL => $url, //the URI we're sending the request to
CURLOPT_RETURNTRANSFER => true, //return content as a string, don't echo out directly
CURLOPT_SSL_VERIFYPEER => false); //don't verify SSL certificate, just do it
$ch = curl_init(); //get a channel
curl_setopt_array($ch, $options); //set options
$response = curl_exec($ch); //make the call
curl_close($ch); //hang up
//extracting contents using simple xml
$xml = simplexml_load_string($response);
echo $xml->title . '<br>';
echo 'You have ' . $xml->fullcount . ' ' . $xml->tagline . '<br><br>';
foreach ($xml->entry as $child) {
echo 'Subject: <b>' . $child->title . '</b><br>';
echo 'From: ' . $child->author->name . '<' . $child->author->email . '><br>';
echo 'Time: <i>' . $child->modified . '</i><br>';
echo 'Summary: ' . $child->summary . '<br><br>';
}
?>
Here the parameters are passed using authorization headers. You can view your unread messages from gmail here. Here is the link for google Oauth page.

















Really nice post mona !
Easy explanations … Keep Up !