Tuesday, January 4, 2011

Quick and Easy Facebook Integration

I figured I'd take a break from the soapbox-style posts I often write and take a step back to another of the original ideas regarding this blog... Sharing something quick and easy and potentially cool to do in code.  This one comes inspired by a handful of Stack Overflow questions I've answered on the subject, and may indeed serve as a simple place to point users to if they ask more similar questions in the future (unless, of course, it's an actual duplicate question and can just be referred to the previous question, as is the SO way).

Facebook development and integration is nothing new.  Come on, man, everybody's doing it.  Don't you want to be cool?  Indeed, while I'm sure that a lot of people/companies are doing this, and while it's evident that a lot of them meet with a great deal of success in the matter, my experience as of late seems to indicate that many people/companies toy with the idea but have no clue as to how to actually implement it.  Well, product folks can undoubtedly come up with all the marketable and sellable ideas they want in this matter, but success or failure may hinge on the simple idea of know how the Facebook platform actually works.  It's one thing to say "we need more Facebook on our site!" and it's another thing entirely to come up with an actual workable solution.

To that end, let's take a look at some very basic Facebook integration.  You may or may not have heard of their Graph API, which is basically a JSON service for getting information our of their "social graph" (the various data objects they track and the relationships between them).  Getting that data, once you have permission that is, is actually very simple.

First, you need to create your application on Facebook.  (This step is a lot easier than it sounds.)  Basically, give Facebook some simple information about your website and how it'll be integrating.  Start out with something simple:
Facebook has some restrictions on the format of the Site URL, I usually just give it a folder where I'll be putting my Facebook-ish stuff on the site.  The page you ultimately want to reach in this process is this one:
Congratulations, you now have a "Facebook app."  Now what are you going to do with it?  Well, keep in mind again that the approach I'm taking here is for interfacing with the Facebook Graph API from your website.  You know, visitors come to your site, they use their Facebook account (since they're most likely logged into Facebook in another tab) to "Like" your site, you harvest their data and spam their friends, etc.

So now you need to add some Facebook stuff to your site.  Note the sample code in the preceding screen shot above.  This code does a couple things:
  1. Initialize your page with your Facebook app.
  2. Present the user with a Facebook login button.
  3. Present the user with a Facebook "like" button.
Let's take a look at the JavaScript first.  It's doing two things.  First, at the bottom, it's writing to the DOM a script tag to load the Facebook JavaScript code.  Second, above that, it's binding an initialization function to a Facebook window load event.  You supply it your application ID, pass other arguments per its documentation, and your page is now ready to interact with Facebook (or, rather, allow the client-side user to interact with Facebook).

Next, the login button.  This is using FBML, which will be handled by their JavaScript code and translated into what it needs to be on the page.  You can create mildly a customized login with a few given parameter, but the basic thing you need to do here is ask the user for permission to access their Facebook data.  Take a look at the "Login" section of this page (recently updated).  The simplest approach, which is what we're doing here, is to ask the user for some permission to their data.  This is done by decorating the FBML login tag with some permission request modifiers.

This is where the user grants or denies your site access to their Facebook data.  If they deny you, then your work ends here.  But if they allow you to access the data, then this is where you'll be able to send requests to Facebook on their behalf.  You can go so far as to, if permitted, post stuff to their wall or send messages to their friends, etc.  But, again, we're sticking with the basics here.  We want to see the Graph API data.

Once permission is granted, Facebook writes a cookie to the user's computer which you can use.  Remember that "application secret" value from before?  You use that to decrypt the cookie.  Take a look at this PHP code (which can still be found here, though they change their documentation a lot):
Notice how it's using the application secret string to decrypt the user's cookie, and from that cookie pull a critical piece of information... the access token.

(Note: You must never share your application secret with anybody.  Don't render it to the page, don't use it anywhere but your protected server-side code.  Anybody who has this value can pretend to be your application and can spoof users and Facebook as you.  The access token you pull form a user's cookie should also be treated with this level of secrecy, with one exception.  You can render that to the page, since you're pulling it from the user's cookie and just showing it back to the user.  However, proper use of SSL is, as always, recommended.)

Note how the PHP code then makes a simple Graph API request to get the user's name.  In this case, the "me" in the Graph API URL is being interpreted by Facebook as the user who owns the access token.  There are a number of ways to access a particular user's node on the graph, this is just one of the shortcuts.  But basically, this is what you're looking for.

These Graph API requests are just URLs with query string parameters, and they just return JSON.  (The data structure is generally fields of data with the occasional object field which has its own ID and can be requested as its own node on the graph.)  So the requests can just as easily be made from your JavaScript code on the client-side or your server-side code.  Each has their advantages and disadvantages (I prefer to do as much in the JavaScript code as possible in this case):
  • Client-Side: You offload some of the work to the client's machine.  The performance implications here are obvious, but for me the main one is that the client's browser is probably better suited for multiple parallel requests than your server code.  Let it handle it.  Otherwise, you risk have your client sitting and waiting, even if just for a moment or two, while you make requests on their behalf.  Just do it in JavaScript and let their browser handle it.  Also, one big thing to note here is that you can tell your users that their data never actually touches your server.  It's all from Facebook, you never see it.  People like privacy policies that can make claims like that.
  • Server-Side: Once you have that access token, you can continue to make requests for data on their behalf.  So in an offline process you can start harvesting.  (Yes, it pains me to say that.  Let me explain...)  You can, say, loop through their friends list and grab email addresses (assuming their friends allow that, they have privacy settings too) to compare with your local data store.  Then you can prompt the user with such gems as "I see your friends are already members of this site, would you like to say hello?" or "Your friends haven't signed up for this site, click here to invite them."  And so on.  Act responsibly, of course.  The user trusts you with their data, don't betray that.
That's about it.  As I'm sure you saw in some of the links, there's a lot more that can be done.  A new addition to the documentation (new as in added this week, I hadn't seen it until I started writing this) is the registration stuff related to the Facebook login button.  It sounds like it can be used to facilitate users registering on your site by pre-populating fields with data they already have on Facebook.  (Of course, I recommend looking into OpenID and OAuth for stuff like that, as Facebook supports both.)  There's also quick little social plugins and other widgets you can add to your site.

Keep in mind that the Facebook documentation changes all the time.  They're known to have broken internal links, pages which link to themselves, etc.  But there is a lot there.  Once you're started with something as simple as the above example, the learning curve flattens considerably and you can branch out a lot through their FBML, JavaScript, and Graph integration options.


  1. thanks for the cod but i can`t copy-paste it

    1. Did you follow the links to the Facebook documentation? The code can be copied and pasted from there, and indeed that should be your first point of reference for updated code and documentation since this post is over a year and a half old. Facebook may have changed something important since then.