Automatically Update all your User’s Facebook Profile

June 27th, 2007

While developing my first Facebook application, I spent a lot of time trying to get my application to auto-update everybody’s Facebook Profile. Majority of this time was wasted searching though discussion boards. Hopefully this will save you some grief.

You probably know by now that Facebook caches anything you post to a user’s profile. This means that you have to write a script which manually updates everyone’s profile. You might think that the reference tag would be the exception, but you would be mistaken.

Facebook will cache the following line:
<fb:ref url=”http://www.mysite.com/someurl.php” />

In order to clear the cache, you would have to execute this line:
facebook.fbml.refreshRefUrl(“http://www.mysite.com/someurl.php”)

Although using handles and references is a valid approach, I found it simpler to use profile_setFBML instead.

This led me to the next problem I ran into. When I started writing my auto-update script, I ran into the infamous “Invalid session key” error. In order to execute profile_setFBML, you need have a valid session key (you will need a valid session key for refreshRefUrl as well). This can be ANY session key! It doesn’t have to be the session key of the user’s profile you are updating.

Unfortunately, this isn’t as easy as using your own session key. Session Keys have lifespans, so we will have to create a special infinite session key. The first step is to create a new user for Facebook. Once you successful do that, install your application for your new user.

Next go to the following address and generate yourself an auth token:
http://www.facebook.com/code_gen.php?v=1.0&api_key=YOUR_API_KEY

Then pass your auth. token to your canvas:
http://apps.facebook.com/applicationname/?auth_token=YOUR_AUTH_TOKEN

When you are on your canvas, you will need to print your session key. You can do this by printing this:
<?php echo htmlentities($facebook->api_client->session_key); ?>

We can then use this key to update everyone’s user profile. Here is some example code (it should work).

Now that we have the script written, you will have to create a cronjob which will execute it on a given interval. I am not going to go into any details on how to create a cronjob. However, most web hosts allow you to do this easily.

As an important side note, you can’t use any infinite session key to publish a story or action (feed_publishStoryToUser or feed_publishActionOfUser). You will need a valid session key for the user you are performing the action on. This will force you to keep a record of valid session keys for all your users.