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…

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.

Comments on “Facebook Connect Tutorial, new version”

20 thoughts

  1. MVerh says:

    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. Giulio Pons says:

    can you see any javascript error?

  3. venkatesh says:

    i wann add a logout for this in my website, how can i do tht?

  4. Giulio Pons says:

    I haven’t done it yet. I think there is a facebook method to call to remove the facebook cookie.

  5. Giulio Pons says:

    There was an “&nbsp;” in the php code. Try to remove it.

  6. maztch says:

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

  7. Edie Summers says:

    Hello,

    I am having a hard time enabling Facebook log-in through Janrain. Any tips?

    thanks

  8. CoursesWeb says:

    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?

  9. Giulio Pons says:

    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.

  10. Giulio Pons says:

    What is Janrain?

  11. jaswinder says:

    Will this script work on localhost..?

  12. jaswinder says:

    No user information is displaying after fb login….

  13. RAJEEV says:

    it do not work on Internet explorer.

    How to make it browser compatible.

  14. Rajib Roy says:

    I am using your code for facebook connect but it is showing following error Fatal error: Uncaught OAuthException: (#601) Parser error: unexpected ‘.’ at position 456. You can try on https://www.30minutesjob.com Please help me

  15. ricki says:

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

  16. Sarten says:

    How i view the user avatar?
    $userInfo = $facebook->api(‘/’.$avatar); ?

    tnx

  17. gabriel gonzalez says:

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

  18. gabriel gonzalez says:

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

  19. Makawee says:

    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

  20. kerim says:

    it doesn’t work with firefox and IE versions. What is the problem with the code please?

Comments are closed