Importing Contacts from Google Mail using OAuth

This is my second post in the fetch contacts from email account series. In this post, we are going to fetch contacts from a Google account. This isn’t a detailed tutorial, but a quick 2 minute how-to.

$this->config->item(‘google_return_url’) is the url of the page to which user is returned after a login attempt.

1. Add the following code where the user has to select Google Mail to import contacts.

<a href="<?php echo $this->config->item('google_return_url').'?data=abc'; ?>&scope=">Fetch Google Contacts</a>

2. Include these 2 functions in your PHP code.
function make_api_call($url, $token)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
    $output = curl_exec($ch);
    return $output;
function get_session_token($onetimetoken)
    $output = make_api_call("", $onetimetoken);
    if (preg_match("/Token=(.*)/", $output, $matches))
        $sessiontoken = $matches[1];
    } else {
        echo "Error authenticating with Google.";
    return $sessiontoken;

3. Add the following code to the return url file.

$sessiontoken = get_session_token($_GET['token']);
$contacts = make_api_call("", $sessiontoken);
$contacts = json_decode($contacts, TRUE);
foreach ($contacts['feed']['entry'] as $contact)
    $emails[] = $contact['gd$email'][0]['address'];
//$emails array has the email addresses of all the contacts.

4. That’s it folks. It is that simple.

Further reading :


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.