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
Rajesh
-June 22, 2015 , 10:54 am
How can i import image of users?
Bogdan Rusu
-June 30, 2015 , 1:47 pm
That’s a good question. We posted an update to the article, so you can find now an example on how to import user photo. Please see “UPDATE: How to import contact photos using Google Contact API” section.
Mohamad
-June 27, 2015 , 5:31 pm
Hi,
I had went through your code and tried it. But got below error. can you please advise.
Not Found
The requested URL /â€Âhttps://accounts.google.com/o/oauth2/auth was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Bogdan Rusu
-June 30, 2015 , 1:59 pm
Hello,
Please be sure that you include all the steps into your code. Did you include the “Google APIs Client Library for PHP” in your code ? Also your url seems to have weird characters, so be sure that you correctly paste the code into your php application.
Roland
-July 1, 2015 , 10:22 am
Hello,
i also get an 404 error. The Link looks very strange:
“https://MYDOMAIN.de/de/test/”https:/accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2FMYDOMAIN.de…”
But the link in Firebug starts correct with:
“https:/accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2FMYDOMAIN.de…”
For over an hour I doubted myself but i found the bug.
“test/”https”
The quotation mark in in the middle cames from copy&paste and is not the correct html one. Replacing all double quotes with the correct one and the 404 Error is away.
But i have another error, i get now contacts from google. After allowing the app, i got the same view just with the link.
Greets
Roland
-July 1, 2015 , 10:59 am
Sorry again. Now it works.
The contacts cant display just with
$google_contacts = $return;
Just do a:
echo ‘
’;
Manikandan G
-July 14, 2015 , 5:43 am
hi,
i am new to this i tried this java script code but its not working for me. i can not retrieve any thing from that. i am not getting any error also. help me
Bogdan Rusu
-August 4, 2015 , 12:04 pm
Hello, please look into your console ( chrome or firefox) so you can see the results.
JRi
-July 11, 2016 , 11:32 am
Hi Bogdan,
after authorization, chrome/firefos console is empty, sorry.
Is Curl method still ok with google api 3?
Thanks in advance for the reply and for the your great work: https://dl.dropboxusercontent.com/u/802417/response.PNG
(PS
Sorry for my bad english)
Manuel Mora
-July 21, 2015 , 10:39 pm
I had the same problem as Roland for an hour to :D!. For future developers: check the quotes in the a tag a
“”””””””””””””””””””””””””
<a href="”> Import google contacts
Thanks excelent code.
Bogdan Rusu
-August 4, 2015 , 1:38 pm
Hello, thanks for your reply. Indeed, was a problem with the quotes in the a tag.
Seems that the editor was bad formatted the quotes.
I corrected the problem.
Manuel Mora
-July 22, 2015 , 2:20 am
$_SESSION[‘contactos’]=$google_contacts = $return;
unset($_SESSION[‘google_code’]);
}
if(isset($_SESSION[‘contactos’]))
{
print_r($_SESSION[‘contactos’]);
}
Done! Modify the code to see the contact list :D!
Nishant
-July 28, 2015 , 4:24 pm
HI, I everything is working fine except fetching contact’s photo. It is returning 401 error.
adam
-August 3, 2015 , 10:06 pm
nothing happening . after getting permission from google
no contacts is displayed
only a blank screen with link button “get contacts feed”
Bogdan Rusu
-August 4, 2015 , 1:42 pm
Please look in your browser console. You can manipulate the data as you want after that.
adam
-August 5, 2015 , 8:11 pm
no redirection to URL with a code token parameter from google.
the redirect page only showing the link button “import google contacts” nothing else
adam
-August 5, 2015 , 8:12 pm
can it without https?
adam
-August 5, 2015 , 8:28 pm
http://www.mysite.com/response-callback.php?code=1241254 is not coming
Thomas
-August 7, 2015 , 7:05 pm
I’m trying to understand what the point of “[feed][entry]” is? Also how can I add different parameters such as phone number etc.?
$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’],
);
}
}
Jakob
-August 13, 2015 , 12:34 pm
Thanks for this tutorial, it helped me very much.
But I have two problems with you code. First, is it seperated into more than one file? Currently my redirekt URL is the same as the requesting URL. And the problem is, that after the Session Cookie is set in the if scope with isset($_GET[‘code’]) it is deleted again and after the redirecting the session is gone and no contacts are shown.
Secondly, I have synchronised my Android Phone with my Google Contacts. All Contacts are shown in https://contacts.google.com/ with the correct image. But when I use this script only 140 of ~200 are found and only 10 have an image. But most of them have an image when I take a look on them on my mobile phone and in the desktop app. Maybe you know what the problem could be.
Thanks again for your help,
Jakob
Sadanand
-August 20, 2015 , 1:29 pm
Great man!!! That helps a lot.. Thank you very much…..
satish
-August 20, 2015 , 4:27 pm
Hello,
can we retrieve phoneNumber using oauth using php
vadim
-August 20, 2015 , 5:25 pm
The same: no contacts are displayed. this $_GET[‘code’]) is not working. Can you upload a zip file to download your tutorial?
Simon
-August 27, 2015 , 10:20 pm
Hello Bogdan, i have created the keys on Google API but i have a problem on Step 2. Where do i put the code you posted? I have created a file (invite.php) and put there all the code on STEP 2. I have uploaded it to my server but i get nothing. Locally (wampserver) i get 3 errors.
Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\wamp\www\project\test\import4\invite.php on line 5
Warning: require_once(http://localhost/project/test/import4/google-api-php-client/src/Google/autoload.php): failed to open stream: no suitable wrapper could be found in C:\wamp\www\wall\test\import4\invite.php on line 5
Fatal error: require_once(): Failed opening required ‘http://localhost/project/test/import4/google-api-php-client/src/Google/autoload.php’ (include_path=’.;C:\php\pear’) in C:\wamp\www\wall\test\import4\invite.php on line 5
Obviously it doesnt go to line 5
require_once ‘http://localhost/project/test/import4/google-api-php-client/src/Google/autoload.php’;
What should i do? Thanks in advance
Bogdan Rusu
-September 30, 2015 , 9:34 pm
Please try to include “Google APIs Client Library for PHP” with relative path, not with absolute path.
Ankit
-October 1, 2015 , 8:35 pm
Hi,
use,
C:/wamp/www/project/test/import4/google-api-php-client/src/Google/autoload.php
instead of,
http://localhost/project/test/import4/google-api-php-client/src/Google/autoload.php
I can see some contact details coming through
-September 24, 2015 , 3:52 pm
Contact details are visible when I look using console in firefox, but how can I separate these and echo them with php?
Thanks
Bogdan Rusu
-September 30, 2015 , 9:39 pm
Hello, you can use an ajax request to pass all the data to php.
David Fear
-October 14, 2015 , 3:20 am
I am getting:
“Undefined index: gd$email in /home/******/public_html/******/contacts-api/response-callback.php on line 88”
Haris
-October 16, 2015 , 9:27 am
Thanks for your tutorial. I have a problem with implementing it.
I am getting this error
Parse error: syntax error, unexpected T_FUNCTION, expecting ‘)’ in /home2/mysite/public_html/testing/importcontacts/src/Google/autoload.php on line 19
Can you please guide me with this?
Haris
-October 16, 2015 , 12:25 pm
Okay i got it working to that extent, it redirects me to the google authorization page and the when I am redirected back to my page. it displays this error
The page isn’t redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
when i comment out
header(‘Location: ‘ . $google_redirect_uri);
the error goes away but the contacts array is empty
Virupax
-December 8, 2015 , 8:42 pm
Hello Bogdan, Thanks for this tutorial, It was very useful
Your code worked well for me. I want your code support to add a contact in google contacts which I will be using for my website.
-Thank You
Pawan
-December 10, 2015 , 12:58 pm
I have used java-script code to fetch contacts but it’s showing only limited number(25) of contacts not all Google contacts.
David J Eddy
-December 12, 2015 , 6:20 am
Cleaned this code of the article a bit and abstracted configuration away from the logic (as per the guidelines of 12 factor application). I think this much easier to read and follow, YMMV.
https://gist.github.com/davidjeddy/eb19e79c2de05a0fcea9
Wim
-January 14, 2016 , 5:49 pm
Is there also a way to do the opposite: import contacts from a database into the Gmail contacts?
Kin
-February 9, 2016 , 11:02 am
I am making demo in local so what to enter in application url?
ajay
-February 18, 2016 , 12:39 pm
thax man!!! That helps a lot.. Thank you very much…..
hazarina
-March 2, 2016 , 9:40 am
can show you how to add new contact using js?
aman
-March 3, 2016 , 10:11 pm
Hi Bogdan Rusu,
I used JS code for retrieving contacts. Why it not return the all contacts of the users.
ayaz
-April 1, 2016 , 3:48 pm
Please write a code here for how to update existing user first name
ayaz
-April 2, 2016 , 10:37 am
This tutorial is good and help a lot , please add here code for update google contact via google API in PHP language
Jayesh dhandha
-April 6, 2016 , 3:13 pm
Hi,
I have done as per the given article but i am not getting phone numbers in jason response. I am getting only email ids and not all but some.
What should i do?
And another thing is that why i am getting the window of allowing to import contacts only once.
Below is my code.
TODO supply a title
function auth() {
var config = {
‘client_id’: ‘279327600502-m8dlj34e84fpubtl5bha35rtc8c24p9a.apps.googleusercontent.com’,
‘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) {
document.getElementById(“test”).innerHTML=JSON.stringify(data);
}
});
}
Hello World!
ClickMe
Jose
-April 13, 2016 , 5:36 pm
Hi Bogdan, amazing code! Thank you!!!
I have one problem, I’m only getting 27 contacts, I tried several google accounts and the same happens. Please help!
Thanks
Marco Gasi
-April 23, 2016 , 7:41 pm
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.
Guus
-May 15, 2016 , 9:52 pm
Thanks man, great work!
Just a question; did you figure out how to update contacts? I’m really breaking my head on that…
Guus
-May 15, 2016 , 9:54 pm
BTW I have used your php version as a base for my application…
Erwin
-May 26, 2016 , 9:37 pm
Hi, I have some issue when google redirect…
In my server:
File Not Found
The requested URL /response-callback.php?code=4/wlVM17D…
Why??
pankaj godhani
-June 11, 2016 , 12:38 pm
good,, that’s great work .
Andrey
-June 16, 2016 , 5:21 pm
Hi.
Thank you for you post!
Is it possible to receive phone number from contacts?
Thank you.
Juri
-July 11, 2016 , 2:42 pm
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.
John
-August 25, 2016 , 12:12 am
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?
Akila Prabath
-September 9, 2016 , 8:33 am
Hiiii!!!!!!!!! any solution for creating a new contact and saving it in google contact from server side
Olaiya Segun
-October 8, 2016 , 11:49 am
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%