Apr
11
2012

Import Gmail or Google Contacts Using PHP and OAuth 2.0

Websites like facebook, Orkut or Email providers like Yahoo helps visitors to import contacts from other email providers. Here we consider gmail. As a developer, it is always good to know the concepts of oauth 2.0 and how to use it using php. Today we are trying to use these technologies to import Contacts from Google and display it to the user.

 

Demo  Download

 

 

Step 1: We need to register the domain we are going to use in order to use Google OAuth 2.0. Website registration for OAuth 2.0 is different from that of OAuth 1.0 protocol inside google. As a start, visit Google API Console. Click on ‘Create New Project’.

 

 

Step 2: Select ‘API Access’ from left menu and Click ‘Create an OAuth 2.0 Client’ button.

 

 

Step 3: Provide a product name. This product name will be displayed to users while authenticating. You may upload a logo within mentioned dimensions.

 

 

Click ‘Next’

 


 

Step 4: Mention redirect urls and domain for your web application

 

 

On submitting you can view your API credentials to use.

 

 

OAuth 2.0 for Server Side Web Applications

 

Now we have all the credentials to develop our application. Server Side Flow involves mainly 2 parts:

  1. Application asks the user for permission to access their data—if the user approves, instead of sending an access token directly as in the client-side flow, Google will send our application an authorization code.
  2. Application will POST that code along with its client secret to Google in order to get both an access token and a long-lived refresh token.

Step 1: Create ‘index.php’ file. Paste the following html code inside body tag. Add some css stuff according to your requirement.

<a href="https://accounts.google.com/o/oauth2/auth?client_id=1052204859802.apps.googleusercontent.com&redirect_uri=http://localhost/google/oauth/validate.php&scope=https://www.google.com/m8/feeds/&response_type=code">Login using Google</a>

 

 

This is how your index page will look like

 

 

Step 2: Now click on ‘Login Using Google’ Button. You should get a screen similar to below one.

 

 

login with the account that you want to fetch contacts from.

 

Step 3: You should get a screen similar to below one. Do not click on ‘Allow Access’ now. Before that we need to complete some steps.

 

 

Step 4: Create ‘validate.php’ as the callback url. Your file name depends upon the call back url provided by you inside index.php file. Now go back to your Permissions page and click ‘Allow Access’. The page is redirected to validate.php with a code. I got something like:

 

http://localhost/oauth/validate.php?code=4/CJ6IGv9sE1uX4xuPh2hA-u-X6QlU

 

 

Step 5: Inside ‘validate.php’ we will write code to pass the authorization code and in return get an access_token and refresh_token. The received access_token is used to get contact email ids from logged in user.

Paste the following php code inside body tag.

<?php

//setting parameters

$authcode= $_GET["code"];

$clientid='1052204859802.apps.googleusercontent.com';

$clientsecret='your client secret from api console';

$redirecturi='http://localhost/google/oauth/validate.php';

$fields=array(

'code'=>  urlencode($authcode),

'client_id'=>  urlencode($clientid),

'client_secret'=>  urlencode($clientsecret),

'redirect_uri'=>  urlencode($redirecturi),

'grant_type'=>  urlencode('authorization_code')

);

//url-ify the data for the POST

$fields_string='';

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }

$fields_string=rtrim($fields_string,'&');

//open connection

$ch = curl_init();

//set the url, number of POST vars, POST data

curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');

curl_setopt($ch,CURLOPT_POST,5);

curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

// Set so curl_exec returns the result instead of outputting it.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//to trust any ssl certificates

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//execute post

$result = curl_exec($ch);

//close connection

curl_close($ch);

//extracting access_token from response string

$response=  json_decode($result);

$accesstoken= $response->access_token;

//passing accesstoken to obtain contact details

$xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$accesstoken);

//reading xml using SimpleXML

$xml=  new SimpleXMLElement($xmlresponse);

$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');

