Create a secure Facebook login in Phonegap

Facebook LoginOne of most useful feature in a mobile app is the login via Facebook (or other social networks like Google+ or Twitter)

In this post I’ll show you how to build a secure login with Facebook for you mobile hybrid app built with Cordova or Phonegap (and PHP on the server)

a) The first step is build an app in Facebook developer portal (

b) Then, get back to you app and install a plugin that allow you use the Facebook API directly inside your app, like this:

c) Now, you can ask to Facebook the info you need, for example the email of your customer:

facebookConnectPlugin.login([‘public_profile’, ’email’], onLoginSuccess, onLoginFailure);

d) In the loginsuccess function you can add the following code:

function onLoginSuccess(obj){
facebookConnectPlugin.api(obj.authResponse.userID+”/?fields=id,email”, [“email”, “public_profile”], function(result){ user.fbToken=obj.authResponse.accessToken; },onLoginFailure);}

It’s very easy to understand:trough the obj argument we can access to some important info like authResponse and its userID and accessToken.

Trough the first one (userID) we call to Facebook to knwo the email. With the access token we can control if we’re really allow to retrive the user info.

e) Now we can send to the server, with a simple Ajax call, the info we need:


The address of the fb_check_url var allow me to check if the token is correct, if I can accesso to the info and, of course, to avoid malicious injection.

f) Decode the JSON:

$jsondata = file_get_contents($fb_check_url);
$fb_json = json_decode($jsondata, true);


//do something…


And that’s all. I don’t need nothing more but save, manage my app or something else….