如何使用facebook插件访问cordova中的访问用户信息(phonegap)

时间:2015-09-17 13:20:59

标签: javascript android facebook cordova phonegap-facebook-plugin

我想在我的phonegap应用程序中添加facebook登录功能,意味着用户可以使用Facebook帐户登录我的应用程序。为此我使用官方Apache Cordova Facebook Plugin

我已完成以下步骤:

  1. 在eclipse中导入示例项目
  2. 创建FB的新帐户并在Facebook开发者控制台上创建新项目。
  3. 在FB控制台(android)上添加平台,然后在FB控制台上添加关键的google play包名,类名,键哈希。
  4. 我也制作原始应用程序的测试应用程序,因为我认为facebook可能不会提供原始应用程序的权限,直到它将上线。(顺便说一下,两个应用程序工作正常,我可以使用App_ids登录。
  5. 我还在项目Manifest文件和facebookconnect.xml文件中添加了所有App_id和显示名称。


  6. 插件工作正常。我可以通过插件登录。每件事都很完美。

    现在的问题是,因为我主要是在Android原生应用程序上工作,而且我是phonegap的新手。由于对javascript的了解较少,我无法正确理解项目结构。

    我需要访问一些用户信息,如电子邮件,用户名,电话号码等。

    那我怎样才能访问用户信息?我需要在代码和项目中进行哪些修改才能访问用户信息。



    项目主要代码文件如下:

    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

    应用程序快照

    App Snapshot

0 个答案:

没有答案