Thursday, July 22, 2010

Facebook - How to use facebook connect on your site | facebook connect beginners guide

Recently I came across the facebook connect API when developing a site that uses facebook connect for it's football manager game. There are a lot of tutorials out there that shows how to do this and that but here I wanted to share a simple guideline on the first step to implement facebook connect to your site.

The first thing you have to do of course to register your application in facebook. You can do that here.

When finished, you will be given an API Key and Application Secret codes, these codes will be use later in the connect API.

You can now write your php file like the sample below:


function get_facebook_cookie($app_id, $application_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
  if (md5($payload . $application_secret) != $args['sig']) {
    return null;
  return $args;
$fb_cookie = get_facebook_cookie(FACEBOOK_APP_KEY, FACEBOOK_SECRET);

if ($fb_cookie) { //if logged in
<!DOCTYPE html>
<div id="fb-root"></div>
FB.init({appId: "<?php echo FACEBOOK_APP_KEY; ?>", status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
    document.location.href = 'document.location.href';

function fb_logout() {
    FB.logout(function(response) {
        document.location.href = 'document.location.href';

<?php if (!$fb_cookie) { //if not login ?>
             <fb:login-button perms="publish_stream,user_photos" v="2"><fb:intl>Connect with Facebook</fb:intl></fb:login-button>
      <?php } else { ?>
                  <div class="logout">
                       HI, <?php echo strtoupper(substr($user->first_name, 0, 17)); ?>! | <a href="javascript:fb_logout()">LOGOUT</a>
      <?php } ?>

      <!-- do your things here-->


There you go, simple application that has a connect button and logout button to sign out. 

If you are using Jquery tools plugin, you cannot use the flashembed feature as it would give you error in Internet Explorer "your api key is not valid.... etc". That's the only issue that I found throughout my experience.

1 comment:

Anonymous said...

Very helpful. Thanks for posting this. Cheers.