Sunday, 22 April 2012

Integrating Facebook register social plugin on websites

Here's a basic step by step guide on implementing the Facebook registration social plugin to your website. Following the steps below will quickly get your site registering users from Facebook.

to find out more on the registration plugin please read the Facebook registration plugin documentation

Step 1


the first step that you would need to take is to register your app on Facebook.
  1. navigate to Facebook developer
  2. create a new app
copy your [app id] and [app secret] as both would be required later

Step 2


you will need a couple of scripts to get things up and running.

firstly, we would need to load the javascript SDK as we would be using FBML tags. you can choose to create a .js to store this script and reference in or simply paste it in the block in your pages. remember to insert your [app id] you copied in step 1 and replace the links with your own domain.

window.fbAsyncInit = function () {
    FB.init({
        appId: '[your app id]', // App ID
        channelUrl: 'http://www.blahblahblah.com/channel.html', // Channel File
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        oauth: true, // enable OAuth 2.0
        xfbml: true  // parse XFBML
    });

    // Additional initialization code here
    FB.getLoginStatus(function (response) {
        if (response.status == 'connected') {
            if (fblogin == false) {
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;
                window.location.href = 'http://www.blahblahblah.com/login.ashx?at=' + accessToken;
            }
        } else {
            // do something
        }
    });
};

// Load the SDK Asynchronously
(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));


we use the FB.getLoginStatus function to retrieve the login status on each page, this can be used to hide the login box/section and to show user info.
it perform a check and login when a user login or reopens the browser. The fblogin variable is created in page_load on the masterpage, which checks if we have the Session variables needed.

    protected void Page_Load(object sender, EventArgs e)
    {
        string script = "";
        if (Session["fbid"] != null)
        {
            script = "var fblogin = true;";
        }
        else
        {
            script = "var fblogin = false;";
        }
        
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "fblogincheck", script,true );
    }


Step 3


Next, we would need to create a registration page (register.aspx), this would hold the registration plugin below.
  • fields : holds the list of fields required by your application (pls read the Facebook registration plugin documentation if you need custom fields)
  • redirect-uri : holds the uri that Facebook will redirect to once the user has authorized your app. the signed_request will be posted to the url.



Step 4


We would also need to create a page/handler to process the information passed from the authorization dialog/registration page.

to simplify implementation, i've used the Facebook C# SDK, you should have Facebook.dll and Newtonsoft.Json.dll in the bin folder once you've referenced this.

I've used a generic handler (.ashx) to handle the login/registration. this handler handles both the post from the Facebook authorization dialog and also the login redirection; thus i've retrieved the access token using an if-else check to see what has been passed to the handler.

the extra interface implemented is required if you want to persist any data to the session state.

public class login : IHttpHandler, IRequiresSessionState {
    
    public void ProcessRequest (HttpContext cx) {
        cx.Response.ContentType = "text/html";
        string at = "";
        FacebookClient fb = new FacebookClient();

        if (cx.Request["signed_request"] != null)
        {
            dynamic signedRequest = fb.ParseSignedRequest("[app secret]", cx.Request["signed_request"].ToString());
            at = signedRequest.oauth_token;
        }
        else if (cx.Request["at"] != null)
        {
            at = cx.Request.QueryString["at"];
            cx.Session["AccessToken"] = at;
        }

        if (at != "")
        {
            fb = new FacebookClient(at);
            dynamic result = fb.Get("me", new { fields = "name,id,gender,birthday,email" });

            string name = result.name;
            Int64 id = Convert.ToInt64(result.id);

            cx.Session["fbid"] = id;
            cx.Session["fbname"] = name;

            // perform the user registration/check here
        }
        else
        {
            //do something if no access token is found
        }
        cx.Response.Redirect("/index.aspx");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

this is a very very simplified implementation of the registration plugin, it gives only the basic name and id which you can use to register a user to your website. should you need further information from Facebook or custom fields, you can add them to the codes above and request the necessary permissions on the Facebook developer app.

to get the birthday and email fields, you would need to add [email] and [user_birthday] permissions ... go to auth dialog on the app settings and add them under authenticated referrals -> user & friend permissions.

2 comments:

  1. Thanks man, really good job. The best .net facebook registration tutorial on the web.

    ReplyDelete