Monday, January 31, 2011

Facebook Connect Application Login Now Simple!

Writing a Facebook Connect application can be done in about half an hour using the newly updated Javascript API. No more server side code required! Here are the steps:

1. Setup a Facebook applicaiton
Go to http://www.facebook.com/#!/developers/ and click on the 'Set Up New App' button to setup a new application. On the about page, enter the application's name and a short description. On the 'Web Site' tab, enter the URL of the web domain that will serve the web page you will put your login box on. Copy the 'Application ID' from this same tab. Click on 'Save Changes'.

2. Add the Facebook javascript library to your web page
Place the following div and script on your web page. The div won't actually display anything, it's just to bring in the Facebook code. I place it at the bottom of my web pages:




3. Initialize the facebook library with your application ID
Execute the following line of code somewhere in your page's javascript.
FB.init({appId: '105604822850082', status: true, cookie: true, xfbml: true});

4. Add the facebook login button to your html
Insert the html below into your page where you would like to see the login button displayed:

Login with Facebook


5. Listen for and respond appropriately to facebook login events
//Listen for the user to login and then customize
FB.Event.subscribe('auth.login', function(response) {
// do something with response
fb_setup();
});

//If the user is already logged in and connected, then get rid of the login button
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
fb_setup();
} else {
// no user session available, someone you dont know
}
}, true);


function fb_setup(){
FB.api('/me', function(user) {
if(user != null) {
document.getElementById('fblogin').innerHTML = '';
//alert(user.name);
var image = document.getElementById('fbimage');

image.innerHTML = ''
var name = document.getElementById('fbname');
name.innerHTML = user.name
login_user = user.id;
login_name = user.name;
}
});
}

6. You're Done!
The code above was adapted from the Facebook Developer documentation at: http://developers.facebook.com/docs/reference/javascript/fb.getloginstatus/ The documentation is getting better all the time.

For a complete working example, you can check out a flash card application I made for studying German 111 at NMSU. I got tired of having to login repeatedly to save my scores, and added a Facebook login button to let Facebook handle that work.
http://copaseticflows.appspot.com/examhelp/flashgb.html

Questions or comments? Please leave them below!

No comments: