woman pointing at digital widgets of social media comment

Tips for Integrating Facebook and Twitter into Your Website

Learn about 3 approaches for integrating your web solutions with one or more social networks

You can enhance nearly any business context and nearly any software by adding social networking capabilities to it. Integrating social networks into software solutions provides a way to create new business opportunities. To integrate social networks into your web applications, you can use one of three basic approaches. First, you can just embed built-in widgets in your pages and use, whenever possible, an unauthenticated API. Second, you can use social networks to authenticate users into your site. Third, you can use a stricter form of interaction with social networks and impersonate a given user and act—well, mostly post—on the user's behalf. In this article, I'll give you a few "fast facts" about each of these approaches.

Embedding Widgets

A common scenario of this type of social networking integration is to embed timelines from Twitter and Facebook into a web app. Another common scenario is embedding buttons to like, share, or tweet some content.

Facebook and Twitter are ostensibly similar only in what they allow you to do. Facebook is easier to use than Twitter because Facebook still offers some plug-ins that you can use in an unauthenticated way. To use a Facebook plug-in, you visit the developer's page on Facebook, choose from the list the plug-in that you want to embed, configure it, and then just get the HTML to embed in the page.

Related: How to Use TweetSharp to Push Twitter Updates in an Application

For example, to embed the Like Box widget, you need know only the page name. Note that the Like Box widget is supported only on Facebook public pages and doesn't work on personal pages. Configuring the Like Box widget is easy: All you have to do is go through the wizard and set a few check boxes. You get an iframe-based piece of HTML ready to embed wherever you want in the Razor or HTML template you're using. Notice in the following sample code that by hiding faces and enabling the stream of posts, you can easily turn the Like Box into a list of Facebook posts. (This version of the iframe code has been modified for readability.)

The Like Box must be associated with an application ID, meaning that you should have a Facebook account and create an application within it. To enable the Like Box, you must select the app's ID when running the wizard. Similarly, you can add a Like or Share button and still receive an iframe to embed.

Note that the Facebook API reserves some other plug-ins that require JavaScript and HTML5 to be inserted in the host page. This is the case for the Comments box. As soon as possible in the page, you must specify the download of the JavaScript Facebook SDK, as shown in Listing 1.

In an ASP.NET MVC solution, you might consider placing this code in the layout of the page so that multiple pages can share it. Here's the markup for the Comments box:

Figure 1 shows all the aforementioned Facebook plug-ins in action in a sample Bootstrap page.

Figure 1: Facebook Widgets in Action in a Sample Page
Figure 1: Facebook Widgets in Action in a Sample Page

For a long time, Twitter exposed a search API that could be consumed by simply calling a public URL to get JSON data. A year ago Twitter discontinued this API, or rather the unauthenticated way of accessing it. Like Facebook, Twitter exposes an embeddable user timeline, but to use it you must first statically create it and associate it with a Twitter user. From the Settings page of the Twitter account that's consuming the API, you create a widget and bind it to the Twitter user whose timeline you're interested in. What you get is some markup that looks like this:

Interestingly, the Twitter website provides a richer markup that also includes the href attribute pointing to the Twitter user to display in the box. It turns out, instead, that the only thing that matters is the data-widget ID; the content of the href attribute is ignored. Figure 2 shows the embedded Twitter user timeline.

Figure 2: Twitter Timeline
Figure 2: Twitter Timeline

The Twitter timeline box contains buttons to follow, tweet, and load more tweets. There are reported issues of the Twitter timeline box not working properly on various versions of Internet Explorer (IE) but not on other browsers. Personally, I don't use the timeline on production apps; however, I have experienced the IE issues on some, but not all, demo pages I tried.

Related: How to Use the Facebook Connect API in an ASP.NET Web Application

On a project where I used the Facebook Like box extensively, I opted not to use the Twitter timeline because it is statically coupled to a Twitter user account. In the project I worked on, I needed to produce Twitter and Facebook timelines dynamically. You can do this easily with Facebook, but not so with Twitter, where I found it unmanageable to deal with thousands of Twitter widget IDs. Instead, we opted to build the Twitter timeline programmatically.

Accessing Timelines Programmatically

In 2013, Twitter retired version 1 of its public REST API used to search for tweets, stating the reason was to avoid malicious use of the API and to learn more about users. With API v1.1, you now need to be authenticated in order to programmatically read about tweets. The first step, of course, is creating a Twitter account and grabbing consumer and secret keys. Once you hold these keys, you send a first request to Twitter to get authenticated. The following code creates the authorization header that includes authentication details.

