• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Coding Still

  • Home
  • About

Facebook login for your website

July 22, 2015 By _tasos Leave a Comment

In this article we will see how we can implement Facebook login for your web application. We will use the JavaScript SDK but Facebook has more than one SDKs available for your language of choice.

The article consists of two parts. The first part we will be the implementation of the login process while the second part will about getting the required credentials.

The code in the first snippet is everything required to enable the Facebook API in your page. Notice that you need a Facebook App ID, we will also see how you can create one.

window.fbAsyncInit = function () {
    FB.init({
        appId: '<Facebook App ID>',
        cookie: true,
        xfbml: true,
        version: 'v3.1'
    });
};
 
// Load the SDK asynchronously
(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

The code in the second snippet is showing you can use the API. The fbLogin() function will be called when your user will click on the Login with Facebook button. The scope defines what information will be returned to you and the fbLoginCallback() function will process the response.

Depending on what information you are asking, Facebook will notify the user about it. There are cases where the user can decline sharing this information. In that case the response from Facebook will contain empty values on the declined info

function fbLogin() {
    FB.login(fbLoginCallback, { scope: 'public_profile,email,user_friends' });
}

In this code block we see how we can process the response from Facebook. All required information is saved in a local variable. The friends list (not all friends, just the ones that have also used your application) is also saved in an array. You will notice an AJAX call in the while() {...} loop. By default, the initial response will contain the first 25 friends of your user. So you need to get 25 from the response.paging.next URL and so on.

var fbLoginCallback = function (response) {
    var friends = [];
 
    if (response.status === 'connected') {
        FB.api('/me', function (response) {
            var userFullName = response.name;
            var userEmail = response.email;
            var userFacebookID = response.id;
        });
        FB.api('/me/picture?type=large&redirect=0', function (response) {
            var userAvatarUrl = response.data.url;
        });
        FB.api('/me/friends', function (response) {
            while(response.data.length > 0)
            {
                var i =0;
                for(i = 0; i<response.data.length; i++)
                {
                    var friend = {};
                    friend.id = response.data[i].id;
                    friend.type = 'fb';
                    friend.name = response.data[i].name;
                    friend.image = 'https://graph.facebook.com/' + friend.id + '/picture?type=large';
                    friend.url = 'https://www.facebook.com/app_scoped_user_id/' + friend.id + '/';
 
                    friends.push(friend);
                }
 
                jQuery.ajax({
                    url: response.paging.next,
                    async: false,
                    success: function(data) {
                        response = data;
                    }
                });
            }
        });        
    }
}

Update: With API v3.0 the /me/picture?type=large stopped working and gave me an invalid JSON error message. Turns out it needs to be updated with the parameter redirect=0.

To get a Facebook App ID you will go to Facebook Developers. At the top menu, go My Apps -> Add a New App. In the modal that appears choose Website. In your newly created App go to Dashboard and there you will see your App ID and App Secret. The App ID is the one we need for this example.

A limitation that I didn’t find a way to overcome is that I could not make this code work from my localhost. This code runs only from the domain you have set when creating your application.

Filed Under: JavaScript Tagged With: OAuth, Social media

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Categories

  • .NET Development
  • ASP.NET
  • Databases
  • Fun
  • IIS
  • JavaScript
  • Web Development

Tags

.NET Core Android ANTLR ASP.NET Ajax ASP.NET Core ASP.NET MVC ASP.NET Web Forms AWS Bouncy Castle Chartjs cli Client info detection Comic Continuous integration CSS Data backup Date handling Firebase Firefox addons Github HigLabo HTML5 Image manipulation jQuery JWT MySQL Nodejs Nuget OAuth Objectionjs OOP openssl Oracle ORM PHP Regular expressions SEO Social media SQL SQL Server UI/UX Url rewriting Videos Visual Studio Web design

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Secondary Sidebar

Archives

  • July 2020
  • March 2020
  • August 2019
  • December 2018
  • November 2018
  • February 2018
  • August 2016
  • June 2016
  • May 2016
  • February 2016
  • January 2016
  • August 2015
  • July 2015
  • October 2014
  • July 2014
  • November 2013
  • April 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • August 2012
  • May 2012
  • February 2012
  • December 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010

Footer

Recent Posts

  • Anatomy of an Objection.js model
  • Check your RSA private and public keys
  • Round functions on the Nth digit
  • Send FCM Notifications in C#
  • Jwt Manager
  • Things around the web #5
  • Query JSON data as relational in MySQL
  • Create and sign JWT token with RS256 using the private key
  • Drop all database objects in Oracle
  • Create and deploy a Nuget package

Latest tweets

  • Things I Wished More Developers Knew About Databases https://t.co/h4gfq6NJgo #softwaredevelopment #databases May 3, 2020 12:52
  • How a Few Lines of Code Broke Lots of Packages https://t.co/p7ZSiLY5ca #javascript May 3, 2020 12:48
  • Can someone steal my IP address and use it as their own? https://t.co/HoQ7Z3BG69 January 24, 2020 13:27
  • Organizational complexity is the best predictor of bugs in a software module https://t.co/aUYn9hD4oa #softwaredevelopment January 13, 2020 08:24
  • Capitalism for people. Socialism for companies? https://t.co/zgUoPcqnix January 5, 2020 07:46
  • http://twitter.com/codingstill

Misc Links

  • George Liatsos Blog
  • Plethora Themes
  • C# / VB Converter
  • Higlabo: .NET library for mail, DropBox, Twitter & more

Connect with me

  • GitHub
  • LinkedIn
  • RSS
  • Twitter
  • Stack Overflow

Copyright © 2021 · eleven40 Pro on Genesis Framework · WordPress · Log in