Mirroring Facebook posts on your website using .Net Core

If you have an active Facebook business page, you can use your posts to that Facebook page to make your website more active too. It is useful to be able to mirror the last couple of Facebook posts to your website. Previously, Facebook did not require that you apply for any special permissions to read your posts, but now special permissions are needed. In addition, you will have to use the access token for a specific user instead of the access token for the app itself. To get started, make sure you have created an app using developers.facebook.com. You will need properties from this app.

Permissions needed

To read the posts from your Facebook page, I used the permissions pages_show_list and manage_pages. You will have to request these permissions using the Facebook app request process.

Get the user access token and the page id

In your controller, add the following.

ViewBag.fb_page_id = "12345"; 
ViewBag.user_access_token = abc123.......";

The Facebook page id is the id of the page from which you are extracting the posts. Facebook provides instructions on finding the id of your page .

You will also need the user access token. Note that there are multiple access tokens in Facebook. You need specifically the “user” access token. You can get the user access token from the app settings. You may need to create a system user. The user access token is the trickiest part of this because it expires. Facebook applies different rules for different platforms.

Extending the life of the user access token

When you get your access token for your selected user from the Facebook developer site, you will have an access token of short duration. You can extend this token to 60 days by executing the following request.

https://graph.facebook.com/{graph-api-version}/oauth/access_token?
         grant_type=fb_exchange_token&
         client_id={app-id}&
         client_secret={app-secret}&
         fb_exchange_token={your-access-token}

Although, I have stored the user access token in a ViewBag on the controller, there are other and better ways to make these available to your view. However, for this app, I used a ViewBag and the .Net program will have to be modified and recompiled when the access token expires after 60 days.

Use a partial view to display the posts

I created my mirrored Facebook posts as a partial view, facebookStories.cshtml, that I placed in the Shared Views folder. Include the following code wherever you want to see this partial view.

@await Html.PartialAsync("facebookstories")

Pull the posts by starting with a model

Create a class for each of your posts and store it in your Models folder.

namespace todaydataCore.Models
{
    

    public  class post
        {
            public string full_picture {get;set;}
            public string description { get; set; }
            public string created_time { get; set; }
            public string link { get; set; }
            public string name { get; set; }
            public string id { get; set; }
        public string message { get; set; }
        }
    }

Functions needed to pull the posts

I placed the functions needed to pull the posts directly in the view. The complete code for the functions is included below. I will just highlight the main ideas of this code.

Pull the posts from Facebook async with Task

I created an async Task called getPosts. This Task calls another async Task that generates a request using the Facebook Graph API to get a Json file of the posts in the form of a string. It then uses the Json.Net framework for C# from NewtonSoft to manipulate this Json string. You will need @using Newtonsoft.Json.Linq at the top of your view.

Working with the json string

The serialized json file is read into a json.net object, JObject. We use that json object to get its children and then loop through the children, converting each child, a json object token into a .Net Object of type post.

Having created getPosts(), our view’s top code calls this function so that we can display the posts, looping through the list. For example, you can incorporate the data item “link” into your website layout by using @post.link and include the data item “description” with @post.description all while looping with @foreach.

Complete code for functions

@functions{
    private async Task<IList<todaydataCore.Models.post>> getPosts()
    {
        Task<string> tget_Posts_as_Json = get_Posts_as_Json();
        string stringFBJson = await tget_Posts_as_Json;

        // convert the json string of posts into the List model
        IList<todaydataCore.Models.post> posts = getPostsToList(stringFBJson);
        return posts;
    }

    async Task<string> get_Posts_as_Json()
    {
        string FBUrl = "https://graph.facebook.com/v3.0/" + ViewBag.fb_page_id + "?access_token=" + ViewBag.user_access_token + "&amp;fields=posts.limit(3){full_picture, description, message, created_time,link,name}";
        HttpClient client = new System.Net.Http.HttpClient();
        return await client.GetStringAsync(FBUrl);
    }


    private IList<todaydataCore.Models.post> getPostsToList(string stringFBJson)
    {

            IList<todaydataCore.Models.post> posts = new List<todaydataCore.Models.post>();
            // after getting the facebook json, you can create a partial json fragment with just what you want
            JObject obj = JObject.Parse(stringFBJson);
            // get JSON partial result objects

            IList<JToken> data = obj["posts"]["data"].Children().ToList();

            // for each jtoken convert to post object
            foreach (JToken dataItem in data)
            {
                todaydataCore.Models.post thispost = dataItem.ToObject<todaydataCore.Models.post>();
                posts.Add(thispost);
            }
            return posts;
    }


    //end of function
}

Leave a Reply

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