Wednesday, January 9, 2013

Facebook login integration with website, Login with Facebook for websites

Facebook provide OAuth support provides web developers are able to create a Login or Sign In option with Existing Facebook Account without spending more time on new registration on your website.
Herewith we saw how to integrate in to your website using  Login with Facebook Button in easy way.

In Order to Create a "Login with Facebook" for your website you need a Facebook account to generate APP_ID and APP_SECRET, Create a Facebook user account and Navigate to the App Developer Page
http://www.facebook.com/developers/

In Top right  press "Create New App" Button you will navigate to the following screen.


In this App Creation Popup, tell your app Display Name on your Facebook Login Popup. and App Namespace is Unique Identifier on Facebook (all lowercase) Check I Agree and Continue. in next screen expand Website Rown from "Select how your app Integrates with facebook" Section.


put your website URL which actually place the "Login with Facebook" Button. eg: http://www.w3lessons.com/ or In case of Local testing you can put http://localhost/facebooklogin/
 press "Save Changes" on Bottom of that screen register your App on Facbook.

Now Your App is Ready and you can create "Login with Facbook" Button for your website.

1. PHP functions for Server Side handling to get Facebook data and store them to our database.
2. Create Login Button Using Facbook JavaScript SDK
3. Create Logout Button Using Facebook SDK

facebook-login.php  (full Source)
<?php
session_start();
define('YOUR_APP_ID', 'YOUR_APP_KEY_HERE');
define('YOUR_APP_SECRET', 'YOUR_SECRET_KEY_HERE');

function get_facebook_cookie($app_id, $app_secret) { 
    $signed_request = parse_signed_request(@$_COOKIE['fbsr_' . $app_id], $app_secret);
    // $signed_request should now have most of the old elements
    $signed_request['uid'] = $signed_request['user_id']; // for compatibility 
    if (!is_null($signed_request)) {
        // the cookie is valid/signed correctly
        // lets change "code" into an "access_token"
  // openssl must enable on your server inorder to access HTTPS
        $access_token_response = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$app_id&redirect_uri=&client_secret=$app_secret&code={$signed_request['code']}");
        parse_str($access_token_response);
        $signed_request['access_token'] = $access_token;
        $signed_request['expires'] = time() + $expires;
    }
    return $signed_request;
}

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

if (isset($_COOKIE['fbsr_' . YOUR_APP_ID]))
{ 
$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']));
 
/*
Uncomment this to show all available variables
echo "<pre>";
 - print_r function expose all the values available to get from facebook login connect.
print_r($user);
 1. Save nessary values from $user Object to your Database
 2. Register a Sesion Variable based on your user account code
 3. Redirect to Account Dashboard
echo "</pre>";
*/
 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facebook Login Connect for Website Demo</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 14px;
 color: #333;
}
body {
 margin-left: 50px;
 margin-top: 50px;
}
</style>
</head>
<body>
<?php if (@$cookie) { ?>
<h2>Welcome <?= $user->name ?> </h2> <br />
E-mail ID: <?= $user->email ?>
<br />
<a href="javascript://" onclick="FB.logout(function() { window.location='facebook-login.php' }); return false;" >Logout</a>
<?php } else { ?>
<h2>Welcome Guest! </h2>    
<div id="fb-root"></div>
<fb:login-button perms="email" width="width_value" show_faces="true" autologoutlink="true" size="large">Login with Facebook</fb:login-button>
<?php } ?>
<script src="http://connect.facebook.net/en_US/all.js"></script>   
<script>
 // Initiate FB Object
 FB.init({
   appId: '<?= YOUR_APP_ID ?>', 
   status: true,
   cookie: true, 
   xfbml: true
   });
 // Reloading after successfull login
 FB.Event.subscribe('auth.login', function(response) { 
 window.location.reload(); 
 });
</script>
</body>
</html>
If you have any problem feel free to comment


Download This Script     Facebook Connect Live Demo

51 comments:

  1. I have followed your post and try to do it by just change the app id and secret id. and copy this file to my root folder but it won't work. no email id or user name displayed.
    What should I do? please reply.
    Thank u

    ReplyDelete
  2. Kindly Verify your facebook App running on the same Website, While you are configure at Website URL setup at the time of New App Creation on Facebook developer account.

    ReplyDelete
  3. Hi Mr Jailani, hopefully you can help my trouble. I like yout sample project. But, can i make this project using coldfusion?? Thanks so much Mr Jai.

    ReplyDelete
  4. Hi, Above Sample Project build with Facebook PHP SDK. As you need in ColdFusion you can use this Facebook Connect code at
    "https://github.com/weejames/Facebook-Connect-Library-for-Cold-Fusion"
    hopefully this will help to your project.

    ReplyDelete
  5. I have managed to create a login and logout page. but I am still confused how to get and display the email and username of the member login.

    could you give me an example with the full source of the sample?

    ReplyDelete
  6. how can i get APP_KEY and SECRET_KEY ?
    in my facebook apps, theres have APP_ID and APP_SECRET. Thanks so much

    ReplyDelete
  7. hi.I have used your code only.But where we add the redirection page after login

    ReplyDelete
  8. When I try to integrate this code ..its saying invalid API key ..though I gave it correct.

    ReplyDelete
  9. It all worked great, but the email and name doesn't come through, and the "logout" link doesn't work?!

    ReplyDelete
  10. Thank you very much ... It is working great. But how can we implement it without using cookies.

    ReplyDelete
  11. after the login it says just "welcome" with out the name and same thin about "E-mail ID:" pls help me

    ReplyDelete
  12. You have done a nice job but how can we speed up this process in website. If we place this code in top of website it took 10-15 seconds to make page load and without it site loads in 2 secs.

    Any IDEA

    ReplyDelete
  13. Hello Sir,How to use the below code :

    Uncomment this to show all available variables
    - print_r function expose all the values available to get from facebook login connect.
    print_r($user);
    1. Save nessary values from $user Object to your Database
    2. Register a Sesion Variable based on your user account code
    3. Redirect to Account Dashboard
    echo

    ReplyDelete
  14. Thank you, your code works nice with me, but i'd like to make some changes. How do i change the Facebook login popup window size?

    ReplyDelete
  15. hi thanks your code working nice. Can you please tell me how to fetch friends details?. viz. name photo, working currently,date of joining etc..

    ReplyDelete
  16. Nice work....But receving error as below

    Warning: file_get_contents() [function.file-get-contents]: URL file-access is disabled in the server configuration in C:\APM_Setup\htdocs\app_name\facebook-login.php on line 14

    Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=xxxxxxxxxx&redirect_uri=&client_secret=xxxxxxxxxxxxxxxxxx) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in C:\APM_Setup\htdocs\app_name\facebook-login.php on line 14

    pls help....

    ReplyDelete
  17. Problem behind this error message is, your hosting provider blog the url access from PHP Script, ask them to enable this feature.

    ReplyDelete
  18. Thanks dude !
    It works perfectly !
    (Y)
    :D

    ReplyDelete
  19. Great Post
    thanks
    For more posts on technology visit Technology blog

    ReplyDelete
  20. Their hardware will be supplanted, in order to build their capability and organization limit, regardless of the contracting size, with acquisitions for instance of land gear among others. Two imperative land programs are at present under thought. dansk

    ReplyDelete
  21. To grow rapidly, at least initially the service should be offered for free. Ads can be displayed to help offset part of the launching and initial running costs. Facebook group poster

    ReplyDelete
  22. Should you feel find it difficult to, you undoubtedly is not able to; If you don't intend, to have failing. Things are subject to intellect, reduction of hundreds exercises are hopeless prior to starting. webceed

    ReplyDelete
  23. Your texts on this subject are correct, see how I wrote this site is really very good.
    mason soiza

    ReplyDelete
  24. Each word composed has charmed its group of onlookers in the most one of a kind way.
    Mason Soiza

    ReplyDelete
  25. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks realizzazione e commerce san marino

    ReplyDelete
  26. I found your this post while searching for information about blog-related research ... It's a good post .. keep posting and updating information.
    Mason Soiza

    ReplyDelete
  27. If you don't have so many fans and you just keep trying and tired of it..so buy social media fans from here..Hopefully you will get a lot fans..

    ReplyDelete
  28. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. Buy Facebook Negative Reviews

    ReplyDelete
  29. Thanks for the post and great tips: even I also think that hard work is the most important aspect of getting success.

    ReplyDelete
  30. Thanks for the post and great tips: even I also think that hard work is the most important aspect of getting success. Buy Bad Facebook Reviews

    ReplyDelete
  31. This is really very nice post you shared, i like the post, thanks for sharing.. Data Centers

    ReplyDelete
  32. Wonderful blog! Do you have any tips and hints for aspiring writers? Because I’m going to start my website soon, but I’m a little lost on everything. Many thanks! Resell websites in affordable prices

    ReplyDelete
  33. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much.
    SubsShop.com

    ReplyDelete
  34. You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant!
    https://zartash.pk

    ReplyDelete
  35. I’m Really Impressed With Your Article, Such Great & Usefull Knowledge You Mentioned Here.https://www.kniveskingdom.com/whole-sale-swords

    ReplyDelete
  36. Keep posting such outstanding post. it really helps all of your visitor ..zonlineshop

    ReplyDelete
  37. I propose merely very good along with reputable data, consequently visualize it:https://www.whatsappsociety.com/

    ReplyDelete
  38. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing. facebook pva accounts

    ReplyDelete
  39. I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer.Thanks. SEO optimalisatie

    ReplyDelete
  40. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future... SEO

    ReplyDelete
  41. I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, im always look for people to check out my web site. website design company los angeles

    ReplyDelete
  42. So as to settle on the best decision for your ebb and flow circumstance you should assess each plan firm you are taking a gander at and settle on an educated choice dependent on your exploration and not the company's attempt to sell something. new york website design company

    ReplyDelete
  43. Just pure brilliance from you here. I have never expected something less than this from you and you have not disappointed me at all. I suppose you will keep the quality work going on.
    website design company los angeles

    ReplyDelete
  44. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. subastas

    ReplyDelete
  45. as should be obvious, getting a website review could truly demonstrate useful. To do as such, you can look at assets like Fiverr where individuals offer these sorts of things at extensively low costs.website reviews

    ReplyDelete
  46. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. and if you need Website Design Company then contact us!

    ReplyDelete