Google API – Get contact list

Google API – Get contact list

67 907
Google API - Get contact list
Google API - Get contact list

Google API – Get contact list

In our new tutorial I am going to tell you about inviting friends. I think that this is the most important part for every website, a key to success. Today I will show you how to create simple and effective Gmail contact importer using OAuth authorization and API. Also, I will tell about obtaining Google API access too.

As the first step – lets prepare our own project in Google API console, please open this link and create your project. Then we need goto ‘API Access’ section and click ‘Create an OAuth 2.0 client ID’ button. Now we should fill a name for our new project:

Google Contacts API - step 1

Click next, and, at the second step we should set URL of our destination page:

Google Contacts API - step 2

Finally, we’ve got our Client ID and secret (or – consumer key and secret):

Google Contacts API - step 3

Now – download the source files and lets start coding !


Live Demo

Step 1. PHP

Now, please create empty index.php file and put next code:

index.php

<?php

// disable warnings
if (version_compare(phpversion(), "5.3.0", ">=")  == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE); 

$sClientId = 'YOUR_GOOGLE_CLIENT_ID';
$sClientSecret = 'YOUR_GOOGLE_CLIENT_SECRET';
$sCallback = 'http://script-tutorials.com/demos/291/index.php'; // callback url, don't forget to change it to your!
$iMaxResults = 20; // max results
$sStep = 'auth'; // current step

// include GmailOath library  https://code.google.com/p/rspsms/source/browse/trunk/system/plugins/GmailContacts/GmailOath.php?r=11
include_once('classes/GmailOath.php');

session_start();

// prepare new instances of GmailOath  and GmailGetContacts
$oAuth = new GmailOath($sClientId, $sClientSecret, $argarray, false, $sCallback);
$oGetContacts = new GmailGetContacts();

if ($_GET && $_GET['oauth_token']) {

    $sStep = 'fetch_contacts'; // fetch contacts step

    // decode request token and secret
    $sDecodedToken = $oAuth->rfc3986_decode($_GET['oauth_token']);
    $sDecodedTokenSecret = $oAuth->rfc3986_decode($_SESSION['oauth_token_secret']);

    // get 'oauth_verifier'
    $oAuthVerifier = $oAuth->rfc3986_decode($_GET['oauth_verifier']);

    // prepare access token, decode it, and obtain contact list
    $oAccessToken = $oGetContacts->get_access_token($oAuth, $sDecodedToken, $sDecodedTokenSecret, $oAuthVerifier, false, true, true);
    $sAccessToken = $oAuth->rfc3986_decode($oAccessToken['oauth_token']);
    $sAccessTokenSecret = $oAuth->rfc3986_decode($oAccessToken['oauth_token_secret']);
    $aContacts = $oGetContacts->GetContacts($oAuth, $sAccessToken, $sAccessTokenSecret, false, true, $iMaxResults);

    // turn array with contacts into html string
    $sContacts = $sContactName = '';
    foreach($aContacts as $k => $aInfo) {
        $sContactName = end($aInfo['title']);
        $aLast = end($aContacts[$k]);
        foreach($aLast as $aEmail) {
            $sContacts .= '<p>' . $sContactName . '(' . $aEmail['address'] . ')</p>';
        }
    }
} else {
    // prepare access token and set it into session
    $oRequestToken = $oGetContacts->get_request_token($oAuth, false, true, true);
    $_SESSION['oauth_token'] = $oRequestToken['oauth_token'];
    $_SESSION['oauth_token_secret'] = $oRequestToken['oauth_token_secret'];
}

?>
<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>Google API - Get contact list | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <header>
            <h2>Google API - Get contact list</h2>
            <a href="http://script-tutorials.com/google-api-get-contact-list/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </header>
        <img src="oauthLogo.png" class="google" alt="google" />

    <?php if ($sStep == 'auth'): ?>
        <center>
        <h1>Step 1. OAuth</h1>
        <h2>Please click <a href="https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=<?php echo $oAuth->rfc3986_decode($oRequestToken['oauth_token']) ?>">this link</a> in order to get access token to receive contacts</h2>
        </center>
    <?php elseif ($sStep == 'fetch_contacts'): ?>
        <center>
        <h1>Step 2. Results</h1>
        <br />
        <?= $sContacts ?>
        </center>
    <?php endif ?>

</body>
</html>

As you can see – in the beginning we include ‘GmailOath.php’ library. This library you can download here. Once you have downloaded it – pay attention to the code. As you can see – the main functionality is separated into 2 sections: authorization and fetching of contact list. As usual – I put my comments in this code to better understanding.

When we click authorization button, it will open google authorization page, where we should grant access for our application to get our contact list:

Google Contacts API - step 4


Live Demo

Conclusion

If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!


67 COMMENTS

    • Are you sure? Is it for your local tests? Or our demo doesn’t work? I’ve just tested our demo – it works fine for me.

  1. Is it for your local tests?
    Yes!
    Did everything as it is written in the example. The result of the:Invalid Token.

  2. But have you applied your own google’s api keys?
    Replaced here:
    11 $sCallback = ‘http://script-tutorials.com/demos/291/index.php’; // callback url, don’t forget to change it to your!

    • 2 Viktor,
      Yes, I know, you should to apply your own API keys + change callback URL as well.
      Only in this case the script will work for you.

  3. I try to use your example but it does not work properly.
    I don’t know what is problem.
    There is no single error and I already checked all thing what you mentioned in this page.

    symptom
    - Actually, it works. But if I click and move to confirm page, and press confirm button then there are no result( just show blank page).

    Could you tell me how to solve this problem?

    • Hi Isac,
      Please recheck both: redirect url (in API settings) and callback url in index.php. Both should point to the same file.

    • Hello Govind,
      curl_init is ordinary function: http://php.net/manual/en/function.curl-init.php
      make sure that ‘curl’ is installed on your server (this is PHP extension)

  4. Warning: session_start() [function.session-start]: open(/home/users/web/b502/nf.webinfomart/public_html/cgi-bin/tmp/sess_c797f142bb6a5491e819ce60e912c084, O_RDWR) failed: No such file or directory (2) in /hermes/bosweb25a/b502/nf.webinfomart/public_html/webinfomart/getcontact/sources291/index.php on line 19

    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /hermes/bosweb25a/b502/nf.webinfomart/public_html/webinfomart/getcontact/sources291/index.php:19) in /hermes/bosweb25a/b502/nf.webinfomart/public_html/webinfomart/getcontact/sources291/index.php on line 19

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /hermes/bosweb25a/b502/nf.webinfomart/public_html/webinfomart/getcontact/sources291/index.php:19) in /hermes/bosweb25a/b502/nf.webinfomart/public_html/webinfomart/getcontact/sources291/index.php on line 19

    I am getting this error, plz help me out ..

    • Hi Kamal,
      Please refer this thread: http://stackoverflow.com/questions/11374110/session-start-errors-on-godaddy-server
      this is related with your problem

  5. dear
    i am using the imports facebook contacts. everything is working fine but i need the email address instead of name and images how i will get the email address of the users using the same script
    best regards
    amir rehman

  6. Great !!! tutorial. Keep up the good job.
    I am able to get contacts list from both facebook and google.

    One question I have, why are we referring these folders “facebook-api-get-friends-list” and “google-api-get-contact-list” in php.
    Is the intent to store the received contacts here?

    • Hello prasad,
      ‘facebook-api-get-friends-list’ and ‘google-api-get-contact-list’ are not folders, they are addresses of our tutorials

  7. Good article like it.
    I was using this same code and it was working fine. But recently I changed my hosting server from US to UK and it is not working for same domain.
    Not giving user the access token
    Please help ASAP

    • Hello Rahul, I think that you need to update your details of your google application, or even to create a new one to obtain fresh API details.

  8. Great post and I was able to get everything to work! I looked online for like 3 days to find something this simple and complete, so basically thanks for posting this!

    I do have a question though, can I access other parts of the contact response? I see the foreach statement on the index.php where you load the $sContacts variable. My main issue is, where are the two arrays, ($aEmail and $aInfo) coming from? I traced it back to the GmailOath.php GetContacts() function, but then I lose it. That function only returns one array, $retarr, so where is the other array? Ideally, I would like to grab the image associated with the account (if it exists, otherwise some sort of default image).

    Thanks in Advance!!

    Pete

    • Hi Pete,
      Yes, everything comes from GmailOath.php, and, it contains some extra info (not only emails and names). I can recommend, that you debug all the fields which return in this array. For example, you can use print_r function to print an array.

  9. Great Tutorial….

    Getting the following error while fetching the contacts

    Warning: Invalid argument supplied for foreach() in line “foreach($aContacts as $k => $aInfo) {“

    • Hi Chandan,
      It may be in case if the $aContacts is empty, to protect the code you can add the following code before this line:
      if (is_array($aContacts) && count($aContacts))

  10. HI ADMIN.
    Thanks for the tutorial. I am creating a social web application and I want to register / sign in users. Upon signing them up I want to send an invitation email to their contact list. This should happen in background. How can I integrate this get contact api with the google sign up

    • Hello George,
      It can not be done in background (invisibly), because in order to fetch your contact list, you need to pass the authorization step

  11. Your Tutorial is Great!
    The only thing i need to ask you is how should i retrieve other details, i want to display phone number of all contacts besides email address. So can u help me out with that?

    • Hi Pratik,
      Bu default, GmailGetContacts::GetContacts returns array of the following: id, updated, category, title, link, gd:email

  12. I have used the code you have shown in your tutorial for my app, ( the above website url ) and I need to display the phone number along with name and email id.
    Can you show me how ?

  13. Hi Andrew, nice tutorial!

    Just to help: I can note most people just have some difficulties to understand the OAuth2 flow.

    I nice article about it is this one: http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified

    It helped me a lot to better understand OAuth2.

    I think if someone with difficult first understand this flow, then can enjoy better your nice article.

  14. Many thanks for the tutorial.
    By the way, do you know why some of the imported contacts wont show the email addresses on the contact?

  15. Just wanted to say wonderful tutorial and I am learning alot for being new to this, but I have a question. How would you organize this in a table, if you could point me in the right direction I would be greatly appreciative.

  16. I have another question, how would one go about trying to pull each individual name for the list of contacts in an array I am trying standard array code such as

    $person = array(‘Name’ => $sContacts);
    $i = 0;
    foreach ($person as $key => $value) {
    echo “\$person[$i]=> $value.\n;
    }
    but all I get is the full list of names and would like to get the first name in the array.

    • Hello again,
      Try to echo (print_r) the $aContacts array. It should contains much more useful information (and maybe even first names).

  17. I downloaded your package and altered it to my client id and secret key. But when I run the index.php file nothing happens only a blank page is displayed. ?!

    • I suppose that you should investigate your possible errors, search for ‘error_log’ file at your host.

  18. Nice tutorial and i have one question, I am new to this but I was wondering if you could show me how to filter the contacts with a simple search. I have searched all over the net with no success.

    • Hi Allen,
      How exactly yo filter contacts? By name/email? Basically, if you don’t want to implement it by yourself, you can search for ready plugins (e.g. jQuery plugins) to filter lists.

  19. Great tut!!

    Is it possible to have the login process in a popup window, so that the background remains the same until login process is complete?
    Would be great!

  20. Hello,
    Yes, this is possible to open the OAuth process in popup, however you will need to add a Callback to put the results back to your main window.

  21. Script works great & I’m having pretty decent result out of it, however one thing that bothers me is when user is asked to grant permission, the screen that shows is pretty unusual. It prints first of all customer key instead of project name, plus it doesn’t show my company’s logo. Basically it’s not showing what I’v setup in Google.
    Any idea how to get back to the original one using the same script?

    • Hi Shanil,
      This is how the google API work. Before you get access to use some internal services – you need to grant your permission to use it.

  22. hi.. nice script………. (and it works!)

    2 questions:

    1) Can I get more information about the contacts other than Full name and EMAIL address?

    2) How can I add to the script a function that will tell me the Name and EMail of the person
    running the script?

    Thank you very much.

    • Hi Rotem,
      Yes, Google returns different information about your contacts (just try to print everything from $aContacts).

  23. can you also share how to get other contact info. like name,picture,gender,birthdate? Code snippet would be great.

  24. Hi Admin
    i followed the steps given by you it ws showing
    Warning: Invalid argument supplied for foreach() in line 43 i added a line before it as follows
    if (is_array($aContacts) && count($aContacts))
    after adding this line it was showing a blank page please solve this issue.

    • Hi Charan,
      Does your code looks like:
      if (is_array($aContacts) && count($aContacts)) {
      foreach($aContacts as $k => $aInfo) {

      ?

Leave a Reply