3

I want to add facebook login function in my phonegap app, means user can login in my app using facebook account. For this I am using official Apache Cordova Facebook Plugin.

I have completed these steps:

  1. Import sample project in eclipse
  2. make new account of FB and create new project on facebook developer console.
  3. Add platform on FB console(android), then add key google play package name, class name, key hashes on FB console.
  4. I also make test app of original app because I thought that facebook might not provide permission for original app until it will go live.(By the way both app working fine, and I can login using both App_ids.
  5. I also added all App_id and Display name in my project Manifest file and facebookconnect.xml file.



Plugin is working fine. I can login through plugin. Every thing is perfect.

Now the problem is, because mostly I work on android native apps and I am newbie in phonegap. And because of less knowledge of javascript I am not able to understand project structue properly.

And i need to access some user information like email, username, phone number etc.

So how can i access user information? What modification I need to do in my code and project to access user information.?



Project main code files are given below:

HelloCordova.java

package io.cordova.hellocordova;

import android.os.Bundle;
import org.apache.cordova.*;

public class HelloCordova extends CordovaActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        // Set by <content src="index.html" /> in config.xml
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///android_asset/www/index.html")
    }
}

index.html

<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=medium-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
            <div class="event listening button" onclick="login();">Login with Facebook</div>
            <div class="event listening button" onclick="showDialog();">Show Dialog with Facebook</div>
            <div class="event listening button" onclick="apiTest();">Test API with Facebook</div>
            <div class="event listening button" onclick="getAccessToken();">Get access token with Facebook</div>
            <div class="event listening button" onclick="logPurchase();">Log Purchase Event</div>
            <div class="event listening button" onclick="logEvent();">Log Regular Event</div>
            <div class="event listening button" onclick="getStatus();">Get login status with Facebook</div>
            <div class="event listening button" onclick="logout();">Logout with Facebook</div>
        </div>
        <div id="fb-root"></div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/facebookConnectPlugin.js"></script>
        <script type="text/javascript">
            var login = function () {
                if (!window.cordova) {
                    var appId = prompt("Enter FB Application ID", "");
                    facebookConnectPlugin.browserInit(appId);
                }
                facebookConnectPlugin.login( ["email"],
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
                    console.log("helloooooooooo");

            }

            var showDialog = function () { 
                facebookConnectPlugin.showDialog( { method: "feed" }, 
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }

            var apiTest = function () { 
                facebookConnectPlugin.api( "me/?fields=id,email", ["user_birthday"],
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) }); 
            }

            var logPurchase = function () {
                facebookConnectPlugin.logPurchase(1.99, "USD",
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }

            var logEvent = function () {
                // For more information on AppEvent param structure see
                // https://developers.facebook.com/docs/ios/app-events
                // https://developers.facebook.com/docs/android/app-events
                facebookConnectPlugin.logEvent("Purchased",
                    {
                        NumItems: 1,
                        Currency: "USD",
                        ContentType: "shoes",
                        ContentID: "HDFU-8452"
                    }, null,
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }

            var getAccessToken = function () { 
                facebookConnectPlugin.getAccessToken( 
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }

            var getStatus = function () { 
                facebookConnectPlugin.getLoginStatus( 
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }

            var logout = function () { 
                facebookConnectPlugin.logout( 
                    function (response) { alert(JSON.stringify(response)) },
                    function (response) { alert(JSON.stringify(response)) });
            }
        </script>
    </body>
</html>

facebookconnectplugin.js

cordova.define("com.phonegap.plugins.facebookconnect.FacebookConnectPlugin", function(require, exports, module) {

    "use strict";

    /*
     * @author Ally Ogilvie
     * @copyright Wizcorp Inc. [ Incorporated Wizards ] 2014
     * @file - facebookConnectPlugin.js
     * @about - JavaScript interface for PhoneGap bridge to Facebook Connect SDK
     *
     *
     */

    if (cordova.platformId == "browser") {

        var facebookConnectPlugin = {

            getLoginStatus: function (s, f) {
                // Try will catch errors when SDK has not been init
                try {
                    FB.getLoginStatus(function (response) {
                        s(response);
                    });
                } catch (error) {
                    if (!f) {
                        console.error(error.message);
                    } else {
                        f(error.message);
                    }
                }
            },

            showDialog: function (options, s, f) {

                if (!options.name) {
                    options.name = "";
                }
                if (!options.message) {
                    options.message = "";
                }
                if (!options.caption) {
                    options.caption = "";
                }
                if (!options.description) {
                    options.description = "";
                }
                if (!options.href) {
                    options.href = "";
                }
                if (!options.picture) {
                    options.picture = "";
                }

                // Try will catch errors when SDK has not been init
                try {
                    FB.ui(options,
                    function (response) {
                        if (response && (response.request || !response.error_code)) {
                            s(response);
                        } else {
                            f(response);
                        }
                    });
                } catch (error) {
                    if (!f) {
                        console.error(error.message);
                    } else {
                        f(error.message);
                    }
                }
            },
            // Attach this to a UI element, this requires user interaction.
            login: function (permissions, s, f) {
                // JS SDK takes an object here but the native SDKs use array.
                var permissionObj = {};
                if (permissions && permissions.length > 0) {
                    permissionObj.scope = permissions.toString();
                }

                FB.login(function (response) {
                    if (response.authResponse) {
                        s(response);
                       console.log("FB Login repo");
                    } else {
                        f(response.status);
                        console.log("FB Login repoo...");
                    }
                }, permissionObj);
            },

            getAccessToken: function (s, f) {
                var response = FB.getAccessToken();
                if (!response) {
                    if (!f) {
                        console.error("NO_TOKEN");
                    } else {
                        f("NO_TOKEN");
                    }
                } else {
                    s(response);
                }
            },

            logEvent: function (eventName, params, valueToSum, s, f) {
                // AppEvents are not avaliable in JS.
                s();
            },

            logPurchase: function (value, currency, s, f) {
                // AppEvents are not avaliable in JS.
                s();
            },

            logout: function (s, f) {
                // Try will catch errors when SDK has not been init
                try {
                    FB.logout( function (response) {
                        s(response);
                    });
                } catch (error) {
                    if (!f) {
                        console.error(error.message);
                    } else {
                        f(error.message);
                    }
                }
            },

            api: function (graphPath, permissions, s, f) {
                // JS API does not take additional permissions

                // Try will catch errors when SDK has not been init
                try {
                    FB.api(graphPath, function (response) {
                        if (response.error) {
                            f(response);
                        } else {
                            s(response);
                        }
                    });
                } catch (error) {
                    if (!f) {
                        console.error(error.message);
                    } else {
                        f(error.message);
                    }
                }
            },

            // Browser wrapper API ONLY
            browserInit: function (appId, version) {
                if (!version) {
                    version = "v2.0";
                }
                FB.init({
                    appId      : appId,
                    cookie     : true,
                    xfbml      : true,
                    version    : version
                });
            }
        };

        // Bake in the JS SDK
        (function () {
            if (!window.FB) {
                console.log("launching FB SDK");
                var e = document.createElement('script');
                e.src = document.location.protocol + '//connect.facebook.net/en_US/sdk.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
                if (!window.FB) {
                    // Probably not on server, use the sample sdk
                    e.src = 'phonegap/plugin/facebookConnectPlugin/fbsdk.js';
                    document.getElementById('fb-root').appendChild(e);
                    console.log("Attempt local load: ", e);
                }
            }
        }());

        module.exports = facebookConnectPlugin;

    } else {

        var exec = require("cordova/exec");

        var facebookConnectPlugin = {

            getLoginStatus: function (s, f) {
                exec(s, f, "FacebookConnectPlugin", "getLoginStatus", []);
            },

            showDialog: function (options, s, f) {
                exec(s, f, "FacebookConnectPlugin", "showDialog", [options]);
            },

            login: function (permissions, s, f) {
                exec(s, f, "FacebookConnectPlugin", "login", permissions);
            },

            logEvent: function(name, params, valueToSum, s, f) {
                // Prevent NSNulls getting into iOS, messes up our [command.argument count]
                if (!params && !valueToSum) {
                    exec(s, f, "FacebookConnectPlugin", "logEvent", [name]);
                } else if (params && !valueToSum) {
                    exec(s, f, "FacebookConnectPlugin", "logEvent", [name, params]);
                } else if (params && valueToSum) {
                    exec(s, f, "FacebookConnectPlugin", "logEvent", [name, params, valueToSum]);
                } else {
                    f("Invalid arguments");
                }
            },

            logPurchase: function(value, currency, s, f) {
                exec(s, f, "FacebookConnectPlugin", "logPurchase", [value, currency]);
            },

            getAccessToken: function(s, f) {
                exec(s, f, "FacebookConnectPlugin", "getAccessToken", []);
            },

            logout: function (s, f) {
                exec(s, f, "FacebookConnectPlugin", "logout", []);
            },

            api: function (graphPath, permissions, s, f) {
                if (!permissions) { permissions = []; }
                exec(s, f, "FacebookConnectPlugin", "graphApi", [graphPath, permissions]);
            }
        };

        module.exports = facebookConnectPlugin;
    }
});

Project Structure

Project Structure

App Snapshot

App Snapshot

Devendra Dagur
  • 840
  • 1
  • 14
  • 35

0 Answers0