Tutorial: Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0 in PHP

First, let me introduce what Contacts Data API and OAuth is.

OAuth

OAuth (Open Authorization) is an open standard for authorization. It allows users to share their private resources (e.g. photos, videos, contact lists) stored on one site with another site without having to hand out their credentials, typically username and password.

Google Contact Data APIs

The Contacts Data API allows client applications to view and update a user’s contacts. Contacts are stored in the user’s Google Account; most Google services have access to the contact list.

You can easily find many source codes for importing Gmail contacts by Googling. But most of them use outdated Google Contact Data API or OAuth. By using the latest APIs we can easily import the contacts with fewer lines of code and is much more efficient than the old version. OAuth is in its second generation today. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. OAuth 2.0 is not backward compatible with OAuth 1.0. Using the older APIs you couldn’t retrieve the contacts in local host. That is, it was difficult to modify or edit the code for the website as the code had to be uploaded again and again to the host. But with the help of new API you can try and edit the code in local host and it works efficiently.

In this tutorial we will be using OAuth 2.0 and Google Contacts Data API.

You can refer more about them at the links below.

http://code.google.com/apis/accounts/docs/OAuth2.html

http://code.google.com/apis/contacts/

As we had a little introduction about both the APIs, we will head to the Step by Step tutorial to import the contacts.

Step 1:

Create file ‘oauth.php’ in your web-host. For the example that I have shown, I made a folder ‘oauth’ in localhost and created the file ‘oauth.php’ in the folder.

Thus, in my case, the URL for the file is http://localhost/oauth/oauth.php

Please note your URL for the file, as you will need it in the later steps.

Now paste the code below into ‘oauth.php’ and save the file.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<html>
<head>
<meta name="robots" content="noindex" />
<title>Email address list - Import Gmail or Google contacts</title>
<style type="text/css">
	a:link {color:Chocolate;text-decoration: none;}
	a:hover {color:CornflowerBlue;}
	.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
	<div class="logo" >
		<a href="http://25labs.com/" >
			<img style="padding-top: 10px;" src="http://25labs.com/wp-content/themes/TheStyle/images/logo.png"></img>
		</a>
	</div>
	<br/>
	<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/" >Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0 in PHP</a></div>
	<br/>
	<div style="padding-left: 50px;">
<?php
$client_id='Your Client ID goes here';
$client_secret='Your Client secret goes here';
$redirect_uri='Your Redirect URIs goes here';
$max_results = 25;
 
$auth_code = $_GET["code"];
 
function curl_file_get_contents($url)
{
 $curl = curl_init();
 $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
 
 curl_setopt($curl,CURLOPT_URL,$url);	//The URL to fetch. This can also be set when initializing a session with curl_init().
 curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);	//TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
 curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);	//The number of seconds to wait while trying to connect.	
 
 curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);	//The contents of the "User-Agent: " header to be used in a HTTP request.
 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);	//To follow any "Location: " header that the server sends as part of the HTTP header.
 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);	//To automatically set the Referer: field in requests where it follows a Location: redirect.
 curl_setopt($curl, CURLOPT_TIMEOUT, 10);	//The maximum number of seconds to allow cURL functions to execute.
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);	//To stop cURL from verifying the peer's certificate.
 
 $contents = curl_exec($curl);
 curl_close($curl);
 return $contents;
}
 
$fields=array(
    'code'=>  urlencode($auth_code),
    'client_id'=>  urlencode($client_id),
    'client_secret'=>  urlencode($client_secret),
    'redirect_uri'=>  urlencode($redirect_uri),
    'grant_type'=>  urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
 
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);
$result = curl_exec($curl);
curl_close($curl);
 
$response =  json_decode($result);
$accesstoken = $response->access_token;
 
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$accesstoken;
$xmlresponse =  curl_file_get_contents($url);
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0)) //At times you get Authorization error from Google.
{
	echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
	exit();
}
echo "<h3>Email Addresses:</h3>";
$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>";
}
?>
	</div>
</body></html>

Step 2:

To use the Google API, you need to register your product at Google. To start the Registration process, head to Google API Console.

If you haven’t created any projects yet, then you will be seeing a page as shown below. Click ‘Create Project…’ button.

Create Project

Create Project

If you have created a project earlier, then you will be taken to an existing project directly. Click on the drop down menu that has the current project’s name which is located at the top left of the webpage (In my case it is ‘API Project’) and click ‘Create…’ in ‘Other projects’ tab. Now you will be asked to enter the name of the project. Enter a name as you wish.

API Projects drop down

API Projects drop down

API drop down - Create

API drop down - Create

Step 3:

Click ‘API Access’ from the let menu.

API Access

API Access

Step 4:

Now click on ‘Create an OAuth 2.0 client ID…’ button on the page that just opened up.

Create OAuth client ID

Create OAuth client ID

Step 5:

Fill in a name for the project. When a user clicks to retrieve the contacts, this product name will be shown on the conformation page. So please provide a sensible name.

You can optional give a product logo. The maximum allowed size for the logo is 120 x 60 pixels. This logo will also be displayed on the user’s confirmation page.

Create Client ID

Create Client ID

After you fill in the details click ‘Next’ button.

Step 6:

Now you will be taken to Client ID settings page.

Choose ‘Web application’ radio button for the Application type.

In ‘Your site or hostname’ block, choose ‘http://’ or ‘https://’ as per your requirement.

Now, enter your domain for the web application. You can also provide ‘localhost’.

Create Client ID

Create Client ID

Now, click ‘more options’ which lies next to ‘Your site or hostname’.

Enter the url that we created in Step 1 as ‘Authorized Redirect URIs’.

You will automatically have your host address as ‘Authorized JavaScript Origins’. You can enter more origins if you wish.

Create OAuth client ID

Create OAuth client ID

Click ‘Create client ID’ button.

Step 7:

Now you have registered your product and you can view the API credentials for your web application.

Note down the Client ID, Client secret and Redirect URIs. You will need them in Step 8 and 9.

API Credentials

API Credentials

Step 8:

Open oauth.php that you created in Step 1.

Replace ‘Your Client ID goes here’, ‘Your Client secret goes here’ and ‘Your Redirect URIs goes here’ with the Client ID, Client secret and Redirect URIs that you created in Step 7, respectively.

You can optionally change the number next to ‘$max_results’. It specifies the maximum number of email addresses to be retrieved.

Step 9:

Create the button or link that the user needs to click to retrieve the contact list and set its href parameter to

'https://accounts.google.com/o/oauth2/auth?client_id=your_client_id_goes_here&redirect_uri=your_redirest_urls_goes_here&scope=https://www.google.com/m8/feeds/&response_type=code'

Replace ‘your_client_id_goes_here’ and ‘your_redirest_urls_goes_here’ with the Client ID and Redirect URIs that you created in Step 7, respectively.

Or you can optionally copy the code given below, replace ‘your_client_id_goes_here’ and ‘your_redirest_urls_goes_here’ as mentioned above, and save it as a new file, may be ‘index.php’.

Then save it to your host.

Please make sure that you place this file in a directory that satisfies ‘JavaScript origins’ that you specified in Step 6.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<meta name="robots" content="noindex" />
<title>Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0</title>
<style type="text/css">
	a:link {color:Chocolate;text-decoration: none;}
	a:hover {color:CornflowerBlue;}
	.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
	<div class="logo" >
		<a href="http://25labs.com/" >
			<img style="padding-top: 10px;" src="http://25labs.com/wp-content/themes/TheStyle/images/logo.png"></img>
		</a>
	</div>
	<br/>
	<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/" >Import Gmail or Google contacts using Google Contacts Data API and OAuth 2.0 in PHP</a></div>
	<br/><br/>
	<div align="center" >
	<a  style="font-size:25px;font-weight:bold;" href="https://accounts.google.com/o/oauth2/auth?client_id=your_client_id_goes_here&redirect_uri=your_redirest_urls_goes_here&scope=https://www.google.com/m8/feeds/&response_type=code">Click here to Import Gmail Contacts</a>
	</div>
</body>
</html>

We have now successfully completed the web application to retrieve Gmail or Google contacts.

Testing the web application:

Now it’s the turn to test the application. Please follow the steps mentioned below.

Step 10:

Browse to the file that created in Step 9 using your favorite web browser. Click on the button or link that you created to retrieve the contacts.

There is a chance that you get an error similar to the one shown below, especially if you are trying it on localhost.

Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\oauth\oauth.php on line 24

If you are among the unlucky ones, please follow the procedure mentioned below to solve the issue.

Solution:

If you are on localhost open:

php/php.ini

php/browscap/php.ini (if existent)

php/php4/php.ini (if existent)

apache/bin/php.ini (if existent)

 

If you are on web host, open web host’s ‘php.ini’

 

Search for ‘extension=php_curl.dll’.

If not found add it to ‘Dynamic Extensions’ section.

If found, uncomment the statement.

Then restart Apache if on localhost.

Try Step 10 again.

Step 11:

You will be taken to a conformation page which will look similar to the one shown below.

Import Gmail Contacts

Import Gmail Contacts

Click ‘Allow Access’ button.

Step 12:

If everything went right, you will have a list of email addresses on screen.

Please comment below, if you have any queries or errors.