PhoneGap Build - Facebook Connect (Part 2)

After several inquiries, in addition of the links provided in Part 1 here is some sample code for Facebook SSO in a PhoneGap environment (using build.phonegap.com and jQuery Mobile 1.3 for user interface). The connect worked for me currently only on Android devices, but no longer on iOs (using PG version 2.3.0). One obstacle is certainly that I have no Apple device for development, local builds or debugging, only Android.

1. Facebook app settings

For the next steps the widget ID in PhoneGap's config.xml it used, be sure to have it matching at all locations below. For demonstration in this case, using Java's packaging convention: "com.companyname.projectname"

Android settings

  • Package Name
    • The same value as specified in config.xml: com.companyname.projectname
  • Class Name
    • Full package name including Android's "activity" class name. Because of my local Java-PhoneGap-Android development, I used the same, e.g. com.companyname.projectname.ProjectActivity
  • Key Hashes
    • For local builds a key hash can be easily generated with Java's keytool (password: android)
      keytool -exportcert -alias androiddebugkey -keystore $HOME\.android\debug.keystore | openssl sha1 -binary | openssl base64
    • For PhoneGap build it was quite harder. Because of lack of knowledge and confusing documentation, I just copied the hash printed after a failed login request. But it should also be possible to add own ones via the build service account settings. Same keys are used for Google Play / Market.
Of course the SSO option has to be activated (in German: "Anmeldung"). More hints, especially how to setup Facebook on an emulator or more information about generating key hashes, are provided in Getting started with Android in the Facebook developer documentation.

iOs settings


The Bundle ID has to match again the widget ID com.companyname.projectname mentioned above. This means, it has to be set in Apple's iOs app settings (of the corresponding developer account, see here). Also again, the SSO option has to be activated (in German: "Anmeldung").

I am not quite sure because of getting a valid access_token on iOs in the past. During development the app stores IDs can be set to 0. More hints concerning iOs are also in the Facebook developer documentation: Getting Started with iOs.

2. Prepare for build service

First add the plugin in your PG Build config.xml in your www folder and set the APP_ID value.
<gap:plugin name="FacebookConnect">
  <param
    name="APP_ID"
    value="123456789" />
</gap:plugin>

EDIT (08/2013): Attention, if using PG > 2.9 read Part 3 to have the correct syntax.

As second, the libraries have to be inserted in the <head> of the index.html (for the build service DO NOT include the JS files themselves, just as phonegap.js).
<script src="cdv-plugin-fb-connect.js"></script>
<script src="facebook-js-sdk.js"></script>

3. Init the library

