X

Import Google contacts with PHP or Javascript using Google Contacts API and OAUTH 2.0

Inviting friends to a web application is a key factor to gain more users and traffic.

In this article we will try to give a practical, step by step web development example on how you can easily import google contacts to your web application, because even if google offers an api documentation, it’s always hard to find an example that is not out-dated,  that fits in your app without having headaches and losing precious time.

This tutorial will offer examples for Server Side application (php) but also for Client Side application (javascript). We will use OAUTH 2.0 authentication and Google Contacts API version 3.0.

View on githubYou can also view the source code on Github

View demoView live example

Step 1

Create a Google application in Google Developers Console for obtaining your Client id and Client secret.

  • Go to Google Google Developers Console and login with your google account.
  • If you don’t have already a project, create one

  • Go into the newly created project
  • In the left menu, go to APIs & auth > API’s

  • Search for “Contacts API” and click on it
  • Enable the “Contacts API” by hitting the “Enable API” button

  • Go to “Consent screen” if you didn’t set a product name already. In the left menu, go to APIs & auth > Consent screen
  • Configure your “Consent screen” settings

  • Create a new OAuth Client ID. In the left menu, go to APIs & auth > Credentials
  • Click on “Create a new Client ID”

  • For “Application type” select “Web Application” and enter a proper URL for “Authorized javascript origins” and “Authorized Redirect URIs” and click “Create Client ID”.
    • Note: It’s important that you enter your correct url application or “Authorized Javascript origins”, something like http://www.example.com.
    • The url that you will enter on “Authorized redirect URIs” , will be the url that google will use to redirect with your response data. For example, after a user will accept giving credentials to your application, will be automatically redirected to http://www.example.com/response-callback.php . In this file you can read the google contacts.
  • If everything goes well, you will now able to see your API credentials, Client ID and Client Secret

 

Step 2

Server side example using PHP

  • Use a real, online server to integrate this example. Localhost server will not work.
  • download and include “Google APIs Client Library for PHP” in your php application. We will use a file name “response-callback.php” located in the root application, for the example bellow.
session_start();

//include google api library
require_once 'google-api-php-client/src/Google/autoload.php';// or wherever autoload.php is located
  • Declare your Google Client ID, Google Client secret and Google redirect uri in  php variables
  • It’s important that the redirect uri to be added be added in Google Developers Console , in your Authorized redirect URIs
$google_client_id = 'Your google client id here';
$google_client_secret = 'Your google client secret here';
$google_redirect_uri = 'http://www.example.com/response-callback.php';
  • setup new google client
//setup new google client
$client = new Google_Client();
$client -> setApplicationName('My application name');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');

$client -> setScopes('https://www.google.com/m8/feeds');

$googleImportUrl = $client -> createAuthUrl();
  • create a curl function
function curl($url, $post = "") {
	$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.
	if ($post != "") {
		curl_setopt($curl, CURLOPT_POST, 5);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
	}
	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;
}
  • Google will redirect back to our URL with a code token parameter, for example: http://www.example.com/response-callback.php?code=1241254
  • For better UX, we can store the received code into a session, and redirect back to this url
//google response with contact. We set a session and redirect back
if (isset($_GET['code'])) {
	$auth_code = $_GET["code"];
	$_SESSION['google_code'] = $auth_code;	
}
  • Check if we have session with our token code and retrieve all contacts, by sending an authorized GET request to the following URL : https://www.google.com/m8/feeds/contacts/default/full
  • Upon success, the server responds with a HTTP 200 OK status code and the requested contacts feed. For more informations about parameters check Google API contacts documentation
if(isset($_SESSION['google_code'])) {
	$auth_code = $_SESSION['google_code'];
	$max_results = 200;
    $fields=array(
        'code'=>  urlencode($auth_code),
        'client_id'=>  urlencode($google_client_id),
        'client_secret'=>  urlencode($google_client_secret),
        'redirect_uri'=>  urlencode($google_redirect_uri),
        'grant_type'=>  urlencode('authorization_code')
    );
    $post = '';
    foreach($fields as $key=>$value)
    {
        $post .= $key.'='.$value.'&';
    }
    $post = rtrim($post,'&');
    $result = curl('https://accounts.google.com/o/oauth2/token',$post);
    $response =  json_decode($result);
    $accesstoken = $response->access_token;
    $url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
    $xmlresponse =  curl($url);
    $contacts = json_decode($xmlresponse,true);
	
	$return = array();
	if (!empty($contacts['feed']['entry'])) {
		foreach($contacts['feed']['entry'] as $contact) {
           //retrieve Name and email address  
			$return[] = array (
				'name'=> $contact['title']['$t'],
				'email' => $contact['gd$email'][0]['address'],
			);
		}				
	}
	
	$google_contacts = $return;
	
	unset($_SESSION['google_code']);
	
}
  • create the link that the user will click to import his contacts
<a href="<?php echo $googleImportUrl; ?>"> Import google contacts </a>
  • when the user will click on that link he will be asked to allow permissions for your application

  • the user will be automatically redirected to your application, and you can display his contact list

 

