How to use Facebook API to login

Users don’t like signing up to things except when it is easy. This is where Facebook and other social media companies come in. You can use their API’s to login to your website, which I will demo here how you login to your website using Facebook credentials.

Facebook is one of the biggest social media platforms and therefore one of the best ones to have integrated into your website. They use the programming language JavaScript and then do AJAX calls to the Facebook service to return the responses. Here is how it is done:

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Login the user

First we need to get the Facebook API plugged in and to do this you simply put the code below in the top of the JavaScript file or basically above where you are going to do the Facebook code.

window.fbAsyncInit = function () {
    FB.init({
       
appId: LoginCall.getCookie(‘fb_id’),
        
cookie: true,  // enable cookies to allow the server to access
       
// the session
       
xfbml: true,  // parse social plugins on this page
       
version: ‘v2.2’ // use version 2.1
       
});

// 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 = “//connect.facebook.net/en_US/sdk.js”;
   
fjs.parentNode.insertBefore(js, fjs);
   
}(document, ‘script’, ‘facebook-jssdk’));

This is the basic to set up any call to Facebook and as you can also see it has the prefix ‘FB’. All the calls to Facebook will use the ‘FB’ call.

Now to do the call to Facebook to login, you use one JavaScript call from their API. From the top you have the API call ‘FB.login’, this is the pre-built function Facebook uses to show the pop up for the user to enter their details. Once the user has entered their details it responds back with its ‘response’. This you can see is passed to the ‘statusChangeCallback’ which I will show next. You can see what the ‘response’ should respond back with as an Object. The final piece to take note is the ‘scope’, this is what permissions you are requesting from the users account. The standard things you need is ‘public_profile’ and ’email’, which returns enough information for you to log your user in.

//Log user in
FB.login(function (response) {
    //Check Facebook Response
    statusChangeCallback(response);
    //Display Response
    console.log(response.authResponse.accessToken);
    console.log(response.authResponse.expiresIn );
    console.log(response.authResponse.signedRequest );
    console.log(response.authResponse.userID);
    //Add Scope
    }, { scope: ‘public_profile,email’ });

To check that the user has entered the correct information and is logged in your need to check the status. Before I mentioned a function I added to the login called ‘satusChangeCallback’. This function simply takes the response back from Facebook and checks what status they have given. There are three different outcomes that can be sent from Facebook. First is that the user has entered the correct information and all details have been given back, which is ‘connected’. The other is a part connected response ‘not_autorized’, which means they have been or are already logged into Facebook, but they have not given you permissions to access their account. This would mean you will have to request their details again to give permissions. If the response is neither of these then the only out come is that the user is not logged in at all and has of course not given your website permissions. You can call in any of the out come another function or pop up to tell the user what to do next.

// This is called with the results from from FB.getLoginStatus().            
function statusChangeCallback(response) {
    if (response.status === ‘connected’) {
        // Logged into your app and Facebook.
    } else if (response.status === ‘not_authorized’) {
        // The person is logged into Facebook, but not your app.
    } else {
        // The person is not logged into Facebook, so we’re not sure if they are logged into this app or not.
    }
}

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Get User Information

If you didn’t get all the users information that you wanted you can request more about the user using the below API call. You will have to had already request them to login so that you have permission to get the users detail, but you can then call this to get all the details as below. As before, top to bottom, you use the call ‘FB.api’ which is not just for this call and can be used for other functionalities. In this call we use ‘/me’ that is the key for Facebook to know what you are requesting. This will automatically use the logged in users credentials to return their details. The function after the comma is the response from Facebook using the ‘response’. Facebook will then reply with a JSon object response with all the details you will need.

//Get User Details
function GetUser() {
   //Get user details
   FB.api(‘/me’, function (response) {
      //Facebook response
      Console.log(JSON.stringify(response));
   });
}

If the user has not given or you forgot to request a certain permission, then you can re-request that permission with the following call to Facebook. As you can see it is the same as the login call, but I have adapted it so that you can pass the new comma separated scope to the function for it to re-request the permission. As the user is already logged in they will not have to enter details again, but will just have to accept the new permissions request. For Facebook to know that it is a re-request you have to add after the scope an ‘auth_type’ this just lets Facebook know that you need this scope for your website.

//Update Facebook permissions Scope
function AddToScope(NewScope) {
   FB.login(function (response) {
      statusChangeCallback(response);
   }, { scope: NewScope
   ,auth_type: ‘rerequest’
   });
}

Logout the user

Don’t forget to log out the user as they won’t want that to be locked in. To log the user out is simple and as quick as logging in. You first need to check that the users status is logged in as Facebook requires you to, which you just use ‘FB.getLoginStatus’. You can then use that calls response to call the ‘FB.logout’ that logs the user out of their Facebook account. The response from this function will then be placed inside where you can log the user out of your own website as well.

//Logout user
FB.getLoginStatus(function (response) {
   FB.logout(function (response) {
      //Logged out
   });
});

Look around at Pure Random for more post about how to send post update and images to Facebook as well.

If you need any help with errors or other calls, please feel free to contact Pure Random at info@purerandom.co.uk

Responsive decided

The battle field was laid out and the fight between the quick, safe, easy  fixed viewport and the reliable, standard responsive viewport was a foot. Then walked in the boss… Google. Recently Google has decided which method you must follow to get good rankings on its search engines. Is it the best choose? And should Google get to decide?

