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.
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.
1 2 3 4 |
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
1 2 3 |
$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
1 2 3 4 5 6 7 8 9 10 11 |
//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
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 |
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
1 2 3 4 5 |
//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
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 |
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
1 |
<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:
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 |
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.
- include jquery and google client.js
1 2 3 |
<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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<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
1 |
<button onclick="auth();">GET CONTACTS FEED</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