Alqin
Alqin

Reputation: 1305

Facebook API get email address

I have to make a website to login with Facebook. Makes sense to be able to send them an email, but I can't get the email address from Facebook.

I followed exactly the instructions from https://developers.facebook.com/docs/facebook-login/getting-started-web/ I add it {scope:email} in FB.login.

How can I get the email address with Facebook API?

My code by now:

<div id="fb-root"></div>
<script>

  window.fbAsyncInit = function() {
  FB.init({
    appId      : 'app', // App ID
    channelUrl : '//domain.COM/channel.php', // Channel File
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  FB.Event.subscribe('auth.authResponseChange', function(response) {
    if (response.status === 'connected') {


    FB.api('/me', function(response) {

      console.log(response);
    });   

    } else if (response.status === 'not_authorized') {

       FB.login(function(response) {},{scope: 'email'});

    } else {


       FB.login(function(response) {}, {scope: 'email'});


    }
  });
  };

  // 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));

  </script>
  <fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>

Upvotes: 1

Views: 13862

Answers (2)

jasingjo
jasingjo

Reputation: 11

I ran into the same issue. Deauthorize the app from the fb account. Then authorize the app again through your test page

I found that it didn't hit the below block once I authorized the app the first time. (adding the scope:email into FB.login once the app has been authorized does no good... i think)

} else if (response.status === 'not_authorized') {

  FB.login(function(response) {},{scope: 'email'});

} else {

  FB.login(function(response) {}, {scope: 'email'});

}

hope that helps

Upvotes: 1

Cormac Driver
Cormac Driver

Reputation: 2521

If you have logged in successfully, calling response.email will return the user's email address.

Upvotes: 0

Related Questions