#native_company# #native_desc#

Create Advanced Facebook Apps with Facebook JavaScript Page 2

By Sachin Khosla
on May 6, 2010

Behind the Scenes of the FBJS Application

Now, what happens behind the scenes in our PHP file is interesting. Our PHP script should be able to recognize legit requests and reject any invalid or fake requests made to the script. Notice that Facebook always sends some session data with every GET or POST request. So, to see if the request is valid, we write the login on top of our PHP file. These values are prefixed with fb_sig_.
Among these values, we will get one “Signature Value” $_POST['fb_sig'], which we should verify at our end to check the authenticity of the request made. To verify the signature, you need to follow the following steps.
  1. Remove the fb_sig_ prefix from all of the keys.
  2. Sort the array alphabetically by key.
  3. Concatenate all key/value pairs together in the format “k=v” (omitting the signature itself, because that is what we are calculating).
  4. Append your secret key, which you can find by going to the Facebook developers page and following the link for your application.
  5. Take the md5 hash of the whole string.
In the following code snippet (store it in submit.php for this example), this Facebook signature is verified. On verification, we send the contact information filled out by the user to the administrator’s email address. If it fails, we display an error message. Visit Facebook’s WiKi page for more information on its signature verification methodology.

$fbsig = array();
$appsecret = YOUR_SECRET_APP_KEY;

foreach($_POST as $key=>$value)
  if(substr($key,0,7) == 'fb_sig_')
    $fbsig[substr($key,7)] = $value;
foreach($fbsig as $key=>$value)
  $string .= $key . '=' . $value;
$string.= $appsecret;
//verify this string with the signature value.
if(md5($string) != $_POST['fb_sig'])
//send an error message and exit
  echo 'Invalid request !! Are you logged in?';
$msg = "Name :  $name n";
$msg .= "Address : $address n";
$msg .= "Phone: $phone n";
//send a mail of the information or store in database
mail('[email protected]','contact',$msg);
//send a confirmation message which is displayed to the user.
echo "Thank You, for your interest in Digimantra."

What Have You Learned?

With the power of Ajax built into FBJS, you can create more interactive Facebook applications. The example that we just ran through was a simple demonstration of how doing to develop an application easily with FBJS. As you learn more about it, you can create more powerful applications that allow you to utilize Facebook’s built-in resources, such as friend picker and chat.
Sachin Khosla is a Web developer and technology evangelist who has written and spoken extensively about open source technology. Sachin is part of an active open source community that organizes OSScamp in Delhi, India. To learn more about this author, read Sachin’s blog at Digimantra.com.