Saturday, December 11, 2010

Extract contacts from Gmail using google AuthSub

There are alot of apis provided by google in order to extract contacts from your gmail account (and alot of other things as well). But the easiest method to extract gmail contacts i found is using AuthSub.

In order to use AuthSub, it's not mandatory to register your app/website with google, however, if you don't do that, google will show a warning message to the user which doesn't look friendly at all. So, it's better to register your site with google. In order to do so, go to the link https://www.google.com/accounts/ManageDomains. You can add a new domain and also manage the domains you have added previously. Keep in mind that in order to use other APIs of google, you'll need to register your site with google and get app secret and key.In order to understand the working of AuthSub, look at the following image (taken from google).











Now, let's get on with the code. You need to tell Google that what information do you want to extract from user's account. Google calls this "Scope". In order to get the contacts, the scope is; https://www.google.com/m8/feeds/. The scope should be url encoded.When the user has authenticated, Google returns an access token in the url. Hence, in order to check if the user has authenticated or not, simply check if the url contains a parameter "token" and it's not empty. i.e.;

if (isset($_GET['token']) && !empty($_GET['token'])) {
     Authenticated();
else
    notAuthenticated();

If you look at the figure above, you'll see that the first step is to request for an access token, now, on in order to do that, we need to generate a authentication url. That can be done using the following code;

function notAuthenticated(){
   $returnURL = "http://www.example.com/getGmailContacts.php";
   $GoogleScope =  "https://www.google.com/m8/feeds/";
   $link = 'https://www.google.com/accounts/AuthSubRequest?scope='.$GoogleScope;
   $link .= '&session=1&secure=0&next='.urlencode($returnURL);
   echo "<a href='$link'>Click here to authenticate request</a>";
}

In the above code, the description of parameters are,
session: (optional) Boolean flag indicating whether the one-time-use token may be exchanged for a session token (1) or not (0)
secure: (optional) Boolean flag indicating whether the authorization transaction should issue a secure token (1) or a non-secure token (0). Secure tokens are available to registered applications only.
next: (required) URL the user should be redirected to after a successful login. This value should be a page on the web application site, and can include query parameters

there are some other parameters as well, the details can be seen at: http://code.google.com/apis/accounts/docs/AuthSub.html#AuthSubRequest

Now, the user will be asked to login to his account and then he will be shown a page whether the user allows the request. Once the user has approved the request, the user will be taken back to the "return url" with "token" parameter in the url parameters.

We have covered the first 4 points shown in the figure shown above. Let's see the code for the rest of 2 points.

function Authenticated(){
       $token = $_GET['token'];
       $Contacts = array ();
       $GMailAuthSubUrl = "https://www.google.com/accounts/AuthSubSessionToken";
       $GMailContactsUrl = "https://www.google.com/m8/feeds/contacts/default/full?max-results=1000";


In the above code, now we are making request to get the session token. The "max-results" parameter in the GmailContactsUrl tells how many contacts do you want to retrieve. Like Yahoo API, give a very big number here to get all your contacts using one call. Now, let's make the call using curl

       $headers = array('Authorization: AuthSub token='.$token,
                         'Content-Type: application/x-www-form-urlencoded');
               
       $cURLHandle = curl_init();
       curl_setopt($cURLHandle, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($cURLHandle, CURLOPT_TIMEOUT, 60);
       curl_setopt($cURLHandle, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($cURLHandle, CURLOPT_URL, $GMailAuthSubUrl);
       curl_setopt($cURLHandle, CURLOPT_HTTPHEADER, $headers);
       $response = curl_exec($cURLHandle);


after making the above call, we will get the session token in the response. We will use this session token to get the contacts of the user now.
           
           $newToken = substr($response, 6);
     $headers = array('Authorization: AuthSub token='.$newToken,
                       'Accept-Charset: utf-8, iso-8859-2, iso-8859-1',
                       'Content-Type: application/x-www-form-urlencoded');  

     $cURLHandle = curl_init();
     curl_setopt($cURLHandle, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($cURLHandle, CURLOPT_TIMEOUT, 60);
     curl_setopt($cURLHandle, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($cURLHandle, CURLOPT_URL, $GMailContactsUrl);
     curl_setopt($cURLHandle, CURLOPT_HTTPHEADER, $headers);
     $response = curl_exec($cURLHandle);
     curl_close($cURLHandle);

       

As you can see, in the above curl call, we have now called the gmail contact url with the session token. Now, let's get the contacts from the response.

     $namespaceChanged = str_replace("gd:email", "gdemail", $response);
     $retrievedContacts = new SimpleXMLElement($namespaceChanged);
            

     echo "<ul>";
     if (!empty($retrievedContacts->entry)) {
        foreach ($retrievedContacts->entry as $contact) {
           $email = strip_tags($contact->gdemail['address']);
           $name = strip_tags($contact->title);
           echo "<li>".($name!=""?$name:$email)." ( ".$email." ) </li>";
        }
    }
    echo "</li>";
}

I hope this post was useful.

3 comments:

  1. eeemail.net allows to extract all email addreses from any web mail : gmail, yahoo, etc . not only contacts

    ReplyDelete