Fixed or Responsive Viewport Post

I recently posted about both methods and how they both have their pro’s, but also their con’s. The fixed method was amazing for the designer and developer to get a design for all devices created then developed. This would then view flawlessly on all devices. The implementation of this was also simple with some simple JavaScript and the viewport. The trouble came when we cross browser tested it as some of the browser of some devices didn’t listen to the viewport in the same manner. We fixed the most popular browsers and made fixes for the others. This I always felt was a work around and not the best method, but it worked very well, much faster and meant we could give a true design to the client.

On the other hand we had the other method, which was to set the viewport to device-width. This meant we had to make sure the website worked in all device sizes. This then also meant we couldn’t have one true design, so it would come down to how we could make the website breakdown in a smooth creative way, that also looked amazing. The time to slowly do this and test on multiples devices takes longer, not much but enough to notice. It also relies on the developer knowing good design, good code and best practices. Then again it is worth it as it makes a better website I think and a better developer. If you can envision how the given design can breakdown over all the pixel range and still have a great design look then it shows you are a good coder.

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

Now Google has decided and choose the full responsive viewport method for you. Recently Google Webmasters released a update that has a feature call ‘Mobile Usability’. In this section you can see any mobile performance errors on your website, which I have not been indexed for yet but I read the learn more link instead. In this they specify on what they will mark you on for mobile devices, as they want to give to the user the best website that not only has the best content, but is also the best to view. If you have the best information in front of you and can’t read it then the information become rubbish. For this reason you will have to go down the same method they have chosen.

Even though I have used the fixed viewport method for this website and some others, I believe Google is correct. They are looking to give the user a website that is user friendly and accessible. If you set the viewport at 767px and view it on a iPhone 6 plus, then the button will be for example 20px. If you view that same website on a iPhone 5 with a smaller screen, then that 20px button will be relative in size to 767px and so will be about 10px. This button is now not very user friendly. I think the other method is the quick fix way, but not the best way.

It does make me question why can you set the viewport to a fixed width then? What application would this be useful in?

Google’s New Rules

Firebug for your tablet

Follow these simple steps to get Firebug on your tablet.

1) Surf to this page on your mobile device.

2) Bookmark the page.

3) Copy the code below:

javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+’NS’]&&F.documentElement.namespaceURI;E=E?F[i+’NS’](E,’script’):F[i](‘script’);E[r](‘id’,b);E[r](‘src’,I+g+T);E[r](b,u);(F[e](‘head’)[0]||F[e](‘body’)[0]).appendChild(E);E=new%20Image;E[r](‘src’,I+L);})(document,’createElement’,’setAttribute’,’getElementsByTagName’,’FirebugLite’,’4′,’firebug-lite.js’,’releases/lite/latest/skin/xp/sprite.png’,’https://getfirebug.com/’,’#startOpened’);

4) Edit the bookmark and replace the URL for the code you just copied.

5) Click done, then click on the bookmark.

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

It should now look like this:

eBay API template

I am using this API for my company and have discovered something so silly and stupid. This is that eBay doesn’t let you use JavaScript or JQuery, when you build a product template, but… They do.

So their policy says you cannot use JavaScript that basically effects anything out side your template and/or no importing of other files. However when I called them, they said you can’t have JavaScript at all, though the person I spoke to is a non tech wizard customer service person who was confused by what JavaScript meant. Then I also had a look at some blogs and other company’s like Sony, and they are doing a little bit of a hack.

All these big dogs are using variables to create the <script> tag, so when eBay do their checks it doesn’t get picked up. Then on page when it loads, it generates the script tag to import script files.

Now I have read some of the blogs and they say that it’s full proof and some say even eBay has said that it is a good technique. So hang about, eBay say no to JavaScript, but let you hack it?

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

So what should you do? I would suggest, which is what I am going to do, is do it with JavaScript and/or JQuery, but have a fall back. If eBay want they will and can just pull your listings. I would assume they will have to give you a warning so this can give you time to switch to the basic style. I would say even though you are using the two J’s, I would try not to as much as possible as you want to keep the user experience if you switch.

Say you have a hover over, you want to make it so you can do it both with and with out JavaScript. This way it makes it easier to switch if eBay say but also the user won’t notice much.

Non JavaScript Websites

As you may be aware, I am a web developer and I have just moved company. Now I am working at my new place, I am realising big difference in practice and one that gets me is Non JavaScript websites.  

At my last place, we had to make sure that the site could still perform and look good even if there was no JavaScript. This was just in case some bigger company’s and groups look at the site, that block it. Some company’s do for security, so you should prepare for it. However my currently company feel most everyone is going to have JavaScript on, which they are right as it is a standard these days. If you want the fancy things then you have to use it.

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

I think it doesn’t take much though to do and can mean that 1 extra sale or at least viewer. I am not talking about making the non JavaScript side perfect and run completely the same, as doing some things are impossible. I am just on about making it presentable. 

For example, if you have a slide show with JavaScript, when you take it off the slides are going to be all in a line, making the page look rubbish as you most probably have overflow:hidden on. If you have it prepared for this then you have put a <noscript> tag with just one image in.

I find it’s a little work for a long way.