如何询问Facebook用户的私人信息,如电子邮件等

时间:2014-03-24 05:23:19

标签: php facebook facebook-graph-api facebook-javascript-sdk facebook-login

所以我有一个令人烦恼的问题,我似乎无法解决,而且它给我的压力太大了,哈哈。

无论如何,我想在我已配置的登录/注册系统上添加FB登录/注册。我想要它以便新用户可以使用Facebook进入并连接,但我无法使用FB检索他们的电子邮件,我只能出于某种原因检索我的。

我想要检索他们的信息,例如用户名,电子邮件,时区等,以便我可以将其存储到数据库中,这样我就可以检查他们是否已登录并让他们创建自己的小配置文件我的网站。但我无法获取公开信息....

在我的控制器中,我被卡住了,因为我想在我的模型中输入信息,但无法从Facebook获取信息。

还有什么方法可以从POST请求中检索Facebook信息吗?因为那是我现在的模型如何重新获取信息..

这是我的login.php控制器:

<?php

class Login extends CI_Controller
{
    var $user = null, $logoutUrl = null, $loginUrl = null;

    function __construct()
    {
        parent::__construct();

        // App stuff
        $data['appId'] = 'erased';
        $data['secret'] = 'erased for obvious reasons';

        // Load facebook library
        $this->load->library('facebook', $data);

        //Get User ID
        $this->user = $this->facebook->getUser();

        if ($this->user)
        {
            try
            {
                // Proceed knowing you have a logged in user who's authenticated
                $this->user = $this->facebook->api('/me');
                $this->logoutUrl = $this->facebook->getLogoutUrl(array('next' => base_url() . 'logout'));
            }
            catch (FacebookApiException $e)
            {
                error_log($e);
                $this->user = null;
            }
        }
    }

    function index()
    {
        if ($this->user) // If user is authenticated
        {
            $choice = 2;
            $this->validate_credentials($choice);
        }

        else if (!(isset($is_logged_in)) || $is_logged_in != true)
        {
            $is_logged_in = $this->session->userdata('is_logged_in');
            $data['main_content'] = 'loginform_view';
            $data['title'] = 'Login!';
            $data['login_error'] = FALSE;
            $this->load->view('includes/template', $data);
        }
        else
            redirect('take_snapshot');
    }

    function validate_credentials($choice = '')
    {
        $this->load->model('membership_model');

        if ($choice === 2) // If user uses Facebook login
        {
            print_r($this->user); // Only prints public info!! ):
        }

        else if ($choice !== 2) // If user uses normal login
        {
            $query = $this->membership_model->validate();

            if ($query) // if credentials are validated
            {
                $data = array(
                    'username' => strtolower($this->input->post('username')),
                    'is_logged_in' => TRUE
                );

                $data['login_error'] = FALSE;
                $this->session->set_userdata($data);
                redirect('take_snapshot');
            }

            else
            {
                $data['main_content'] = 'loginform_view';
                $data['title'] = 'Login!';
                $data['login_error'] = TRUE;
                $this->load->view('includes/template', $data);
            }
        }
    }
}

?>

这是我的标题:

<!-- START Facbook Javascript API -->
        <div id="fb-root"></div>
        <script>
          window.fbAsyncInit = function() {
          FB.init({
            appId      : 'MY ID [erased for obvious reasons]',
            status     : true, // check login status
            cookie     : true, // enable cookies to allow the server to access the session
            xfbml      : true  // parse XFBML
          });

          // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
          // for any authentication related change, such as login, logout or session refresh. This means that
          // whenever someone who was previously logged out tries to log in again, the correct case below 
          // will be handled. 
          FB.Event.subscribe('auth.authResponseChange', function(response) {
            // Here we specify what we do with the response anytime this event occurs. 
            if (response.status === 'connected') {
              // The response object is returned with a status field that lets the app know the current
              // login status of the person. In this case, we're handling the situation where they 
              // have logged in to the app.
              testAPI();
            } else if (response.status === 'not_authorized') {
              // In this case, the person is logged into Facebook, but not into the app, so we call
              // FB.login() to prompt them to do so. 
              // In real-life usage, you wouldn't want to immediately prompt someone to login 
              // like this, for two reasons:
              // (1) JavaScript created popup windows are blocked by most browsers unless they 
              // result from direct interaction from people using the app (such as a mouse click)
              // (2) it is a bad experience to be continually prompted to login upon page load.
              FB.login();
            } else {
              // In this case, the person is not logged into Facebook, so we call the login() 
              // function to prompt them to do so. Note that at this stage there is no indication
              // of whether they are logged into the app. If they aren't then they'll see the Login
              // dialog right after they log in to Facebook. 
              // The same caveats as above apply to the FB.login() call here.
              FB.login();
            }
          });
          };

          // Load the SDK asynchronously
          (function(d){
           var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
           if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           ref.parentNode.insertBefore(js, ref);
          }(document));

          // Here we run a very simple test of the Graph API after login is successful. 
          // This testAPI() function is only called in those cases. 
          function testAPI() {
            /*
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
              console.log('Good to see you, ' + response.name + '.');
            });
            */

           window.location = '<?php echo base_url(); ?>login/validate_credentials';
          }
        </script>

2 个答案:

答案 0 :(得分:1)

您在登录代码中缺少scope参数。要获得除基本权限/朋友列表等之外的permissions,您必须使用代码中的参数scope添加权限。

所以,用 -

替换FB.login()
FB.login(function(response) {
   // handle the response
}, {scope: 'email'});

您可以找到权限列表here

答案 1 :(得分:0)

您需要获得特殊权限才能返回用户电子邮件。

有两种方法可以做到,但最简单的方法就是在登录按钮中添加一个范围。

<fb:login-button id="loginBtn" max_rows="1" scope="basic_info,email" size="medium" show_faces="false" auto_logout_link="true"></fb:login-button>

您可以在范围内传递任意数量的权限。