I see, learn and rediscover… everyday!
 
Importing Contacts from Google Mail using OAuth

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="https://www.google.com/accounts/AuthSubRequest?next=<?php echo $this->config->item('google_return_url').'?data=abc'; ?>&scope=http://www.google.com/m8/feeds/contacts/default/thin&secure=0&session=1">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);
    curl_close($ch);
    return $output;
}
 
function get_session_token($onetimetoken)
{
    $output = make_api_call("https://www.google.com/accounts/AuthSubSessionToken", $onetimetoken);
    if (preg_match("/Token=(.*)/", $output, $matches))
    {
        $sessiontoken = $matches[1];
    } else {
        echo "Error authenticating with Google.";
        exit;
    }
    return $sessiontoken;
}

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

$sessiontoken = get_session_token($_GET['token']);
$contacts = make_api_call("http://www.google.com/m8/feeds/contacts/default/thin?alt=json&max-results=1000", $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 :
1. http://code.google.com/apis/contacts/
2. http://code.google.com/apis/contacts/docs/3.0/reference.html

3 Comments

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.