Friday, June 15, 2012

Getting started with the Facebook API

I'm developing a site that requires users to log in, but I've opted to only allow access from Facebook users for now.  I need the user to grant access for Facebook to give me access to their profile, and then I need to actually get their profile.  The Facebook API documentation is thorough, but still wouldn't work without a few experiments and changes, so I figured this might be useful for someone else.

The code will present a button for the user to Login to Facebook, which will request access from Facebook.  The user will get a window asking for permission.  This only occurs once per user, or if they're not logged into Facebook.

The code will then grab the user's Facebook profile details, such as their name.

Don't forget to change <MY APP ID> to the app id given to you by the Facebook Developer site when you create your app.

Javascript:
// Initialise the Facebook API - note that the API itself is loaded
        // further down in the code
        window.fbAsyncInit = function() {
          FB.init({
            appId      : '<MY APP ID>',
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
         
        // Subscribe to an event in the Facebook API - this event
        // will fire whenever a change in authorisation status occurs.
        // This will happen when the user's Facebook account is
        // connected (essentially, authorised), or if the access token
        // expires.
        FB.Event.subscribe('auth.statusChange', function(response) {
            if(response.status == "connected") {
                // Logging lots of stuff to the console - you won't need all of this
                console.log(response);
                // Facebook account connected successfully - can now do things
                // with the Facebook API. First we really need the access token.
                useraccesstoken = response.authResponse.accessToken;
                console.log(useraccesstoken);
                // I'm taking the userID but only because I'm keeping a record
                // of who's connected. You might not need this.
                fbuid = response.authResponse.userID;
                               
                // Let's get the user's Facebook profile information, by passing
                // the useraccesstoken to prove that we have access.
                FB.api('/me?access_token=' + useraccesstoken, function(response) {
                    // Log the user's Facebook profile data object to the console,
                    // using the useraccesstoken taken from the auth.statusChange
                    console.log(response);
                });

            } else {
                // If status changes to anything other than "connected",
                // it's assumed the connection has been lost or there is
                // an error.
                console.log("Facebook login lost.");
            }
          });

        };
        // Load the Facebook API
        (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));
HTML:
<div id="fb-root"></div>
<div class="fb-login-button">Login with Facebook</div>

No comments:

Post a Comment