Sunday, April 11, 2010

Simple PHP Facebook API

Facebook is by far the most popular social networking site on the web. If you are a web application developer, chances are you have tried to use the Facebook API at least once. While the Facebook developer platform offers Facebook Connect and Client Libraries for various languages, including PHP, Javascript, ASP.NET, and Actionscript, these libraries are, in my opinion, rather hefty.

In one of my recent projects, I wanted to allow my client and server code to interface with Facebook "directly". Of course, one should avoid hardcoding the Facebook App API Key into the client code, and one should NEVER transmit the Facebook App Secret to the client side at all. Therefore, any client calls to the Facebook API should be passed through a server.


Anyway, here is the minimalistic PHP code for interfacing with Facebook.

$fb_appapikey = 'APPAPIKEY';
$fb_appsecret = 'APPSECRET';

function post_request($param, $secret='') {
 global $fb_appapikey; 
 $param['api_key'] = $fb_appapikey;
 $param['call_id'] = microtime(true);
 $param['v'] = '1.0';
 $postparam = array();
 foreach ($param as $key => &$val) $postparam[] = $key.'='.urlencode(is_array($val) ? implode(',', $val) : $val);
 $postparam[] = 'sig='.generate_sig($param, $secret);
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, 'http://api.facebook.com/restserver.php');
 curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $postparam));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_USERAGENT, 'Facebook API PHP5 Client 1.1 (curl) ' . phpversion());
 $result = curl_exec($ch);
 curl_close($ch);
 return $result;
}

function generate_sig($param, $secret='') {
 global $fb_appsecret; 
 $sig = '';
 ksort($param);
 foreach ($param as $key => &$val) $sig .= "$key=$val";
 $sig .= $secret ? $secret : $fb_appsecret;
 return md5($sig);
}


To post a request to Facebook, one can simply passed the API method name and the associated parameters to the post_request function. If you are developing a desktop facebook app, you should pass the Session Secret to the function; otherwise, leave the field empty to use your App Secret instead. The full API documentation can be found here.

// Get the list of friends associated with the active user
post_request(array('method'=>'friends.get','format'=>'JSON','session_key'=>$session), $secret)
// Get the basic profile information of the active user
post_request(array('method'=>'users.getInfo','format'=>'JSON',
'session_key'=>$session,'uids'=>array($uid),'fields'=>array(
'uid','about_me','activities','affiliations',
'birthday_date','books','current_location',
'education_history','first_name','hometown_location',
'hs_info','interests','last_name','locale',
'meeting_for','meeting_sex','movies','music',
'name','notes_count','pic','pic_big','pic_small',
'pic_square','political','profile_blurb',
'profile_update_time','profile_url','proxied_email',
'quotes','relationship_status','religion','sex',
'significant_other_id','status','timezone','tv',
'username','wall_count','website','work_history'
)), $secret)

In order to allow my client code to interface with Facebook directly, I have also written a simple gateway. For the sake of simplicity, I have omitted the necessary code to verify the client's identity and security credential. You should implement your own security mechanism to prevent malicious attackers from using your Facebook App API Key to carry out attacks.

$gw_uid = preg_replace("/[^0-9]/", '', $_POST['uid']);
$gw_action =  preg_replace("/[^a-zA-Z]/", '', $_POST['action']);
$gw_param =  json_decode(stripslashes($_POST['param']), true);

// On should always verify the client's credential before posting the request to Facebook

switch ($gw_action) {
 case 'facebookapi':
  echo post_request($gw_param);
  break;
 case 'otheractions':
  echo otherfunctions();
  break;
}

Hope this helps.

No comments:

Post a Comment