Facebook Connect Tutorial, new version

Since my previous connect tutorial for facebook no longer works, here is a new version of the tutorial, with also a demo page.

I will show you how to crate an app for facebook to handle the facebook connect process on your web site.

Then I will show you the php code to perform the login on facebook and retrieve the informations you need for your site.

The last suggestion will point how to merge facebook users with your users.

MAKE A FACEBOOK APP FOR FACEBOOK CONNECT

Go on the facebook developer app centre. Create a new app this way, clicking on the “+ create new app” button:

Probably you will also need to insert a captcha code. You will come to a page like this:

The app is necessary to obtain a key and a secret that belongs to your site and are necessary to let facebook users give data to your site.

You need to compile also how your app integrates with Facebook. Compile the part “Website with Facebook Login” inserting the address of your site:

The app is completed. Grab the app id and app secret:

PHP CODE FOR FACEBOOK CONNECT

You can download the libraries to interact with facebook from this project on github. Download, unpack, copy in your working folder.

Create a page named fblogin.php. This page will handle all the process. In this page you will use the php libraries together with the Javascript facebook lib. It’s very simple now, here is the code, below I will explain it:


<?php
//
// uses the PHP SDK. Download from https://github.com/facebook/php-sdk
include("facebook-php-sdk/src/facebook.php");

//
// from the facebook app page
define('YOUR_APP_ID', '321849981247524');
define('YOUR_APP_SECRET', '49fd00ce6237aff0af08fd8ca25dbc92');

//
// new facebook object to interact with facebook
$facebook = new Facebook(array(
 'appId' => YOUR_APP_ID,
 'secret' => YOUR_APP_SECRET,
));
//
// if user is logged in on facebook and already gave permissions
// to your app, get his data:
$userId = $facebook->getUser();

?>
<html>
<head>
 <style>body { text-align:center; font-size: 40px }</style>
</head>
<body>
<?php
if ($userId) {
 //
 // already logged? show some data
 $userInfo = $facebook->api('/' + $userId);

echo "<p>YOU ARE: <strong>". $userInfo['name'] ."</strong><br/>";
echo "Your birth date is: ".$userInfo['birthday']."</p>";



} else {
 //
 // use javaascript api to open dialogue and perform
 // the facebook connect process by inserting the fb:login-button
 ?>
 <div id="fb-root"></div>
 <fb:login-button scope='email,user_birthday'></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) {
 // ------------------------------------------------------
 // This is the callback if everything is ok
 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>

Trought the php libraries you check for a facebook cookie on your server, this cookie contains the informations about the user.

The lib checks if there is an app on facebook to handle login on your web site.

If there is the app and there isn’t the cookie, the Javascript part opens the dialog to handle the permission process on facebook, in the example I ask permission for email and birth date, you can ask more info. If the user isn’t logged in facebook, this dialogue will also handle the login process of facebook. If the process is done properly Javascript will handle the callback, in this example the callback is just a refresh.

If there is the app and you already have a valid cookie the dialogue will not be opened and the code doesn’t use the Javascript part, and data come directly from the php libraries that call facebook servers. Now you have data from facebook, go on!

Note: if the facebook app isn’t configured properly this will not work. For example, the URL address specified on the app config panel must be the same of the site: if you configured it for www.yourdomain.com and test it on yourdomain.com (without www), it will not work.

You can watch a WORKING DEMO here.

HOW TO MERGE FACEBOOK DATA WITH YOUR DATABASE

Now that you can grab data from facebook for the connected user, what will you do? You have to merge with yours, you can use the email to check if you have the user in your database, if you already have it you have to log him in with your custom login functions, the same way as he typed his password in your login form.

If you haven’t that email in your database, you have first to create a new user with data from facebook, and then log him in, you should also generate a random password for him.

22 comments

  1. MVerh

    Great tut! But it doesn’t work for me. When I try everything you describe, I’ll get a totaly blank page. And I’m sure the app id, the website url and secret id are correct. Is there more I have to configurate before it works? Thank you so much!

  2. maztch

    try to change this:
    $userInfo = $facebook->api(‘/’ + $userId);
    for
    $userInfo = $facebook->api(‘/’.$userId);

  3. CoursesWeb

    Hi,
    In the Facebook documentation about Login the user with Facebook APP they say:

    “Because it requires you to include your App Secret you should not attempt to make this call client-side as that would expose this secret to all your app users. It is important that your App Secret is never shared with anyone”.

    I understend it is about APP Secret, but what about the Developer ID?
    The developer ID is added in the URL address of the window for login the user with Facebook:
    https://www.facebook.com/dialog/oauth?client_id=APP_ID&redirect_uri=…&state=…&scope=…
    The APP_ID can be copied and used by anyone.
    I tryed with JavaScript SDK, and with PHP SDK, but in both cases the developer ID appears in the address bar.
    I tryed also the get and display the page from that URL address using cURL, but of course not works.
    Is there any way to login the users in my web site using Facebook, without revealing the developer ID?
    Or, it doesn’t matter if someone uses your Facebook APP ID?

  4. Giulio Pons

    The client id is not so important and you can see the client id of any user… for example in the filename of the user avatar. To use it you need to log in and know also the password I think.

  5. ricki

    people with a blank page, look for this line: appId : and insert your app id, as the current method doesnt work.

  6. gabriel gonzalez

    ¿como saco mas datos del usuario por ejemplo el nombre de usuario, ,telefono, correo electronico?
    te agradeceria mucho si me contestaras esa duda

  7. gabriel gonzalez

    How do I get more user data such as username,, telephone, electronic mail?
    I would greatly appreciate if you answer me this question

  8. Makawee

    Hello I ran your tutorial as shown but it only works on google chrome (mac version) what is wrong with the following code?

    YOUR_APP_ID,
    ‘secret’ => YOUR_APP_SECRET,
    ));
    //
    // if user is logged in on facebook and already gave permissions
    // to your app, get his data:
    $userId = $facebook->getUser();

    ?>

    body { text-align:center; font-size: 40px; }

    api(‘/’ + $userId);

    echo “YOU ARE: “. $userInfo[‘name’] .”“;
    echo “Your birth date is: “.$userInfo[‘birthday’].””;

    } else {
    //
    // use javaascript api to open dialogue and perform
    // the facebook connect process by inserting the fb:login-button
    ?>

    window.fbAsyncInit = function() {
    FB.init({
    appId : ,
    status : true,
    cookie : true,
    xfbml : true,
    oauth : true,
    });

    FB.Event.subscribe(‘auth.login’, function(response) {
    // ——————————————————
    // This is the callback if everything is ok
    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));

    you can try the following link to the file

    http://www.visitami.net/facebooksdk/fblogin.php

  9. Jesper Andersen

    How do you add a logout function to the script ? Everything works fine… but need af logout funkction ! Please help…

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>