2010年5月10日 星期一

Add Facebook Connect Button to your web site

This article describes how to add a Facebook Connect button to your web site.
I've implemented this function in the following demo site :

http://easyhangout.appspot.com/

The steps for adding "Facebook Connect Button" are as follows:

1. Apply a Facebook Developer account first by visiting this URL: http://www.facebook.com/developers/.

I will not repeat the details here since there are a lot of articles about this topic. For more details, pls visit this site.

2. Copy the xd_receiver.htm file to the root of your domain, this file will be called by Facebook and redirect the login session to your application.


<!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" >
<head>
<title>Cross-Domain Receiver Page</title>
</head>
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?v2" type="text/javascript"></script>
</body>
</html>


3. Change the HTML tag of your login page:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">


4. Add the following javascript in your login page:

<body>
....
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript">
</script>

<fb:login-button onlogin='window.location="/YOUR_SERVLET?para=1";' length="long" ></fb:login-button>
<script type="text/javascript">
FB.init("YOUR_API_KEY", "xd_receiver.htm");
</script>
....
</body>


5. This step is very important, you have to define the Base Domain in the Facebook Application Setting, otherwise, the event "onlogin" of the Connect Button will not be triggered and the popup Login form will NOT be closed.
For example, if your app URL is :

http://abc.appspot.com/ABCServlet?para=1

then, the Base Domain is :

abc.appspot.com




6. Now, when the user click the Connect Button, a login form will pop up and the user will input name and password. If successful, the login form will be closed and your application servlet will be called.



There will be an authentication token generated and you can retrieve it from the HttpServletRequest object:

String token = request.getParameter("auth_token");

After you have received the token, you can use a Facebook REST library to call the Facebook platform API and I will not repeat the details here.

To download the library, you can goto:
http://code.google.com/p/facebook-java-api/

沒有留言:

張貼留言