UPDATE: How to import contact photos using Google Contact API

Google documentation about retrieving a contact’s photo.

To retrieve a contact’s photo, send an authorized GET request to the contact’s photo link URL.
Considering that we already have the contact photo link in our $contacts array above, we just need to import the photo with a GET request using PHP.

When parsing the contacts in the php foreach, we will retrieve also the image for each contact. The foreach code will become:

	if (!empty($contacts['feed']['entry'])) {
		foreach($contacts['feed']['entry'] as $contact) {
            //retrieve Name and email address  
			$return[] = array (
				'name'=> $contact['title']['$t'],
				'email' => $contact['gd$email'][0]['address'],
			);

            //retrieve user photo
			if (isset($contact['link'][0]['href'])) {
				
				$url =   $contact['link'][0]['href'];
				
				$url = $url . '&access_token=' . urlencode($accesstoken);
				
				$curl = curl_init($url);

		        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
				curl_setopt($curl, CURLOPT_VERBOSE, true);
		
		        $image = curl_exec($curl);
		        curl_close($curl);
				
			}

                        $return['image'] = $image;

                        echo '';

		}				
	}

 

Step 2 (alternative) :

Client side example using Javascript

According to Google documentation about “OAuth 2.0 for Client-side Applications” , your application should always use HTTPS when using client side implementation.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  	
<script src="https://apis.google.com/js/client.js"></script>
  • authorize access and fetch contacts
<script type="text/javascript">
	  function auth() {
	    var config = {
	      'client_id': 'your client ID HERE',
	      'scope': 'https://www.google.com/m8/feeds'
	    };
	    gapi.auth.authorize(config, function() {
	      fetch(gapi.auth.getToken());  
	     
	    });
	  }
	
	  function fetch(token) {
	    $.ajax({
		    url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
		    dataType: "jsonp",
		    success:function(data) {
                              // display all your data in console
		              console.log(JSON.stringify(data));
		    }
		});
	}	
</script>
  •  Make a button to fire the event
<button >

 

Still having problems importing your contacts using Google API?

Don’t hesitate to post your question bellow, in the Comments section.

 

New, on our blog: A tutorial on importing Gmail contacts with PHP or Javascript using Google Contacts API and OAUTH 2.0…

Posted by Design19 on Monday, May 4, 2015

 

 

Bogdan Rusu: Working in development for more then 10 years, Bogdan Rusu is the CTO of Design19 web agency. Highly skilled in PHP development and usage of CMS like Wordpress, Magento, Zend framework, but also custom built platforms based on PHP, Bogdan has driven the team to a higher level of proficiency in development.

View Comments

  • Hi Bogdan. Thank you for this great tutorial: following your instruction I setup everything and it works like a charm!
    But I have a problem importing images: I use the Javascript to get Google contacts but I'm not able to do the right request for the profile image. Here's my code:

    for ( var i = 0;i < contacts['feed']['entry'].length;i++ ) {
    if ( contacts['feed']['entry'][i]['link'][0]['href'] != null ) {
    profileImageUrl = contacts['feed']['entry'][i]['link'][0]['href']+'?v=3.0&access_token=' + token.access_token;
    jQuery.ajax({
    type: 'get',
    url: profileImageUrl,
    success: function(result)
    {
    console.log(result);
    },
    });
    }
    if ( contacts['feed']['entry'][i]['gd$email'] != null ) {
    emailAddress = contacts['feed']['entry'][i]['gd$email'][0]['address'];
    if ( contacts['feed']['entry'][i]['title']['$t'] != null &&
    contacts['feed']['entry'][i]['title']['$t'] != '' ) {
    emailOwner = contacts['feed']['entry'][i]['title']['$t'];
    } else {
    emailOwner = '';
    }
    var html = '' + emailAddress + ' (' + emailOwner + ')';
    console.log(html);
    if (html !== ''){
    jQuery('#google-contacts').append(html);
    }
    }
    }
    But this gives as result a Bar request response and Cross origin request blocked message in the console. Any idea?
    Thank you again.

  • Thanks man, great work!

    Just a question; did you figure out how to update contacts? I'm really breaking my head on that...

  • Hi, I have some issue when google redirect...

    In my server:
    File Not Found
    The requested URL /response-callback.php?code=4/wlVM17D...
    Why??

  • Hi.
    Thank you for you post!
    Is it possible to receive phone number from contacts?

    Thank you.

  • I solved (I didn't see nothing after google account authorization).

    Please, add:

    print_r($google_contacts);

    and use for your session:

    if(!isset($_SESSION)) {session_start();}

    Then, all works very fine.
    Bogdan, thank you so much for your great great work.

  • Hi. Thanks for this work. Only thing is I a crazy number of contacts returned. I only have 5 contacts and it is returning over 700. They are all addresses I have sent email to or received email from, but not actual contacts. Is this normal behavior?

  • Hiiii!!!!!!!!! any solution for creating a new contact and saving it in google contact from server side

  • Thanks so much, i was able to integrate this into my codeigniter application as i used your guidelines to make a library. Thanks. Working 100%