Social Networks in Games: Playing with Your Facebook Friends

This is another article in Game Programming Gems 8, talking about accessing web services of social networks from our own games. For example, log people in using their Facebook account.

RESTful Web Service

Representational State Transfer (REST) is the predominant architecture for offering programmatic access to data stored on the web. A RESTful service is composed of a collection of resources, which are identified by a web address, such as http://example.com/resource. It is based on stateless operations, which means any state information is held in the client, so a service can scale to a large number of clients–ideal for web services.

In practice, a RESTful service works with HTTP requests. We send HTTP GET to retrieve data, and the response are usually in JavaScript Object Notation (JSON) format, which looks like this:

{“trends”:{“2009-08-23 04:00:47”:[
  {“query”:”\”Best love song?\”“,”name”:”Best love song?”},
  {“query”:”#fact”,”name”:”#fact”},
  {“query”:”#shoutout”,”name”:”#shoutout”},
  {“query”:”#HappyBDayHowieD”,”name”:”#HappyBDayHowieD”},
  {“query”:”\”District 9\”“,”name”:”District 9”},
  {“query”:”\”Inglourious Basterds\”“,”name”:”Inglourious Basterds”},
  {“query”:”\”Hurricane Bill\”“,”name”:”Hurricane Bill”},
  {“query”:”#peacebetweenjbfans”,”name”:”#peacebetweenjbfans”},
  {“query”:”#Nascar”,”name”:”#Nascar”},
  {“query”:”Raiders”,”name”:”Raiders”}
]},”as_of”:1251000047}

Authenticating a User

Normally we have to confirm a user’s identity before we gain access to data. The most basic authentication mechanism requires users to enter a user name and password, which our application sends to the web service. It requires users to trust our application not to collect passwords and abuse them for other purposes. This fear might stop users from trying out new applications.

Applications on the web have answered this need by offering authentication mechanisms based on forwarding. When logging into an application, users will be forwarded to the login page of the account provider and enter user name and password there. The application will never see user’s credentials, but will only receive a confirmation of whether the login was successful.

Facebook Login

Let’s try the Facebook Login on a web page. There are 4 steps:

  1. Set Redirect URLs.
  2. Check the login statues.
  3. Log people in.
  4. Log people out.

The first step can be done in Facebook App Settings. It ensures Facebook login page only responses to calls from valid URLs.

When loading our webpage, the first thing to do is check if a user is already logged into our application with Facebook Login. We can start that process with a call to FB.getLoginStatus, this function will trigger a call to Facebook to get the login status and call our callback function with the results.

However definitely we should load and initialize Facebook JavaScript SDK. Here is the codes:

<script>
  // This Init function should be inserted
  // directly after the opening  tag
  window.fbAsyncInit = function() {
    FB.init({
      appId            : 'your-app-id',
      cookie           : true,  // enable cookies to allow the server to access
                                // the session
      autoLogAppEvents : true,
      xfbml            : true,  // parse social plugins on this page
      version          : 'v2.12'
    });
  };

  // Load the SDK asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

Now that we’ve initialized the JavaScript SDK, we call FB.getLoginStatus(). This function gets the state of the person visiting this page and can return one of three following states:

  • Logged into our app (‘connected’)
  • Logged into Facebook, but not our app yet (‘not_authorized’)
  • Not logged into Facebook, so we cannot tell if they are logged into our app or not (‘unknown’)

These three cases are handled in the callback funtion.

<script>
  // This Init function should be inserted
  // directly after the opening &amp;amp;lt;body&amp;amp;gt; tag
  window.fbAsyncInit = function() {
    FB.init({
      appId            : 'your-app-id',
      cookie           : true,  // enable cookies to allow the server to access
                                // the session
      autoLogAppEvents : true,
      xfbml            : true,  // parse social plugins on this page
      version          : 'v2.12'
    });

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });

  };

  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response.status);  // three states
  }

  // Load the SDK asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

Once our app knows the login status of the person using it, it can do one of the following:

  • If the person is logged into Facebook and our app, redirect them to our app’s logged in experience.
  • I the person isn’t logged into our app or isn’t logged into Facebook, prompt them with the Login dialog with FB.login() or show them the Login Button.

Facebook provides an easy way to generate a Login Button by one click:

WX20180214-004201

After user logged in, we can access authorized data using FB.api(). I have made a demo on http://chenglongyi.com/test/fbapi/, and the full code is below:

<!DOCTYPE html>
<html>
<head>
  <title>Facebook login</title>
</head>
<body>

<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'your-app-id',
      cookie     : true,  // enable cookies to allow the server to access 
                          // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.12' // use graph api version 2.8
    });

    // Now that we've initialized the JavaScript SDK, we call 
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  };

  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);

    if (response.status === "connected") {
      welcome();
    } else {
      document.getElementById('welcome').innerHTML = "";
    }
  }

  function welcome() {
    FB.api(
      '/me',
      'GET',
      {"fields":"id,name"},
      function(response) {
        console.log(response);
        document.getElementById('welcome').innerHTML = "Welcome " + response.name + "!";
      }
    );
  }

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

</script>
<div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="continue_with" data-show-faces="false" data-auto-logout-link="true" data-use-continue-as="true" onlogin="checkLoginState"></div>

</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s