Facebook Javascript SDK – Reload/Redirect URL after Facebook Login

 
Update 2012-01-14: For OAuth 2.0 implementation, please refer to the new post.
Facebook Javascript SDK – Logout with OAuth 2.0

Update 2011-12-19: Since Facebook has updated their authentication system and HTTP to OAuth 2.0 and HTTPS. The following example will not work any more. i will update the post later. For more information, you can refer to Jerry Cain – Updated JavaScript SDK and OAuth 2.0 Roadmap

 

We tried a simple Facebook login using Facebook Javascript SDK yesterday.
Facebook Javascript SDK – A Simple Login Page

In the above post, the browser will not refresh the website URL after the Facebook login process is completed. We have to issue a refresh manually. Actually we can add the reload/redirect with just a simple API call.
Let’s add the FB.Event.subscribe in fb-login.php.

<?php

// Enter the app id and secret below
define('YOUR_APP_ID', '<facebook app id>');
define('YOUR_APP_SECRET', 'facebook app secret');

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

$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
$user = json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));

?>
<html>
  <head>
    <title>Eureka! - My Facebook Login Page</title>
  </head>
  <body>
    <div id="fb-root"></div>
    <?php if ($user->id) { ?>
      <p>Welcome <?= $user->name ?></p>
    <?php } else { ?>
      <script src="http://connect.facebook.net/en_US/all.js"></script>
      <script>
        FB.init({ 
          appId:<?php print YOUR_APP_ID; ?>, cookie:true, 
          status:true, xfbml:true
        });
        /*** Redirect after Facebook login ***/
       FB.Event.subscribe("auth.login", function(response) {
         // Reload the same page
         window.location.reload();
         // Or uncomment the following line to redirect
         //window.location = "https://ykyuen.wordpress.com";
       });
     </script>
     <fb:login-button>Login to Eureka!</fb:login-button>
    <?php } ?>
  </body>
 </html>

 

Done =)

Reference: Facebook Developers – Facebook for Websites

4 thoughts on “Facebook Javascript SDK – Reload/Redirect URL after Facebook Login”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.