Thursday, November 1, 2012

Handle Facebook API real time updates using PHP

Facebook Graph API offers a cool feature for applications, real time updates, to enable your application to subscribe to changes in data. Using the API can improve dramatically the reliability of your application and decrease the load time. Whenever a subscribed change occurs, Facebook makes a HTTP post request to the URL address you specify, with a list of changes. Please note that only the changed properties are sent, not the actual data. You'll have to query the data using Facebook APIs (Graph or FQL) in order to get the changes.
Real time updates are easy to configure, the Facebook documentation is strait forward: https://developers.facebook.com/docs/reference/api/realtime/
However, you have to handle the post data sent by Facebook; on the developers website you can find a Python sample application. A lot of Facebook developers are asking for a PHP version.
I recently built a simple PHP to handle Facebook post requests which works great for a large volume of data. The script is also verifying the request by validating the X_HUB_SIGNATURE header and making sure is coming from Facebook.
Here is the code:

if($_SERVER['REQUEST_METHOD'] == 'GET')
{
    if(array_key_exists('hub_mode', $_GET)
        && array_key_exists('hub_challenge', $_GET)
        && array_key_exists('hub_verify_token', $_GET)
        && $_GET['hub_mode'] == 'subscribe'
        && $_GET['hub_verify_token'] == FB_REALTIME_API_SECRET)
        die($_GET['hub_challenge']);
}
elseif($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $payload = file_get_contents('php://input');
    if(!empty($payload)
        && array_key_exists($_SERVER, 'HTTP_X_HUB_SIGNATURE')
        && $_SERVER['HTTP_X_HUB_SIGNATURE'] == 'sha1='
              .hash_hmac('sha1', $payload, FB_APP_SECRET))
        // Do your thing - for example cache the payload on a database for later processing
}

Happy coding!