Facebook How-To: scheduling profile updates

Several of the Facebook Applications I have developed have required scheduling updates to Facebook User Profiles.

The process for scheduling updates is a little involved, but basically involves using a Session Key to push data to each User’s Profile.

  • Store the user’s Session Key.
  • Schedule an update with Cron
  • User the User ID and Session Key to create a Facebook Client Object make a Facebook API call.

The following samples are from a CakePHP project I recently completed and use the Facebook PHP Library. I’ve expanded the SQL so you have a better idea of what is happening behind the scenes.

Store the Session Key:

function beforeFilter() {
$this->facebook_user_id = $this->facebook->require_login();
$this->sessionKey = $this->facebook->api_client->session_key;
$this->Settings->query("UPDATE settings SET sessionKey = '{$this->sessionKey}' WHERE id = '{$this->facebook_user_id}'");
}

Each time the user hits the application I generally refresh the Session Key in my normal login/authentication process.

Make the API Call:

$data = $this->Settings->query("SELECT * FROM settings WHERE lastUpdated <= DATE_SUB( NOW(), INTERVAL 1 DAY) ORDER BY lastUpdated ASC LIMIT 1");
$id = $data[0]["settings"]["id"];
$sessionKey = $data[0]["settings"]["sessionKey"];
$this->facebook = new Facebook(FB_API_KEY, FB_SECRET);
$this->facebook->set_user($id, $sessionKey);
$this->facebook_user_id = $id;
$this->facebook->api_client->profile_setFBML($fbml);

This code grabs the first Faccbook User from the database who last updated a day ago and then creates a Facebook Client using the Facebook User Id and Session Key to make an API Call.

Note: When scheduling updates I generally use Cron to call a URL on my application with wget or Curl. Using this technique you can leverage the existing logic of your app and don’t have to write a standalone script.

One Response to “Facebook How-To: scheduling profile updates”

  1. Konr says:

    How long does the user’s session key remain valid for updating a profile?

Leave a Reply