If using JQuery Mobile a "mobileinit" event is triggered after the framework is fully loaded:
$(document).on('mobileinit', function() {
  FB.init({
    appId : auth.fbId,
    nativeInterface : CDV.FB,
    useCachedDialogs : false
  });


4. Authentication prototype

var auth = new function() {

  this.fbId = "123456789";

  this.FBlogin = function() {

    FB.login(function(response) {

 var uid = null; 
 try {
     uid = response.authResponse.userId;
 } catch (e) {
     main.errorLog(e, "FB.login");
 }

 // iOs Hack other property name
 if (!uid && navigator.userAgent.match(/(iPhone)/i)) {
    try {
       uid = response.authResponse.userID;
    } catch (e) {
       main.errorLog(e, "FB.login");
    }
 }

 if (response.status == 'connected') {
   main.loadAjax(main.ajaxPrefix + '/auth/loginsocial/', {
     fbId : uid,
     access_token: response.authResponse.accessToken,
            secret: TOP_SECRET_GENERATED_HASH
   }, auth.successLogin, auth.errorLogin);

 } else if (response.status === 'not_authorized') {
    alert('Error in authentication: not authorized');
 } else {
    alert('Unknown error in authentication');
 }
    }, {scope : "email"});
  }
}

5. Validation of access_token

On Facebook's mobile SDKs, that are used internally by the PG Facebook Connect plugin, no signedRequest is available (see here). Therefore for security reasons the access_token provided by the Facebook API and a generated hash is passed to the server. The hash is used to validate the request is being done from the mobile app, the access_token to ensure a valid Facebook session. For the second check the GraphAPI can be used:

https://graph.facebook.com/$USERID?fields=id&access_token=$TOKEN

6. Some hints at the end...

If calling auth.FBlogin() the Facebook native app should open and ask for permission. If permissions are already granted, there is a just redirect to the requesting app. As commented in the code above, currently PG Build provides different userId keys (response of FB.login, see here and here). It will be hopefully fixed in version 2.5.0, which will be available soon at the build service, see PGB's Blog)

As said in the beginning I had some problems with iOs, it worked shortly but no success so far. Even if using the correct "misspelled" userID from the request (link) the value is currently always: "...". Because of getting no answer from support forum until today (03/23/2013) I assume, that this will fixed also with the upcoming version...

Be free for adding:
  • constructive critics, 
  • corrections, 
  • additions, 
  • more hints (especially how to get work on iOs),
  • liking, linking or just experience exchange.
  • Blog comments are very welcome, too.

21 comments:

  1. A cool article helping poor souls dealing with PhoneGap Build and Facebook SSO. Great. Thanks

    ReplyDelete
  2. Thank you thank you thank you! The Phonegap Build Documentation is very incomplete. This is awesome!

    ReplyDelete
  3. Thanks for the article. I am also having trouble with iOS. When I include the code in the config.xml, Phonegap Build won't complete a build - I just get an error.

    Any thoughts on that?

    Also, where is the access token code included (https://graph.facebook.com/$USERID?fields=id&access_token=$TOKEN) - in the FB init or config.xml?

    Thanks for the great walk through!
    -Kyle

    ReplyDelete
    Replies
    1. Hi,

      1) normally you should see the build error on the PGB website. There should be a link "here" which tells you what is wrong.

      2) I think you misunderstand oAuth (Fb Login). The accessToken is generated and delivered for each session ( after successful FB connect). Therefore it can be used for validation. You only have to configure your Facebook app id in the config.xml.

      Delete
  4. Hi,
    I'm having problems with my app's FB settings, after I call FB.init I get this :
    "Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains. "

    I tried to add "http://localhost/" to site url on FB settings but it's still not working, any help please ?

    ReplyDelete
    Replies
    1. Which device? Which Versions? Where do you call FB.init after deviceready is fired? How did you configured your FB app in detail? I have set no whitelist at all as the plugin communicates to the native FB application not with the website...

      Delete
  5. Nice article! That seems perfect ;-) Great thanks for that!
    Just a few things:
    Could you describe more detailed what are Package Name, Class Name and Key Hashes? How i have to implement the Package Name in the config.xml? And what exactly is the Class Name and the Key Hashes?

    ReplyDelete
  6. Jens, thanks for sharing your knowledge like this.

    I would like to invite you to try out latest iteration of "AppGyver steroids" for PhoneGap. I believe you will be able to build apps much faster for your customers using steroids than ever before.

    www.AppGyver.com/steroids

    Please give it a try and let me know what you think, and let me know if you have any questions; I'd be happy to introduce to to the support team:

    These recent write-ups give a little more context:
    http://techcrunch.com/2013/03/01/pitching-app-ideas-appgyver-delivers-mobile-app-prototypes-in-minutes-no-technical-know-how-needed/

    http://venturebeat.com/2013/06/03/pitching-an-app-appgyver-says-it-can-deliver-gorgeous-prototypes-more-exclusive/

    http://www.infoworld.com/d/application-development/appgyver-aims-make-phonegap-developers-more-effective-using-steroids-220102

    With my kindest regards,
    Michael Smith
    www.AppGyver.com

    https://twitter.com/AnAppGyverGuy

    "We will not be remembered for building cool tools that build crappy apps"

    ReplyDelete
    Replies
    1. Sorry for beeing offline, hab a lot of work, holidays and missed the blog....

      Delete
  7. Thank god I found this. I now might be able to figure out the problems I've been having.

    ReplyDelete
  8. Millions of people are using Facebook and it's still increasing as time goes by. Some business owner must try to make some application and hire a Facebook Application Developer for their business products or services. This will help them to promote their business and make it known online.

    Facebook Application Development India

    ReplyDelete
  9. Hi! Which value goes in 'Class name' field if I'm developing using PhoneGap Build?

    ReplyDelete
  10. The script tags are only used so that PhoneGap Build can insert those files into your app before building, and which version (Android, iOS, etc) of the file they load will vary depending on which app they are building.

    ReplyDelete
  11. This topic is interesting and impressive. Even on internet, its very difficult to find good quality content about this particular topic on internet.
    iOrder Cloud

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Hay nice article . I wrote an another article for facebook connect
    Facebokk connect plugin using cordova cli 3.3..0

    ReplyDelete
  14. in the end of class name i have to write .ProjectActivity or something else..
    i am dont know the class name of my phonegap build app

    ReplyDelete
  15. we are providing the best service of facebook apps develops on your demand.
    you can contact feel free .we have a good ideas and techniques.
    Thank you so much


    Custom Facebook Apps Development

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete