Integrate Facebook with MVC Web API

Welcome back, now you will see how to integrate Facebook with MVC Web API.

If you are not familiar with MVC Web API, I encourage you to read my previous post here, and then come back to see how to display your Facebook feed onto your web page.

Firstly, you have to register an app at Facebook Developers site and then you get ClientId and ClientSecret, but to get an access_token use below url string:

https://graph.facebook.com/oauth/access_token?client_id=enterClientId&client_secret=enterClientSecret&grant_type=client_credentials

Once you have this access_token, use it in the API to get access to the user account and get user feed.
Optional: Use Graph API Explorer tool to get an idea which fields you need.
Here is a sample code:


//Helper class
 using Newtonsoft.Json;
 using System;

namespace Integration.Facebook
 {
 public static class Helper
 {
 //returns Facebook Feed
 public static ICollection< FbFeedItem > ReadFeed(string fbUserId, string accessToken)
 {
 /***
 * Graph API v2.4
 * /{user-id}/feed
 * The feed of posts (including status updates) and links published by this person, or by others on this person's profile. There are other edges which provide filtered versions of this edge:
 * /{user-id}/links shows only the links that were published by this person.
 * /{user-id}/posts shows only the posts that were published by this person.
 * /{user-id}/statuses shows only the status update posts that were published by this person.
 * /{user-id}/tagged shows only the posts that this person was tagged in.
 *
 ***/

//gets recent 20 user posts when limit=20
 const string UriJson = "https://graph.facebook.com/v2.4/{0}/posts?fields=message,description,created_time,id,name,link,picture,from,status_type&amp;limit=20&amp;access_token={1}";

var returnFbFeedItems = new List< FbFeedItem >();

try
 {
 var fbJsonString = Core.Utilities.Json.GetJsonString(String.Format(UriJson, fbUserId, accessToken), null, null, true);
 //create a stream to hold the contents of the response and create Facebook Object
 var fbObject = JsonConvert.DeserializeObject< FbFeedJson >(fbJsonString);

if (fbObject == null || !fbObject.Data.Any()) return returnFbFeedItems;

else
 {
 if (fbObject.Data != null)
 {
 //return feed
 returnFbFeedItems = fbObject.Data.Select(fbItem => new FbFeedItem
 {
 Message = fbItem.Message,
 Description = fbItem.Description,
 CreatedTime = fbItem.CreatedTime,
 PostId = fbItem.Id,
 Picture = fbItem.Picture,
 Link = fbItem.Link,
 Name = fbItem.Name,
 FromName = fbItem.From.Name,
 FromId = fbItem.From.Id,
 StatusType = fbItem.StatusType
 }).ToList();
 }
 }
 }
 catch (Exception ex)
 {
 Console.WriteLine("Error : " + ex);
 }
 return returnFbFeedItems.ToList();
 }
 }
 }

Next, you have to create a controller as shown:


//Facebook controller
 public class FacebookController : ApiController
 {
 public ICollection< FbFeedItem > GetFacebookFeed(string fbUserId)
 {
 return Integration.Facebook.Helper.ReadFeed(fbUserId);
 }
 }

Then you have to publish the API to your Azure instance, here is test site url: https://{enteryoursite}.azurewebsites.net/api/facebook/GetFacebookFeed?fbUserId={enterFbUserId}

Finally you can use this url in web page using JQuery:
Place below code to a custom javascript file, for example: /script/custom.js


 //Facebook Feed
 function _initFacebookFeed(FbUserId) {
 var fbFeed = $('#facebook-feed');
 // get facebook posts from api
 function __getFacebookPosts(callback) {
 var apiUri = 'https://{enteryoursite}.azurewebsites.net/api/facebook/GetFacebookFeed?fbUserId=';

$.ajax({
 url: apiUri + FbUserId,
 type: 'GET',
 success: function (result) {
 callback(result);
 },
 error: function () {
 //fbFeed.closest('.ms-webpartzone-cell').hide();
 }
 });
 }

// format the data returned from the facebook api
 function __processFacebookPosts(posts) {
 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
 var facebookPostsHtml = '';
 var message;
 var link;
 var description;
 var picture;
 var date;
 var post;
 for (var post in posts) {
 message = posts[post].Message;
 description = posts[post].Description;
 link = posts[post].Link;
 picture = posts[post].Picture;
 date = date.match(/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})/);
 date = date[3] + ' ' + months[date[2] - 1] + ' ' + date[1];

if (message.length > 0) {
 if ( message.length > 180 ) {
 message = message.substring(0, 180) + '...';
 }
 if (picture != null) {
 post = '

'+message+'
 '+date+'
 ';
 }
 else {
 post = '
 '+message+'
 '+date+'
 ';
 }
 facebookPostsHtml += post;
 }
 }
 facebookPostsHtml = '
 '+facebookPostsHtml+'
 ';
 return facebookPostsHtml;
 }

// get facebook posts and add them to the facebook UI
 __getFacebookPosts(function (facebookPosts) {
 fbFeed.html(__processFacebookPosts(facebookPosts));
 });
 }

Then create a web page and add below snippet:


//Facebook Feed


<div id="facebook-feed">
</div>

<script>
 //init facebook feed
 _initFacebookFeed("{enterUserId}");
</script>

Once you save the page, you will see the 20 recent posts loaded on the web page.
Happy Coding…Hope you like this post!!! Please share or comment if you like it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s