Welcome to Pakt!
How to add Facebook Connect to your website using the PHP API
Logo
Difficulty:
Progress:
Step 21
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 22

Introduction

Facebook Connect allows web developers to leverage the Facebook social application for their own off-Facebook applications. This tutorial will walk you through setting up a new Facebook application for use with Connect and provide some examples on how to use the Quick Start Facebook Connect PHP API library.
Step 1
Setting up a new Facebook Application
Login or Signup to track your progress
You first need a Facebook Platform API key for your site. Follow these steps to create an application with the Facebook Developer application.
  1. Go to http://www.facebook.com/developers/createapp.php to create a new application. You must be logged into Facebook to create an app.
  2. Enter a name for your application in the Application Name field.
  3. Accept the Developer Terms of Service, then click Save Changes.
  4. On the Basic tab, keep all of the defaults, except enter a Callback URL. This URL should point to the top-level directory of the site which will be implementing Facebook Connect (this is usually your domain, e.g. http://www.example.com, but could also be a subdirectory).
  5. Take note of the API Key and Secret Key, you'll need them to access Facebook Connect.
  6. Click the Connect tab. You should include a logo that appears on the Facebook Connect dialog. Next to Facebook Connect Logo, click Change your Facebook Connect logo and browse to an image file. The logo can be up to 99 pixels wide by 22 pixels tall, and must be in JPG, GIF, or PNG format.
  7. If your site is going to implement Facebook Connect across a number of subdomains of your site (for example, foo.example.com and bar.example.com), you need to enter a Base Domain (which would be example.com in this case). Specifying a base domain allows you to make calls using the PHP and JavaScript client libraries as well as get and store session information for any subdomain of the base domain. For more information about subdomains, see Supporting Subdomains In Facebook Connect.
  8. Click Save Changes.
Step 2
Create Cross-Domain Communication Channel File
Login or Signup to track your progress
You will need to create a cross-domain communication channel file called xd_receiver.htm and place it in a directory relative to the callback URL.

For example, let's say you're using http://www.example.com/ as your callback URL, but you want to store your Facebook Connect files in their own subdirectory, say http://www.example.com/connect. You should create the xd_receiver.htm file in the directory from where you'll be serving your Connect Web pages (http://www.example.com/connect in our example).

Below is an example of a cross-domain channel file ...

<!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" mce_src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js" type="text/javascript"></script>
</body>
</html>
c
Without a Cross-domain channel file, facebook will not be able to communicate correctly with your server.

You have the option of calling the file anything you want as long as you specify the correct file name in the FB.init method.
Step 3
Download API library
Login or Signup to track your progress
In order to follow the next steps, download the Quick Start Facebook Connect PHP API library.

This library includes the official facebook php api http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz plus some additional classes and functions to help you get started faster.
To see this optimized library in action visit http://pakt.com/scripts/facebook/connect/
t
Once you have downloaded the library, place the files on your web server.
Step 4
Setup Template Bundle
Login or Signup to track your progress
In order to view the demo file that comes with the library, you will need to register a Template Bundle on the Facebook Developer's Test Console.

A template bundle tells facebook how to display the data that you are sending to the feed. An application can have multiple Template Bundles as well as supports 'one line stories', a slightly longer 'short story', and a more verbose 'full story'. You can post links and images to feed stories as well.

You can use the sample template data to fill out the Template Bundle form found in the lib/config.php file.
Step 5
Configure Files
Login or Signup to track your progress
In the "lib" folder open config.php and enter the information as specified.
If you have entered the configuration data accurately, you should be able to run index.php in the application root folder
Step 6
View demo
Login or Signup to track your progress
Taking a look at index.php from your server application folder in a browser, it demonstrates some of the common functions you might use with Facebook Connect. For example, getting and setting a user's Facebook Status, posting a feed story, viewing all a user's friends, and viewing which friends have "connected" or not "connected" to your application.
Step 7
Inspecting index.php
Login or Signup to track your progress
As you can see with the code for index.php, it is very easy to accomplish the aforementioned facebook functions. In the next step, we'll look at the pieces a little closer.
<?php
include_once 'lib/config.php';
$user = User::fbc_getLoggedIn();
($user) ? $fb_active_session = $user->fbc_is_session_active() : $fb_active_session = FALSE;
if (!$user) {
// DISPLAY PAGE WHEN USER IS NOT LOGGED IN TO FB CONNECT
echo render_header($user);
echo render_logged_out_index();
echo render_footer();
exit;
}
// USER CONNECTED TO APPLICATION
if ($user->fbc_is_facebook_user()) {
if ($_POST["comment"] != "") {
// PUBLISH STORY TO PROFILE FEED
$template_data = array(
'post-title'=>idx($GLOBALS, 'sample_post_title'),
'post-url'=>idx($GLOBALS, 'sample_post_url'),
'post'=>$_POST["comment"]);
$target_ids = array();
$body_general = '';
$publish_success = $user->fbc_publishFeedStory(idx($GLOBALS, 'feed_bundle_id'), $template_data);
if ($publish_success) { $publish_result = "Published story via PHP to your profile feed!"; } else { $publish_result = "Error publishing story!"; }
}
if ($_POST["status"] != "") {
// PUBLISH STORY TO PROFILE FEED
$status_success = $user->fbc_setStatus($_POST["status"]);
if ($status_success) { $status_result = "Updated your status via PHP!"; } else { $status_result = "Error updating your status!"; }
}
echo render_header($user);
// SHOW FACEBOOK STATUS
echo render_status($user, $status_result);
// POST FEED TO PROFILE
echo render_feed_form($user, $publish_result);
// SHOW ALL FRIENDS
$friends = fbc_get_all_friends($user, TRUE);
echo render_friends_table_html($friends, 0, 10, "fbconnect_friend", "All Friends");
// SHOW ALL CONNECTED FRIENDS TO APPLICATION
$friends = fbc_get_connected_friends($user, FALSE);
echo render_friends_table_html($friends, 0, 10, "fbconnect_friend", "Connected Friends");
// SHOW ALL UNCONNECTED FRIENDS TO APPLICATION
$friends = fbc_get_unconnected_friends_xfbml($user, TRUE);
echo render_friends_table_xfbml($friends, 3, 5, "fbconnect_friend", "Unconnected Friends");

echo render_footer();
} else {
echo render_header($user);
echo render_footer();
}
?>
c
Step 8
Authenticate user
Login or Signup to track your progress
The following code verifies if the user has an active facebook session associated with your application. As you can see this is performed before any presentation layer code is rendered to the user.
$user = User::fbc_getLoggedIn();
($user) ? $fb_active_session = $user->fbc_is_session_active() : $fb_active_session = FALSE;
c
If you decide on a purely facebook user authentication method, this should work fine. Otherwise, you could use this as a piece of your overall authentication.
Step 9
Un-logged-in users
Login or Signup to track your progress
This code is diplayed when a user has an inactive or non-existent Facebook connect session. The code presents the user with an option to log into Facebook/your Facebook Application
if (!$user) {
// DISPLAY PAGE WHEN USER IS NOT LOGGED IN TO FB CONNECT
echo render_header($user);
echo render_logged_out_index();
echo render_footer();
exit;
}
c
Step 10
Setting Extended Permissions
Login or Signup to track your progress
In order to use the Facbook PHP API to update a user's status and post feed stories you must have the user acknowledge an acceptance of status_update and offline_access extended permissions. See http://wiki.developers.facebook.com/index.php/Extended_permissions for more information on Facebook extended permisssions.

The current list of extended permissions are email, offline_access, status_update, photo_upload, create_listing, create_event, rsvp_event, sms, video_upload, create_note, share_item.

There are two html buttons in the demo that launch the extended permissions dialog.

The following PHP code will check a user's 'status_update' extended permission state.
$user->fbc_getExtendedPermission('status_update');
c
If a user does not have the extended permission set, you would call the following javascript function to launch the dialog ...
FB.Connect.showPermissionDialog('status_update', function(accepted) { window.location.reload(); } );
c
Once the permission has been accepted, this javascript function will reload the page to ensure the correct user state is being used by your application.

Conclusion

Using this API library, you can access the Facebook social application using only a few lines of code and help reduce the amount of time required to convert your web application to a Facebook Connect enabled application. Please check out the Facebook developer wiki http://wiki.developers.facebook.com/index.php/API for additional supported methods.

Links

Disclaimer - Please use your best judgement when taking the advice of others. Please consult a professional if you are concerned about performing tasks that could endanger your health or the health of others. Pakt does not certify or warrant the legitimacy or safety of the information submitted by users.

The content provided on this page is copyright of Pakt, LLC unless otherwise specified. Progress tacking and tutorial mentoring are patent pending.
My Mentoring

Ask for Mentor