NOV 9
Code Games Javascript

There are a few ways you can handle authentication when making an HTML5 Facebook app. Facebook has relatively mature APIs in both PHP and Javascript for interacting with its backend Open Graph API. Whether you want to go PHP or Javascript depends on your comfort with the language and the resulting medium. For apps that will use Facebook as a merely a login system and live on a non-Facebook page, PHP seems to be relatively painless. ┬áBut for apps that will live solely on Facebook pages, the Javascript API is essential (if you’re curious why, check beneath the code).

The code (heavily commented) is as follows:

<html>
	<head>
		<title>JS Test</title>
		<script src="//connect.facebook.net/en_US/all.js"></script>
  		<script src="http://code.jquery.com/jquery-latest.js"></script>
	</head>
 
	<body>
		<div id="fb-root"></div>
		<script>
			window.fbAsyncInit = function() {
				FB.init({
					appId      : 'YOUR APPLICATION ID', // Insert your App ID here
					status     : true, // check login status
					cookie     : true, // enable cookies to allow the server to access the session
					oauth      : true, // enable OAuth 2.0
					xfbml      : true  // parse XFBML
				});
 
			    /*** Initialization code here ***/
 
				// Get the users login status
				FB.getLoginStatus(function(response) {
					if (response.authResponse) {
						// Logged in and connected user, someone you know
						console.log("User is logged in");
						loginToFacebook();  // Pass directly to login so we can get the users name and email (at this point we only have the facebook ID)
					} else {
						// No user session available, someone you dont know
						console.log("User is NOT logged in");				
						showLogin();
					}
				});
			};  // End Facebook async login
 
		  // Load the SDK Asynchronously
			(function(d){
				var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
				js = d.createElement('script'); js.id = id; js.async = true;
				js.src = "//connect.facebook.net/en_US/all.js";
				d.getElementsByTagName('head')[0].appendChild(js);
			}(document));
		</script>		
 
		<script>
			/*** USER TRIGGERED JS ***/
			var username = '';
			var userid = '';
			var userEmail = '';	
 
			function loginToFacebook() {
				console.log('Login to facebook');
				// Login
				FB.login(function(response) {
					if (response.authResponse) {
						console.log('Welcome!  Fetching your information.... ');
						FB.api('/me', function(response) {
							console.log('Good to see you, ' + response.name + ', ' + response.email + '.');
							username = response.name;
							userid = response.id;
							userEmail = response.email;
 
							showLobby(response.id, response.name, response.email);
						});
					} else {
						console.log('User cancelled login or did not fully authorize.');
						showErrorScreen();
					}
				}, {scope: 'email'});
			}
 
			function showLogin() {
				// Get DOM elements to show/hide
				var lobby = document.getElementById("lobby");  
				var login = document.getElementById("login");  
 
				lobby.style.display = 'none';  // Show the lobby
				login.style.display = 'block	';  // Show the lobby
			}
 
			function showLobby(facebookID, name, email) {
				console.log('showLobby -> ' + facebookID, name, email);
 
				// Get DOM elements to show/hide
				var lobby = document.getElementById("lobby");  
				var login = document.getElementById("login");  
				lobby.style.display = 'block';  // Show the lobby
				login.style.display = 'none';  // Show the lobby				
			}
			function showErrorScreen() {
				console.log('showErrorScreen');
			}
			</script>
 
		<div id="login" style="display:none;">
			<a href="#" onClick="loginToFacebook()">Login to the application</a>
		</div>
 
		<div id="lobby" style="display:none;">
			Game screen goes here
		</div>
	</body>
</html>
One Note:

You might be asking yourself – Why is there a login screen at all? Can’t you just trigger the login method if you don’t get back any information on the user? Unfortunately, you can’t (that violates security parameters within the site).

Testing

After you get everything rolling with your code, there are eight use cases you should be aware of when testing your application.

HTTP

  • User is logged in to Facebook
    • User has authorized the application
    • User hasn’t authorized the application
  • User is not logged in to Facebook
    • User has authorized the application
    • User hasn’t authorized the application

HTTPS

  • User is logged in to Facebook
    • User has authorized the application
    • User hasn’t authorized the application
  • User is not logged in to Facebook
    • User has authorized the application
    • User hasn’t authorized the application

Why the Javascript API is essential

Essential? Sounds so – absolute. Here’s why.

Assume you’ve got a Facebook app that you want surfaced solely on apps.facebook.com/myBitchinApp. That app has to be hosted on some personal domain somewhere – probably something like http://www.myRadSite.com/myBitchinApp/. The annoying thing about the PHP API is that when you do the authentication call (from either the Facebook or your personal domain), the redirect_uri parameter will *always* redirect the user back to the personal domain. If you try to set the redirect_uri parameter manually back to apps.facebook.com/myBitchinApp, you’ll find you get a Facebook error that you don’t have access to the domain. Boo hiss.

One Response to HTML5 FACEBOOK APP AUTHENTICATION VIA JAVASCRIPT
  1. Jugi Deniro wrote:

    where do i get that

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>