var code = String.Format("{0}:{1}",
    Uri.EscapeDataString(YourConsumerKey),
    Uri.EscapeDataString(YourConsumerSecret));
var authorizationHeader = String.Format("Basic {0}",
    Convert.ToBase64String(Encoding.UTF8.GetBytes(code)));

The authorization header must be stored in an HTTP header in a POST request addressed to "https://api.twitter.com/oauth2/token." The code in Listing 2 shows the actual request.

var authRequest = (HttpWebRequest)WebRequest.Create(OAuthUrl);
authRequest.Headers.Add("Authorization", authorizationHeader);
authRequest.Headers.Add("Accept-Encoding", "gzip");
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

In the body of the request, you write the following string as a sequence of bytes:

grant_type=client_credentials;

The JSON response you get from Twitter maps to the following C# class; the name of the class is arbitrary.

public class TwitterAuthResponse
{
    public string token_type { get; set; }
    public string access_token { get; set; }
}

The two pieces of information—access token and type—must be packaged into the successive request to actually grab the timeline of a given user. Here's the URL to call to access the timeline:

https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&count{1}"

The screen_name argument is the name of the Twitter account to access; the count argument indicates the maximum number of tweets to return. Note that this URL only returns the timeline of the user; if you want to get all tweets by hashtag, you use a different URL to do so. Refer to the Twitter documentation for more details. The code to set up the authenticated request, though, is the same. The returned JSON, of course, is not and must be parsed properly. Here is the code required to prepare the request to access the timeline.

var userContext = String.Format("{0} {1}", authResponse.token_type, authResponse.access_token);
var timelineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
timelineRequest.Headers.Add("Authorization", userContext);
timelineRequest.Method = "Get";

The response you get is a list of JSON objects that you can easily parse to a C# class using the services of the http://json2csharp.com site. Listing 3 shows some sample Razor markup to display tweets in a page.


    @foreach (var t in Model)
    {
    
    }
@t.text
@t.created_at

There's a lot more that you can do when it comes to rendering Twitter or even Facebook timelines programmatically. In particular, you might want to detect hyperlinks and hashtags and possibly expand pictures. There are also some JavaScript libraries available for rendering Twitter and Facebook timelines. As far as Facebook is concerned, the best way to embed the timeline is via the Like Box. Programmatic access is problematic unless you impersonate the user.

Social Authentication

ASP.NET MVC 5 comes with a full template that simplifies the work required to let users authenticate with your site using their Facebook or Twitter account. At the end of the procedure, Facebook and Twitter (and similarly, LinkedIn, Instagram, and Google+) return you an access token to be used as the key to impersonate the user who was just authenticated. In other words, by authenticating with your site through his or her social network account, a user grants the permission to impersonate him or her and operate on his/her behalf—for example, for posting updates. The code in Listing 4 demonstrates how to post to Facebook a message with an attached picture. The code represents an ASP.NET MVC endpoint exposed by a controller class.

public static void Post(String token, String message, String picturePath)
{
    var client = new FacebookClient(token);
    using (var stream = File.OpenRead(picturePath))
    {
    dynamic result = client.Post("me/photos",
                    new
                        {
                        message = message,
                        file = new FacebookMediaStream
                            {
                                ContentType = "image/jpg",
                                FileName = Path.GetFileName(picturePath)
                            }.SetValue(stream)
                        });
     }
}

The code in Listing 4 is based on the classes defined in the Facebook C# SDK. The language you use to query is the Graph API, and, according to the documentation, you may require a POST or a GET method call on the Facebook client object. For example, to get the photos of a given user, you'd use the following code:

var client = new FacebookClient(token);
dynamic result = client.Get("/user-id/photos");

Per the Facebook documentation, you receive a JSON stream to be parsed at your own expense. Note that what you get out of your queries is strictly related to the privacy settings of the user, including when the user is yourself.

To programmatically post to Twitter, you also need some help from an external library that hides most of the OAuth intricacies. TweetSharp is a good choice for this.

Develop Your Social Skills

For a web developer, Twitter and Facebook are the most important two social networks to integrate into your web apps. Many of the activities that a user can perform within a website lend themselves to be further pushed to those social networks—for example, by providing widgets for sharing, liking, or recommending some content or more controlled access to timelines programmatically.

Providing such programmatic access is a far more restrictive process today than it was only a couple of years ago. Today, virtually no tasks can be accomplished without authenticating through an ad hoc application and user. The sole exception to this is using widgets, if a widget is available for the kind of feature you have in mind. Authentication adds a layer of complication on top of your code, but it also might help in building your own network of loyal users. In any case, social networks get most of their power from authenticated users. If you rely on social networks, you can't avoid authentication.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish