Import contacts using Google’s API

Maybe the most important thing about this post is how to use HTTP based APIs in a simple way -using a wrapper for cURL PHP extension. Most of the examples available on the Web are kind of out-of-date, based on the idea that there is no a better abstraction layer.

Requirements / Example environment configuration.

This example was originally built for CakePHP, but as you can see, it can be used or migrated to several frameworks – the key is to use the PEAR component. Note: I believe that this example will make most of the example out there crappy – and I hope it, so other developers could use it.

 
// PEAR Package HTTP_Request2
// http://pear.php.net/manual/en/package.http.http-request2.php
require_once('HTTP' . DS . 'Request2.php');
 
class GoogleImportComponent extends Object {
 
	private $username = null;
	private $password = null;
	private $token = null;
 
	/**
	 * Authenticate user credential against provider services
	 *
	 * @param string $username User's login
	 * @param string $password User's account password
	 * @see http://code.google.com/apis/contacts/docs/3.0/developers_guide_protocol.html
	 */
	function authenticate($username, $password) {
		$this->username = $username;
		$this->password = $password;
 
		$hrc = new HTTP_Request2('https://www.google.com/accounts/ClientLogin', HTTP_Request2::METHOD_POST);
		$hrc->setAdapter('HTTP_Request2_Adapter_Curl');
		$hrc->setConfig('ssl_verify_peer', false);
		$hrc->addPostParameter('accountType', 'HOSTED_OR_GOOGLE');
		$hrc->addPostParameter('service', 'cp');
		$hrc->addPostParameter('source', 'MY_APP_ID');
		$hrc->addPostParameter('Email', $this->username);
		$hrc->addPostParameter('Passwd', $this->password);
 
		$response = $hrc->send();
		$body = $response->getBody();
		if ($response->getStatus() == 200) {
			$this->token = substr($body, strpos($body, 'Auth=') + 5);
		}
		else {
			throw new Exception($response->getReasonPhrase(), $response->getStatus());
		}
	}
 
	/**
	 * Return the contacts' email list
	 *
	 * @return array
	 * @see http://code.google.com/apis/contacts/docs/3.0/developers_guide_protocol.html
	 */
	function get() {
		$addresses = array();
 
		$hrc = new HTTP_Request2("http://www.google.com/m8/feeds/contacts/{$this->username}/full", HTTP_Request2::METHOD_GET);
		$hrc->setHeader('Authorization', "GoogleLogin auth={$this->token}");
		$response = $hrc->send();
		if ($response->getStatus() == 200) {
			$xml = simplexml_load_string(utf8_encode($response->getBody()));
			$xmladd =  $xml->xpath("//gd:email/@address");
			foreach ($xmladd as $value) {
				$data = get_object_vars($value);
				$addrs = $data['@attributes']['address'];
				if ($addrs != $this->username) {
					$addresses[] = $addrs;
				}
			}
		}
		else {
			throw new Exception($response->getReasonPhrase(), $response->getStatus());
		}
 
		return $addresses;
	}
}

That’s it. It is not a huge amount of code with HTTP protocol related instructions – like the ones you can get for free. It relies on HTTP_Request2 PEAR module, that even if it’s on beta, works like a charm.

Esta entrada fue publicada en SW Development y etiquetada , , , , . Guarda el enlace permanente.

Una respuesta a Import contacts using Google’s API

  1. Pingback: Brendan » Blog Archive » Interesting things I’ve looked at for March 7th through March 9th

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>