Facebook Connect Integration
By Erik Smith (Shuffle Interactive)
Modified with permission by Ryan Merket

Shuffle Interactive

This document will describe the process of integrating Facebook Connect from a technical perspective, and provide all the resources and code examples needed to accomplish this.

Creating the Facebook Application.

Each Connect site functions in the same manner as an application; for this reason, the first step in the Connect process is to log on to Facebook and create a new application.

  1. Go to http://www.facebook.com/developers/. If you're not already a developer, you may be asked to add the developer application.
  2. Next, click the "Set Up New Application" in the top right corner.
  3. Add the application name (this will be visible to users), so it should be called something like "YourSite.com" and accept the terms of service.
  4. Once you've completed this, you will now to editing your application settings.
    1. To edit your application in the future, you can visit http://www.facebook.com/developers/createapp.php#/developers/apps.php
  5. Under the Basic tab, it's important to note, for now, the application key and application secret provided to you. These will be used soon.
  6. Under the Connect tab, provide the following information:
    1. Connect URL: stage.YourSite.com
    2. Base Domain: YourSite.com
  7. Finally, save the changes, and we're done!

Integrating Facebook Connect

Facebook has client libraries for both PHP and Javascript. The Javascript library is hosted remotely on their servers, and is primarily used for installing Connect. The PHP library, is of course, on our host, and is usually used to make FQL calls, get user's ID, information, etc.

  1. First, we need to alter the HTML namespaces to allow us to render FBML, Facebook's markup langage. Begin by adding or altering the HTML tag to any page that will pertain to Facebook Connect:
  2. Next, bring in the Javascript API feature loader by adding this just before the closing body tag. Then, you need to initiate the connection with Facebook by including the following directly after the feature loader include:
    1<script type="text/javascript">
    2    FB.init("YOUR_API_KEY_HERE", "http://stage.YourSite.com/xd_receiver.htm");
    3</script>
  3. Next, we need a way for Facebook to communicate directly with your site; so, we'll add their cross-domain communication channel file. Take the following code and place it in a new file called xd_receiver.htm.
    1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <body> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script> </body> </html>

Rendering FBML

Now that we've successfully connected all the components for Facebook Connect, we can test out our installation by trying to render some FBML. To do so, we'll use the FBML login button – the same button we will use to prompt users to connect to your site using Facebook.

To render the element, use the following code:

1<fb:login-button></fb:login-button>

If you see the following button, the installation was successful!

Step 4: Prompt the User to Connect

Now we can begin the actul user-flow by prompting the user to Connect to your site.

To do so, add the same code above to where you'd like to prompt the user. The following attributes can be added to alter the appearance and functionality.

fb:login-button

Functionality

FBML tag Used to prompt users to "allow" a Connect site to gather basic information on the user.

Commonly Used Attributes


To see a full set of attributes, see the Facebook Wiki: http://wiki.developers.facebook.com/index.php/Fb:login-button

It's common practice to use a javascript redirect function in the onlogin attribute; this script should redirect the user to a PHP handler page.

This would look something like:

1<script type="javascript">
2    function fbHandler(){
3        location.href = 'fbHandler.php';
4    }
5</script>   
6 
7<fb:login-button onlogin="fbHandler();"></fb:login-button>
8    

Reading a user's ID after login can also be accomplished with the Javascript API, but is not as easily implemented, in my opinion.

Handling a Facebook User with PHP

Now, we'll assume a user has clicked the login button, accepted the Connection, and is being redirected to fbHandler.php (Note: the file name is unimportant and can fit with your current naming standards).

On fbHandler.php, we want to determine what to do with the user. The basic options will be:

Including the Facebook PHP API

So, to actually use the fbHandler.php, we need to bring in the PHP API.

The following files should be uploaded on the server (probably in a "fb" or "facebook" folder within your library folder).

I would also suggest creating your own FB wrapper class; I use something like this to make things simple:

It's only required to include to facebook.php file, the REST library is included by facebook.php.

01class fb {
02    public function __construct(){
03        $this->api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
04        $this->api_sec = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
05        if(class_exists('Facebook')){
06            $this->fb = new Facebook(self::$api_key, self::$api_sec);
07            $this->client = $this->fb->api_client;
08            try {
09                $this->fid = $this->lib->get_loggedin_user();
10            } catch(Exception $e){
11                $this->fid = false;
12            }
13        }
14    }

Basically, I use this to determine each time the Facebook API is called whether or not we have a valid session for the user. You'll notice the over-use of try/catch; this is because if any session-required part of the API is called, the API will throw an error.

From here on out, I'll refer to the individual parts of the API so as not to restrict it to any one particular programming preference.

fbHandler.php

Initiate the Facebook API

1$fb = new Facebook("API_KEY", "API_SECRET";

Get a User's Facebook ID

1$fid = $fb->api_client->get_loggedin_user();

Get a User's Facebook Basic Information

1$fb->api_client->users_getInfo($fid, array("first_name", "last_name", "current_location", "sex", "pic_square"));

At this point in the process, we want check the user authentication via a Facebook ID. The process might look something like:

The simplified version looks like:

1$fb = new Facebook("API_KEY", "API_SECRET";
2$fid = $fb->api_client->get_loggedin_user();
3//$check = $user->get_via_fid($fid);
4if($check){
5    // login and redirect
6} else {
7    // save and redirect
8}