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.

Import Google contacts with PHP or Javascript using Google Contacts API and OAUTH 2.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

Google Console, create project

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

Google Console APIs

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

Enable Contacts API Google developers

  • 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

Configure Consent screen

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

Create Client ID Google API

  • 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
    • 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 . 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

Google API Client ID, 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.

  • 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

  • setup new google client

  • create a curl function

  • Google will redirect back to our URL with a code token parameter, for example:
  • For better UX, we can store the received code into a session, and redirect back to this url

  • Check if we have session with our token code and retrieve all contacts, by sending an authorized GET request to the following URL :
  • 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

  • create the link that the user will click to import his contacts

  • when the user will click on that link he will be asked to allow permissions for your application

Google API request permission

  • 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:


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.

  • authorize access and fetch contacts

  •  Make a button to fire the event


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.



-June 22, 2015 , 10:54 am

How can i import image of users?

    -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.


-June 27, 2015 , 5:31 pm

I had went through your code and tried it. But got below error. can you please advise.

Not Found
The requested URL /” was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    -June 30, 2015 , 1:59 pm

    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.


-July 1, 2015 , 10:22 am


i also get an 404 error. The Link looks very strange:
But the link in Firebug starts correct with:

For over an hour I doubted myself but i found the bug.
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.



-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

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

    -August 4, 2015 , 12:04 pm

    Hello, please look into your console ( chrome or firefox) so you can see the results.

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.

    -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;

Done! Modify the code to see the contact list :D!


-July 28, 2015 , 4:24 pm

HI, I everything is working fine except fetching contact’s photo. It is returning 401 error.


-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”

    -August 4, 2015 , 1:42 pm

    Please look in your browser console. You can manipulate the data as you want after that.


      -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


        -August 5, 2015 , 8:12 pm

        can it without https?


-August 5, 2015 , 8:28 pm is not coming


-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’],


-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 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,


-August 20, 2015 , 1:29 pm

Great man!!! That helps a lot.. Thank you very much…..


-August 20, 2015 , 4:27 pm

can we retrieve phoneNumber using oauth using php


-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?


-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

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?


    -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”


-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?


    -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


-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


-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.


-January 14, 2016 , 5:49 pm

Is there also a way to do the opposite: import contacts from a database into the Gmail contacts?


-February 9, 2016 , 11:02 am

I am making demo in local so what to enter in application url?


-February 18, 2016 , 12:39 pm

thax man!!! That helps a lot.. Thank you very much…..


-March 2, 2016 , 9:40 am

can show you how to add new contact using js?


-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.


-April 1, 2016 , 3:48 pm

Please write a code here for how to update existing user first name


-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


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’: ‘’,
‘scope’: ‘’
gapi.auth.authorize(config, function() {


function fetch(token) {
url: “” + token.access_token + “&alt=json”,
dataType: “jsonp”,
success:function(data) {

Hello World!


-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!


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;
type: 'get',
url: profileImageUrl,
success: function(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 + ‘)‘;
if (html !== ”){
But this gives as result a Bar request response and Cross origin request blocked message in the console. Any idea?
Thank you again.


-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…


-May 15, 2016 , 9:54 pm

BTW I have used your php version as a base for my application…


-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…

pankaj godhani

-June 11, 2016 , 12:38 pm

good,, that’s great work .


-June 16, 2016 , 5:21 pm

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

Thank you.


-July 11, 2016 , 2:42 pm

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

Please, add:


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.


-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%

Leave a Reply to Sadanand

Your email address will not be published. Required fields are marked *

  • All fields marked with * are mandatory

Cancel Reply