Single Blog Title

This is a single blog caption

Facebook signup on website and accessing the user information from facebook

//
Posted By
/
Comment0
/

I am a web developer by profession, and the first impression that the facebook left on my face on my first interaction with it was a big WOW!

How come Mark Zukerberg able to sense the ease at which the end user wants to interact with a web site. And at the very next moment I made my mind to implement a Facebook Registration interface on my site. Facebook provides tools to quickly register users for your website. With the addition of the Registration, Facebook will facilitate user registration for Facebook and non-Facebook users.

After going through the developer documentation thoroughly I decided to implement it on one of my website. We need to have a Facebook Application Id and secret key in order to access facebook tools in our website. I am using Registration Plugin to let user register from our website.

The Registration Plugin will streamline the Registration process for Facebook users by pre-filling many fields, and for all non-Facebook users, provide a simple form that can be easily integrated into your website.

You can see from the screen shot below as I am already login to my facebook account some information is prefilled from the facebook database. In addition I have added some fields that are required for my site. This facebook lookalike registration system is displayed from my local system as you can find it from the URL.

Accessing facebook user information

Given below is the screen shot of my registration page once I log out from the facebook. You can see all the form fields are blank.

Registration without facebook login

Now let me let you know how to implement this facebook registration interface on your website. Given below is the html tag of my registration.aspx page which includes the facebook registration control

<fb:registration:  <body>  <div id="wrapper">  <div id="content">  <div class="reg-cont">  <div id="fb-root"></div>  <script type="text/javascript">  window.fbAsyncInit = function() {  FB.init({  appId   : 187468337965792,  status  : true,  cookie  : true,  xfbml   : true  });  };  (function() {  var e = document.createElement('script');  e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';  e.async = true;  document.getElementById('fb-root').appendChild(e);  }());  </script>  <fb:registration  fields="[{'name':'name'},  {'name':'email'},  {'name':'location'},  {'name':'gender'},  {'name':'birthday'},  {'name':'password'},  {'name':'like',       'description':'Do you like this plugin?', 'type':'checkbox',  'default':'checked'},  {'name':'phone',      'description':'Phone Number',             'type':'text'},  {'name':'anniversary','description':'Anniversary',              'type':'date'},  {'name':'captain',    'description':'Best Captain',             'type':'select',    'options':{'P':'Jean-Luc Picard','K':'James T. Kirk'}},  {'name':'force',      'description':'Which side?',              'type':'select',    'options':{'jedi':'Jedi','sith':'Sith'}, 'default':'sith'},  {'name':'live',       'description':'Best Place to Live',       'type':'typeahead', 'categories':['city','country','state_province']},  ]"  redirect-uri="http://localhost:3850/work_at_home/index.aspx"  width="530">  </fb:registration>  </div>  </div>  </div>  </body>

All you need to do is place the above tag on your page and the Interface is ready to impress your users

You can add the fields of your choice, that u want to capture and store in your database. Once the user is done with the registration he can be redirected to some other page by assigning the page link to the redirect-uri property, as I have done I am redirecting the user to index.aspx page where I will display some information of the user that he had entered at the time of registration.

The form fields are by default validated with some credentials, as shown in the figure below. We can change the validation credentials as per our need.

To get the data on your end, you must use the client side validation function to add those to the user’s session (via a cookie or server-side call). Then when the form submit comes through you can read the signed_request and the data you stored in the user’s session and build your user row in your database.

I am using Server side call to extract data returned by Facebook.

Given below is the code that I had written to read the signed_request string?

Please follow the code in c# to read the decoded json object from the signed_request.

protected void Page_Load(object sender, EventArgs e)  {  if (Request.Form["signed_request"] != null)  {  JObject obj = DecodingFacebookRequest(Request.Form["signed_request"]);  name = obj.SelectToken("registration.name").ToString();  string email = obj.SelectToken("registration.email").ToString();  uid = obj.SelectToken("user_id").ToString();  message = "<p>Congratulations " + name + ", you are now a member!</p>";  �  }  }  �  public static JObject DecodingFacebookRequest(string signed_request)  {  �  string[] requestArray = signed_request.Split('.');  string  sig = Base64_Url_Decode(requestArray[0]);  string  dataString = Base64_Url_Decode(requestArray[1]);  JObject data = JObject.Parse(dataString);  string algo = data["algorithm"].ToString().Replace(""", "");                      if (algo != "HMAC-SHA256")  {  return null;  }  �  return data;  }  �  �  public static string Base64_Url_Decode(string input)  {  string fixedString = string.Empty;  string fixedDashString = input.Replace('-', '+');  string fixedUnderscoreString = fixedDashString.Replace('_', '/');  if (fixedUnderscoreString.Length % 4 != 0)  {  fixedString = String.Format("{0}", fixedUnderscoreString);  int paddingCount = fixedString.Length % 4;  while (paddingCount % 4 != 0)  {  fixedString += '=';  paddingCount++;  }  }  else  {  fixedString = fixedUnderscoreString;  }  byte[] inputBytes = new byte[0];  inputBytes = Convert.FromBase64String(fixedString);  return Encoding.UTF8.GetString(inputBytes);  }

In the above code what I am doing is reading the encoded signed_request and decoding it to get the json object.

The signed_request parameter is a concatenation of a HMAC SHA-256 signature string, a period (.) and a base64url encoded JSON object. As we receive the signed request we need to decode the base64url JSON object and that is done as explained below:

1)        Extracting the strings from the query string  from  function And converting it from base64url encoded to normal string

string[] requestArray = signed_request.Split('.');  string  sig = Base64_Url_Decode(requestArray[0]);  string  dataString = Base64_Url_Decode(requestArray[1]);

2)      Then parsing the returned string from Base64_Url_Decode()to Json object

3)      I have used Newtonsoft.Json.Linq to work with Jobject. Once we get the Json object, the required information can be fetched as shown in code below by using select token function of the JObject. As shown below:

name = obj.SelectToken("registration.name").ToString();  string email = obj.SelectToken("registration.email").ToString();  uid = obj.SelectToken("user_id").ToString();

I have just fetched the name and email of the registered user and displayed it on my index.aspx page as shown in the screen shot:

<div>  <div>  <div ><h1>you are a registered user</h1></div>  </div>  <div id="content">  <div>  <%= Message %>  </div>    </div>  </div>

This Message property is initialized from code behind as shown below:

message = "<p>Congratulations " + name + ", you have registered and your email id is "+email+" !</p>"; }

With this I conclude my article, and very soon I will be coming with some other facebook Plugin.

Leave a Reply