Connecting to Facebook


A developer can use several ways to connect with the Facebook Platform depending on the goal she/he is trying to achieve.

If the developer only wants to use client side validation, he can easily do it using the following code.

      <div id="fb-root"></div>
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            appId      : 'YOUR_APP_ID',
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
        };
        (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>

The APP_ID is a code given by Facebook to developers to identify each application individually. Each application is bounded to a domain (or set of domains) to avoid counterfeit application. To enforce this policy, APP_ID are given only to accounts that can be traced to a person offline. This verification is made by either giving a cellphone number or a credit card number.

However, if the developer need a more powerful solution he can opt to use a more robust approach such as the Facebook PHP-SDK

/*On the top of file*/
<?php define('YOUR_APP_ID', 'YOUR APP ID');

require 'facebook.php';

$facebook = new Facebook(array(
  'appId'  => YOUR_APP_ID,
  'secret' => 'YOUR APP SECRET',
));

$userId = $facebook->getUser();

?>

<!-- In the Body -->

    <?php if ($userId) {
      $userInfo = $facebook->api('/' + $userId); ?>
      Welcome <?= $userInfo['name'] ?>
    <?php } else { ?>
    <div id="fb-root"></div>
    <fb:login-button></fb:login-button>
    <?php } ?>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : '<?= 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>

This approach allows the manipulation of the content in realtime, changing the elements to be displayed when the page is loading, providing a better way to customize the content of the site for each user.

  1. No comments yet.
(will not be published)