Querying Google Contacts API via PHP
For the last few days I have been going through Google API documentations for one of the projects I have been working on to get Google Contact details of a Google user. To the developer’s luck, the documentation about Google API is very well prepared but due to the fact that authentication with oAuth is a painful process, things get scary while accessing Google API. (Even requesting access is a nightmare
I have handled the authentication by Zend Framework oAuth component which made things pretty easy. But it took me almost 2 days to figure out how to fetch contact details of the user via Google Contacts API with the access token that I receive. oAuth playground is a nice utility to compare the values you create and should be created. It was the time that I realized that access token was url encoded twice while generating base string. I do not know why, but you can check the playground and the slash character is encoded two times. First encoding translates / to %2F, and second one translates %2F to %252F.
Anyway, here is a sample code in PHP to make things easier for anyone interested. Good luck!
$timestamp = time(); $contactsURL = "https://www.google.com/m8/feeds/contacts/default/full/"; $oauth_nonce = md5(uniqid(rand(), true)); $sign_method = 'HMAC-SHA1'; $oauth_version = '1.0'; $oauth_consumer_key = 'aaaaaaaaaaa'; // the key you receive from Google $oauth_consumer_secret = 'bbbbbbbbbbbb'; // the secret you receive from Google $oauth_token = 'cccccccccccccccc'; // the token you receive at the end of authentication $oauth_token_secret = 'ddddddddddddd'; // the token secret you receive at the end of authentication // be careful that access token is urlencoded here, // and going to be urlencoded once more while creating base_string $baseParams = array("oauth_consumer_key" => $oauth_consumer_key, "oauth_nonce" => $oauth_nonce, "oauth_signature_method" => $sign_method, "oauth_timestamp" => $timestamp, "oauth_token" => urlencode($oauth_token), "oauth_version" => $oauth_version ); $baseArr = array(); foreach ($baseParams as $key => $value) $baseArr[] = $key . "=" . $value; $base_string = "GET&".urlencode($contactsURL)."&".urlencode(implode("&", $baseArr)); $key = urlencode($oauth_consumer_secret) . '&' . urlencode($oauth_token_secret); $sig = base64_encode(hash_hmac('sha1', $base_string, $key, true)); $queryParams = array("oauth_version" => $oauth_version, "oauth_nonce" => $oauth_nonce, "oauth_timestamp" => $timestamp, "oauth_consumer_key" => $oauth_consumer_key, "oauth_token" => $oauth_token, "oauth_signature_method" => $sign_method, "oauth_signature" =>$sig ); // http_build_query url encodes every parameter and creates well-formed query string $queryURL = $contactsURL."?".http_build_query($queryParams); echo file_get_contents($queryURL);















