Facebook Graph API Integration

 As a developer one of the great challenges is to develop a way in which we can leverage the use of social media to increase user adoption and participation levels of our websites.

We can agree that a large proportion of our customer base have some presence on Facebook, whether they regularly use it or not could be debated, but is it most likely that they are some kind of account on the site.

Facebook provide a good set of developer tools in the form of their Facebook Graph API (Social graph tool) as a primary tool to get data out of Facebook, and put data into if required. Their low level API allows developers to be able to query current data with different information representations such as nodes, edges and in our usage fields.

There is also an online Graph API explorer that will allow you to query against Facebook in order to test the relevant scope requirements that you would require in order to access the data that you require. The scope is the permission set that is requested from the user when first presented with the Facebook connect option with their Facebook account.

Here is the url for the explorer: https://developers.facebook.com/tools/explorer

 

Implementation

Facebook’s developer help page provides good examples that can be quickly implemented in the website and be used immediately once an custom app has been created.

<html>
<body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '#', // Set YOUR APP ID
      channelUrl : '#', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });
 
    FB.Event.subscribe('auth.authResponseChange', function(response) 
    {
     if (response.status === 'connected') 
    {
        document.getElementById("message").innerHTML +=  "<br>Connected to Facebook";
        //SUCCESS
 
    }    
    else if (response.status === 'not_authorized') 
    {
        document.getElementById("message").innerHTML +=  "<br>Failed to Connect";
 
        //FAILED
    } else 
    {
        document.getElementById("message").innerHTML +=  "<br>Logged Out";
 
        //UNKNOWN ERROR
    }
    }); 
 
    };
 
    function Login()
    {
 
        FB.login(function(response) {
           if (response.authResponse) 
           {
                getUserInfo();
            } else 
            {
             console.log('User cancelled login or did not fully authorize.');
            }
         },{scope: 'email,user_friends'});
 
    }
 
  function getUserInfo() {
        FB.api('/me', function(response) {
 
      var str="<b>Name</b> : "+response.name+"<br>";
          str +="<b>Link: </b>"+response.link+"<br>";
          str +="<b>Username:</b> "+response.username+"<br>";
          str +="<b>id: </b>"+response.id+"<br>";
          str +="<input type='button' value='Logout' onclick='Logout();'/>";
          document.getElementById("status").innerHTML=str;
 
    });
    }
    function getPhoto()
    {
      FB.api('/me/picture?type=normal', function(response) {
 
          var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
          document.getElementById("status").innerHTML+=str;
 
    });
 
    }
    function Logout()
    {
        FB.logout(function(){document.location.reload();});
    }
 
  // Load the SDK asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));
 
</script>
<div align="center">
<h2>Facebook OAuth Javascript Demo</h2>
 
<div id="status">
 Click on Below Image to start the demo: <br/>
<img src="/LoginWithFacebook.png" style="cursor:pointer;" onclick="Login()"/>
</div>
 
<br/>
 
<div id="message">
Logs:<br/>
</div>
 
</div>
</body>
</html>

For this example we require user_friends, so we need to define this scope when requesting them to log into the site.

Since this implementation request is present on the client side, there is no way we can initiate any form of secrets exchange to verify the identity of the outgoing request with Facebook. We cannot store these secrets securely on the client side and thus that option available from Facebook would be useless. A way to overcome this would  be in the form of client identity validation from Facebook in the form of callback url verification. All we do is provide the appID and update the Facebook app developer console with a valid callback domain, this way we can securely connect to Facebook as a trusted request.

 

Obtaining friends list from Facebook

One of the more common challenges facing developers now is being able to obtain users friends list and details. From Facebook Graph Api v2.0 onwards there has been a strict privacy lock down of their services and most of this information once previously available is now no longer available.

With the current /me/friends command the scope of user_friends is no longer included by default and needs to be explicitly requested. Even so, this would now only show other friends who have granted the user_friends permission, and if its a new app would essentially yield no results initially.

If you want a more usable list of friends then the endpoint that is required is the /me/taggable_friends also under the same user_friends scope. Do bear in mind that your endpoint is required to be reviewed by Facebook before allowed to be released for public use.

 

What information does this provide?

With taggable fields only a limit set of results would be returned such as encrypted Facebook Id, Name and profile Image url.

You are able to apply filters on the requests like /me/taggable_friends?limit=5000 in your javascript code that would get a list of your top 5000 friends.

 

For more information you can read below:-

https://developers.facebook.com/docs/graph-api/using-graph-api

https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friends

Leave a Reply

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