獲取郵箱地址薄的PHP API

 

Rapleaf Address Book API Kit - PHP

By Mimi Sun

This helper kit allows you to use the Rapleaf Address Book API through direct PHP function calls. It fetches the XML response from the Rapleaf server and returns a corresponding PHP object.

Contents

  • rapleaf_abook.php - the library file that you need to put on your server and include.
  • sample.php - a sample application to help get you started. It simply displays your contact list.

Usage

Step 1: Include the library

	require_once 'rapleaf_abook.php';

Step 2: Initialize an address book object. You can find your API key here.

	$abook = new RapleafAbook($api_key);

Step 3: Query the API for the contact list. You need to get the user's email address and password through a form; see sample.php for an example.

	$result = $abook->getData($email, $password);

The returned result has the following structure:

	$result = (
		'status'   => '200',  # HTTP status code returned by the server
		'error'    => '',     # error message if there are any
		'contacts' => (       # contact list
		               ([name]=>'dummy',  [email]=>'[email protected]'), 
		               ([name]=>'dummy2', [email]=>'[email protected]'),
		               ...
		              )
	);
 

You should check the status before attempting to process the contact list. The following example lists the contacts on success, prints the error message otherwise.

	$html = '';
	if ($result['status']=='200') { # OK
		$contacts = $result['contacts'];
		foreach ($contacts as $contact) {
			$html.= htmlentities($contact['name'].' <'.$contact['email'].'>');
			$html.='<br />';
		}
	} else {
		$html = $result['status'].': '.$result['error'];
	}
	
	echo $html;
 

Demo

Download

附代碼如下:

rapleaf_abook.php

<?php
/*
 * Helper class for the Rapleaf Address Book API
 *   (http://www.rapleaf.com/apidoc/v2/abook)
 * Gets the XML response from the Rapleaf server and parses it into a PHP object.
 *
 * Usage:
 *  1. $abook = new RapleafAbook(api_key[,url]) to initialize
 *  2. $result = $abook->getData(email, password) to query the API for a contact list
 *  See the function definitions for details.
 * 
 * 03/01/2008
 *
 */
 
class RapleafAbook {
 var $url;
 var $api_key;
 var $status;

 function RapleafAbook($api_key, $url = 'http://api.rapleaf.com/v2/abook') {
  $this->api_key = $api_key;
  $this->url = $url;
  $this->status = '';
  $this->curl_info = '';
 }

 function getData($email, $pass) {
  # assemble post_data string
  $post_data = "login=$email&password=$pass";
  $response = $this->sendPostRequest($this->url, $post_data);
   
  # the return structure
  $result = array(
   'status'   => '',  # HTTP status code returned by the server
   'error'    => '',  # error message if there are any
   'contacts' => array(),  # contact list if request succeeded
  );
  
  $result['status'] = $this->status;
  if ($this->status == '200') { #OK
   $result['contacts'] = $this->xmlToObj($response);
  } elseif ($this->status == '400') {
   $result['error'] = 'The request did not contain all required parameters: '.$response;
  } elseif ($this->status == '401') {
   $result['error'] = 'API key was not provided or is invalid.';
  } elseif ($this->status == '420') {
   $result['error'] = 'Login failed.';
  } elseif ($this->status == '500') {
   $result['error'] = 'There was an unexpected error on our server. This should be very rare and if you see it please contact [email protected].';
  } elseif ($this->status == '520') {
   $result['error'] = 'There was an error while reading the contacts from the address book.';
  } else {
   $result['error'] = $this->error;
  }
  return $result;
 }

 # Parse the xml response text into an associative array
 function xmlToObj($str) {
  $xml = simplexml_load_string($str);
  $result = array();
  foreach ($xml->contact as $contact) {
   $result[] = array('name' => (string) $contact['name'], 'email' => (string) $contact['email']);
  }
  return $result;
 }
 
 # Returns the xml response on success, sets the error message on failure
 function sendPostRequest($url, $post_data) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  curl_setopt($ch, CURLOPT_HTTPHEADER,
   array("Authorization: ".$this->api_key, "Content-Type: application/x-www-form-urlencoded")
  );
  
  $data = curl_exec($ch);
  $this->status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $this->error = curl_error($ch);
  $this->curl_info = curl_getinfo($ch);
  curl_close($ch);
  return $data;
 }
}
?>
sample.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rapleaf Address Book API Sample - PHP</title>
<body style="padding-left:50px;padding-right:50px;background-color:#ddeedd;">
<h1>Rapleaf Address Book API Sample</h1>

<form action="sample.php" method="post">
 <table>
 <tr><td>Email: </td><td><input type="text" name="email" size="40"/></td></tr>
 <tr><td>Password: </td><td> <input type="password" name="pass" size="40"/></td></tr>
 <tr><td><a href="http://www.rapleaf.com/developer/api_key">API Key:</a> </td><td><input type="text" name="api_key" size="40" /></td></tr> 
 </table>
 <input type="submit" value="Import Contacts" />
</form>
<hr />

<?php
require_once 'rapleaf_abook.php';

if (sizeof($_POST) > 1) {
 $abook = new RapleafAbook($_POST['api_key']);
 $result = $abook->getData(urlencode($_POST['email']), $_POST['pass']);
 $html = '';
 if ($result['status']=='200') { # OK
  $contacts = $result['contacts'];
  $html = '<h2>My Contacts ('.sizeof($contacts).')</h2>';
  foreach ($contacts as $contact) {
   $html.= '<input type="checkbox" checked>'.htmlentities($contact['name'].' <'.$contact['email'].'>');
   $html.='<br />';
  }
  $html.='<input type="submit" value="Continue" />';
 } else {
  $html = $result['status'].': '.$result['error'];
 }
 
 echo $html;
 echo "<br /><br />Connection time: ".$abook->curl_info['connect_time'].'<br />'.
 "Total time: ".$abook->curl_info['total_time'].'<br />';
}

?>

</body>
</html>

<!--
-->
發佈了16 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章