Quantcast
Channel: Eureka! » Facebook PHP SDK
Viewing all articles
Browse latest Browse all 3

Facebook Javascript SDK – A Simple Login Page with OAuth 2.0

$
0
0

A few months ago, i published several posts about Facebook Javascript SDK but they no longer work since Facebook updates to OAuth 2.0. So this post is the updated version of
Facebook Javascript SDK – A Simple Login Page
and it should work works with OAuth2.

1. Create the a Facebook App @ Facebook Developers.

2. Enter the website URL under Select how your app integrates with Facebook.

3. In the webroot folder, create a directory called php-sdk and download the following 2 files from GitHub – facebook / php-sdk to the new created folder.

  • facebook.php
  • base_facebook.php

 

4. Upload the following file to your web server. This file should be located at the URL which we enter in step 2.
fb-login-oauth2.php

<?php

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

require 'php-sdk/facebook.php';

$facebook = new Facebook(array(
  'appId'  => YOUR_APP_ID,
  'secret' => YOUR_APP_SECRET,
));

$userId = $facebook->getUser();
?>

<html>
  <body>
    <div id="fb-root"></div>
    <?php if ($userId) { 
      $userInfo = $facebook->api('/' + $userId); ?>
      Welcome <?= $userInfo['name'] ?>
    <?php } else { ?>
    <fb:login-button></fb:login-button>
    <?php } ?>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId : <?php print YOUR_APP_ID; ?>,
          status: true, 
          cookie: true,
          xfbml : true,
          oauth : true,
        });

        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });
      };

      (function(d){
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
      }(document));
    </script>
  </body>
</html>

 

That’s all for the OAuth2 updates. But there is a slight difference with the old example Facebook Javascript SDK – A Simple Login Page. In this new example, after you have logged in, the login session will not end even if you logout from http://www.facebook.com in another browser tab. So you have to add the log out feature otherwise the application will keep your login session until you clear the browser cache.

Done =)

Reference:


Filed under: Facebook API Tagged: Facebook, Facebook Javascript SDK, Facebook PHP SDK, Javascript, OAuth, OAuth 2.0

Viewing all articles
Browse latest Browse all 3

Trending Articles