$result = $xml->xpath('//gd:email');

foreach ($result as $title) {

echo $title->attributes()->address . "<br><br>";

}

?>

Here is the flow of controls inside above code snippet. We first obtain the authorization code from query string. Rest of the parameters are known to us and we are POSTing the request using CURL to obtain access token in JSON format. The access token is then extracted from JSON string using json_decode. Extracted access token is then passed to feed link to obtain email ids.

Some key notes to remember. While using CURL we need to include ‘curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);’ since the protocol is https. Normal CURL code snippets were not giving me the output. Also in the final XML list of contacts, emails are withing a custom tag named ‘gd:email’. In order to extract values from a custom tag we need to register the namespace for custom tag ‘gd’ using ‘registerXPathNamespace’. Now run index.php and if everything went smooth, you should see your contact list.

This demo fetches only 25 contacts. if you want to fetch more records then you can change this line :

$xmlresponse=  file_get_contents(‘https://www.google.com/m8/feeds/contacts/default/full?oauth_token=’.$accesstoken);

TO

$xmlresponse= file_get_contents(‘https://www.google.com/m8/feeds/contacts/default/full?oauth_token=’.$accesstoken.’&max-results=1000′);

Now you can fetch up to 1000 contacts.

 

Demo  Download

 

Related Posts

About the Author: Vrushank Brahmakshatriya

I am Vrushank Brahmakshatriya a 24 year old Entrepreneur blogger, Founder and Editor of "WebDeveloperGeeks". I spend too much time in front of the computer and find myself telling my wife', "We'll go in 5 minutes!" far too often. I just can't go out to dinner while I'm still producing FireBug errors...drives me crazy. I love jQuery, PHP, MYSQL, CSS, AJAX - pretty much anything. You can follow me on @twitter and @facebook

1 Comment + Add Comment

  • Hi, your article is wonderful. when i try to implement this from my machine. but i am facing one issue.

    ———————————-
    Notice: Undefined property: stdClass::$access_token in C:\wamp\www\2012\oct8\oauth\validate.php on line 38

    Warning: file_get_contents(https://www.google.com/m8/feeds/contacts/default/full?oauth_token=&max-results=5000) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Authorization required in C:\wamp\www\2012\oct8\oauth\validate.php on line 43

    Fatal error: Uncaught exception ‘Exception’ with message ‘String could not be parsed as XML’ in C:\wamp\www\2012\oct8\oauth\validate.php:45 Stack trace: #0 C:\wamp\www\2012\oct8\oauth\validate.php(45): SimpleXMLElement->__construct(”) #1 {main} thrown in C:\wamp\www\2012\oct8\oauth\validate.php on line 45

    ————————————————
    can u help me to solve this issue.

Leave a comment


GeeksLabs Network

Subscribe To My Blog

Enter your email address:

Delivered by FeedBurner

Donate


If you like what I do, please consider donating a token of your appreciation.

Tag Cloud

Ajax (2)
Android (4)
Blackberry (1)
Brochures & Cards (4)
Charts (1)
CMS News (1)
CSS (9)
CSS3 (9)
database (1)
Design (1)
Drupal (1)
Editors (1)
Flash (1)
Font (2)
Form (1)
HTML (6)
HTML5 (8)
Icon (3)
Illustration (7)
Infographics (2)
Insipration (9)
Inspiration (4)
iphone & ipad (1)
Java (1)
JavaScript (3)
Joomla (1)
Jquery (13)
Jquery (9)
Logo (3)
Magento (1)
Mobile News (4)
Open Source (6)
Photography (1)
PHP (6)
PHP (4)
PSD (3)
Resources (3)
SEO (1)
Template (15)
Text Effect (1)
Textures (4)
Tools (5)
Tutorial (1)
Typography (3)
Uncategorized (1)
Vectors (1)
Wallpapers (1)
Web Apps (4)
Web Development (1)
Wordpress (4)

WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.

Buffer