使用facebook登录获取用户名,电子邮件

时间:2016-01-28 18:01:00

标签: javascript php jquery facebook facebook-graph-api

我在我的网站上使用facebook进行登录,

这是按钮

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

我正在使用给定here

的确切示例

但是在检查登录状态之后,我只得到了facebook和令牌的用户ID的响应,但我也想得到用户名..我怎么能得到它?

帮助

这是脚本

window.fbAsyncInit = function () {
        FB.init({
            appId: 'xxxx',
            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.2
        });

        FB.getLoginStatus(function (response) {
            console.log(response);
            console.log(response.email);

            //here status is connected
            //statusChangeCallback(response);
        });

    };

resopnse中,我得到了整个json,

response.status我正在连接

但是当我尝试response.email时,我得到了未定义的

我如何获得电子邮件或用户名?

1 个答案:

答案 0 :(得分:0)

已编辑以显示实际为我修复的内容:

所以它似乎取决于您的配置设置允许的API版本。但是,我能够通过使用以下内容获得v2.5 api上的电子邮件地址:

如果您使用的是Hello World代码,请替换此部分:

FB.api('/me', function (response) {
                        console.log('Success ');
                        console.log(response);
                    });

有了这个:

FB.api('/me', { fields: 'email' }, function (response) {
                        console.log('Success ');
                        console.log(response);
                    });

不同之处在于添加{字段:&#39;电子邮件&#39;对象调用。这似乎是API的v2.4或v2.5中的新增功能,这就是为什么你在SO上看到的旧代码似乎适用于海报但不适合你的原因。希望这会有所帮助。

我不确定这是否有资格作为解决方案,但我能够重现此问题(在有效请求后没有电子邮件返回)。

我有两个应用程序,每个应用程序都在不同的FB帐户下创建。第一个是一年多前创建的,第二个是今天创建的。我的代码完全针对较旧的应用程序运行(返回电子邮件),并且针对较新的应用程序(无电子邮件)失败。

起初我觉得FB可能只是对某些全新应用程序的数据有所保留,但我觉得它很难在任何地方记录下来。

所以我决定并排比较每个应用程序配置。我发现旧版本的API VERSION(位于仪表板顶部)设置为2.0,而较新版本为2.5。 API SDK页面上的Hello World代码请求版本2.2,如下所示:

window.fbAsyncInit = function () {
            FB.init({
                appId: [my app id here],
                cookie: true,  // enable cookies to allow the server to access 
                // the session
                xfbml: true,  // parse social plugins on this page
                version: 'v2.2' 
            })
        };

根据文档,新配置的API在配置中设置为2.5的事实意味着对旧API(例如2.2)的任何请求将自动升级到2.5。当我将上面的javascript设置为请求2.5(例如版本:&#39; v2.5&#39;)时,我能够让旧应用程序失败。所以我怀疑问题出在更新的v2.5 api。

我无法找到如何设置我的新应用以接受较旧的api通话,但如果我这样做会在此处更新。