March 3, 2010

Enable your site with Facebook Connect.

Recently i worked on integrating facebook connect on site so visitors can login with their facebook id to give comment on article .Incorporating facebook connect is advatageous to both the commenter and site owner .As commenter gets to publicize his facebook profile and get credit for good comments and site owner gets authenticate commenter and their site becomes more resourcefull and active .

Create an Facebook Application:-
First of all one needs to create an application on facebook so that people can authenticate with it in order to login on third site.
To create an go here http://www.facebook.com/developers/createapp.php. Give an appropriate App name and create the application.You will be presented with application settings page with multiple tabs.

1) In basic tab note down the app key and app secret (you will need it when you download php library for application from here **) fill out the other info as required .
2) In Authentication tab select user / pages as per your need .so who can install the application .
3) In Publihsre tab fill out the info if needed as per requirement.
4) Canvas tab is the imporatant setting for your application to work properly

In Canvas Page URL add appropriate name which will appear in application URL .
In Canvas Callback URL - Add the URL , on your web server where you will be hosting the facebook application. Do not forget to add '/' at the end of URL.
In Post-Authorize Redirect URL - Add the URl for the page where you want facebook users to get redirected to after they authorize you application access to their profile.
In Canvas Settings - choose Render Method as FBML or framesdepending on the type of application you want to host. If you don't have much functionality but informational application use frames else FBML .To learn more on FBML check here http://wiki.developers.facebook.com/index.php/XFBML. Add othetr info as per you likeness.

5) In Connect tab - Add Connect URL. it will be the root of your domain where you must copy xd_receiver.html. This is cross domain channel file used by facebook JavaScript Client Library to establish communication between your Web pages and Facebook pages.T file can be downloaded from here http://www.somethingtoputhere.com/xd_receiver.htm

Other tabs can be filled as per your needs and doesnt affect facebook connect functionality so not discussed here.

Now you application is ready and you have application key and secret noted from Basic tab in application settings page.

Install PHP library at canvas page URL:-

Download the php library from http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz and copy the folders php and footprints to Canvas Callback URL you set in application settings page under canvas tab.

You may add following code in index.php in your canvas callback URL to check if faceboook application is working properly


require_once 'php/facebook.php';

$appapikey = 'Your App Key';
$appsecret = 'Your App Secret';
$facebook = new Facebook($appapikey, $appsecret);
$user_id = $facebook->require_login();

// Greet the currently logged-in user!
echo '<p>Hello,<fb:name uid=\"$user_id\" useyou=\"false\" />!</p>';

// Print out at most 25 of the logged-in user's friends,
// using the friends.get API method
echo "<p>Friends:";
$friends = $facebook->api_client->friends_get();
$friends = array_slice($friends, 0, 25);
foreach ($friends as $friend) {
echo  '<fb:profile-pic size="square" uid="'.$friend.'" facebook-logo="true"></fb:profile-pic>';
}
echo "</p>";

Adding javascript to web pages :-

Now on the web page from your web site where you want to add facebook connect you shall include this JS-

<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
Adding this JS file tells browser how to parse the facebook html tags used in page.

Now intialize the facebook javascript library.
<script type="text/javascript">
FB.init("Your App Key","http://domain.name/xd_receiver.htm");
</script>

Please add the application key and domain name in above places in javascript code.

Use this FBML code to add facebook connect icon on your web page -

<fb:login-button onlogin="facebook_onlogin_ready();"></fb:login-button>

"facebook_onlogin_ready" is the function which gets called when visitor is logged in using his facebook login.In this function you may reload the page or use ajax to fetch the visitors facebook profile details.

Following sample code fetches user profile with ajax -

var uid = FB.Facebook.apiClient.get_session().uid;
FB.Facebook.apiClient.users_getInfo(uid, ['name','first_name','last_name','email'],function(ret,ex) {


        var nameobj = document.getElementById('txtVName');
        nameobj.value = ret[0].name;
        FB.XFBML.Host.parseDomElement(nameobj);

        var webobj = document.getElementById('txtVWebsite');
        webobj.value = ret[0].profile_url;
        FB.XFBML.Host.parseDomElement(webobj);
});

In above code we use JS function from facebook javascript library "FB.Facebook.apiClient.users_getInfo" to get user details - first argument to it is user Id which we can retrieve from session using the js function "FB.Facebook.apiClient.get_session()" second argument is the profile fields we want to fetch. and third argument is the callback function which gets executed on succesfull profile fetching in which we update DOM with details .

Alternatively we can reload the page and use PHP library to fetch the profile details from facebook and prepopulate the web page with visitors details .

Use following code to fetach profile fields from facebook using php library.

$facebook = new Facebook('Your app Key', 'Your app secret');
$user_id = $facebook->get_loggedin_user();
$userObj = $facebook->api_client->users_getInfo($user_id, array('name','first_name','profile_url','pic_square'));

In order to access email like confidential profile fields you need to take extra permission from visitors which can be done by adding '{permsToRequestOnConnect : "email", }' as third argument to FB.init call .

5 comments:

  1. Pandurang, Glad to see such a clean and informative write up. Do keep writing. I am following you!

    Vivek Sathe

    ReplyDelete
  2. Hi,CAN U PLS TELL ME HOW DO I FETCH ZIP OF FACEBOOK LOGIN USER in javascript using FQL,
    currently it returns all other fields,but zip in current location is empty?

    pls suggest

    ReplyDelete
  3. Hi nitin

    you can use the following fql query to retrieve the user info after initialization of facebook JS library

    FB.Facebook.apiClient.fql_query("SELECT name,first_name,current_location FROM user WHERE uid=******", function(result, exception){ alert(result);
    });

    Remember current_location have four sub fields and zip is one of them .
    Thanks

    ReplyDelete
  4. Hi Pandurang Sir,

    Yes initially when i did this i used to get fb user zip but for the last 2 months i am not gettign this zip .is gets null i use alert("zIP IS "+rows[0]["current_location"].zip); in the function of fql query but no use.current location array has 4 fields but i get city but not zip ?
    how to make it now
    pls guide ..

    ReplyDelete
  5. Hi Nitin

    The mistake you are doing here is i think the way you access zip field

    Please try using this to get value of the field
    $row[0]['current_location']['zip']
    $row[0]['current_location']['country']
    $row[0]['current_location']['state']
    $row[0]['current_location']['city']
    $row[0]['current_location']['id']
    $row[0]['current_location']['name']

    I got the above results with this query
    $result = $facebook->api_client->fql_query("SELECT current_location FROM user WHERE uid=xxxxxxxxxxxxxxx");

    ReplyDelete