As
a software developer I think that you have to watch "The Social
Network" movie once a month.
If you haven’t invented facebook
yet then you should always try to create something that will change the world.
A
few days ago I watch it again and suddenly I had an idea to create a website
that in my opinion many people will use it (I hope). The website will have to
integrate with facebook. I decided to post some tutorials for using Facebook
API with mvc4.
If
your website will use facebook info the first thing you have to do is log into
facebook. I tried to use different helpers (Facebook helper, Microsoft helper)
but after a while I decided that the best way is to write your own code (the
helpers didn’t really help).
This
post I'll talk about login into facebook from your site.
We will login into facebook in 10 simple steps:
1. Create an asp.net mvc4 web application using basic tamplate:
2. Create Home controller and
the Index view:
3. Create a "FacebookLoginModel":
public class FacebookLoginModel
{
public string Uid { get; set; }
public string AccessToken { get; set; }
}
4. Create the "AcountController" and the "FacebookLoginMethod". This method will be called after a successful login so that we store the access token and the user id in order to use them whenever we would like to connect to facebook servers from our site:
public class AccountController : Controller
{
[HttpPost]
public JsonResult FacebookLogin(FacebookLoginModel model)
{
Session["uid"] =
model.Uid;
Session["accessToken"] =
model.AccessToken;
return Json(new { success = true });
}
}
5. Go to https://developers.facebook.com/ and create a new facebook app. Even though you create your own website you have to create a facebook application so that all the facebook services would work.
Make sure that all the app's urls point to your
website url
6. Save the AppId and the AppSecret in your web.config:
<add key ="FacebookAppId" value="11111111"/>
<add key ="FacebookAppSecret" value="2222222222"/>
7. Create Facebook.js file and paste there this script:
function
InitialiseFacebook(appId) {
window.fbAsyncInit = function () {
FB.init({
appId:
appId,
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('auth.login', function (response) {
var credentials = { uid:
response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
});
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
alert("user is logged into
fb");
}
else if (response.status === 'not_authorized') {
alert("user is not authorised"); }
else { alert("user is not conntected to facebook"); }
});
function
SubmitLogin(credentials) {
$.ajax({
url:
"/account/facebooklogin",
type: "POST",
data: credentials,
error:
function () {
alert("error logging in to
your facebook account.");
},
success: function () {
window.location.reload();
}
});
}
};
(function (d) {
var js, id = 'facebook-jssdk', ref =
d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js =
d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
}
This java script will subscribe us to the login event on which we'll receive our access token and save it in the Session object. Besides that the js will alert every time the user logs in and logs out.
8. Add the initialization
method for the facebook services in your _Layout.cshtml:
<div id="fb-root"></div>
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Facebook.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
InitialiseFacebook(@System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"]);
});
</script>
9. Now we'll add the facebook button html to our view
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<fb:login-button autologoutlink="true" perms="read_friendlists, create_event, email, publish_stream"></fb:login-button>
Now your session holds the access token which helps you to
connect to facebook from your site.
10. F5 the solution and observe!
Hitting the pretty login button opens formal facebook login page that after submitting stores the access token in the Session object.
In the next post I'll show you have to get your facebook details and how to use the FQL – Facebook Query Language.