Facebook Graph API, how to get users email?

357,918

Solution 1

The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.

http://developers.facebook.com/docs/authentication/permissions

You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.

I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.

Solution 2

// Facebook SDK v5 for PHP
// https://developers.facebook.com/docs/php/gettingstarted/5.0.0

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.4',
]);

$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();
var_dump(
    $userNode->getField('email'), $userNode['email']
);

Solution 3

Open base_facebook.php Add Access_token at function getLoginUrl()

array_merge(array(
                  'access_token' => $this->getAccessToken(),
                  'client_id' => $this->getAppId(),
                  'redirect_uri' => $currentUrl, // possibly overwritten
                  'state' => $this->state),
             $params);

and Use scope for Email Permission

if ($user) {
   echo $logoutUrl = $facebook->getLogoutUrl();
} else {
   echo $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
}

Solution 4

Just add these code block on status return, and start passing a query string object {}. For JavaScript devs

After initializing your sdk.

step 1: // get login status

$(document).ready(function($) {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
        console.log(response);
    });
  });

This will check on document load and get your login status check if users has been logged in.

Then the function checkLoginState is called, and response is pass to statusChangeCallback

function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

Step 2: Let you get the response data from the status

function statusChangeCallback(response) {
    // body...
    if(response.status === 'connected'){
      // setElements(true);
      let userId = response.authResponse.userID;
      // console.log(userId);
      console.log('login');
      getUserInfo(userId);

    }else{
      // setElements(false);
      console.log('not logged in !');
    }
  }

This also has the userid which is being set to variable, then a getUserInfo func is called to fetch user information using the Graph-api.

function getUserInfo(userId) {
    // body...
    FB.api(
      '/'+userId+'/?fields=id,name,email',
      'GET',
      {},
      function(response) {
        // Insert your code here
        // console.log(response);
        let email = response.email;
        loginViaEmail(email);
      }
    );
  }

After passing the userid as an argument, the function then fetch all information relating to that userid. Note: in my case i was looking for the email, as to allowed me run a function that can logged user via email only.

// login via email

function loginViaEmail(email) {
    // body...
    let token = '{{ csrf_token() }}';

    let data = {
      _token:token,
      email:email
    }

    $.ajax({
      url: '/login/via/email',    
      type: 'POST',
      dataType: 'json',
      data: data,
      success: function(data){
        console.log(data);
        if(data.status == 'success'){
          window.location.href = '/dashboard';
        }

        if(data.status == 'info'){
          window.location.href = '/create-account'; 
        }
      },
      error: function(data){
        console.log('Error logging in via email !');
        // alert('Fail to send login request !');
      }
    });
  }

Solution 5

To get the user email, you have to log in the user with his Facebook account using the email permission. Use for that the Facebook PHP SDK (see on github) as following.

First check if the user is already logged in :

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();
if ($user) {
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If he his not, you can display the login link asking for the email permission :

if (!$user) {
    $args = array('scope' => 'email');
    echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
    echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}

When he is logged in the email can be found in the $user_profile array.

Hope that helps !

Share:
357,918
kylex
Author by

kylex

Updated on October 20, 2020

Comments

  • kylex
    kylex over 3 years

    I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

    The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

    All well and good, but how do I access that info?

    This is what I have so far:

    $json = $facebook->api('/me');
    
    $first = $json['first_name']; // gets first name
    $last = $json['last_name'];
    
  • kylex
    kylex over 13 years
    Okay, changed file_get_contents. But I'm a little confused as to where I would pass the req_perms=email.
  • kylex
    kylex over 13 years
    Nevermind, I figured it out: $facebook->getLoginUrl(array('req_perms' => 'email'))
  • grayger
    grayger over 13 years
    you can't get it without extended permission.
  • Olson.dev
    Olson.dev about 11 years
    It wasn't completely obvious to me based on this answer... if you're using the JavaScript API, you want to use FB.api('/me?scope=email', function(apiResponse) { ... });
  • zed Blackbeard
    zed Blackbeard about 8 years
    This is not working for me. $user_profile does not contains email
  • Radu Murzea
    Radu Murzea about 7 years
    Is there somewhere a reference page describing the /me route? I keep browsing the pages on Graph API and can't find it anywhere :(
  • Ashley
    Ashley about 7 years
    /me?locale=en_US&fields=name,email was the only way I could figure out to get it to return the email address, couldn't find any other reference to this online
  • arku
    arku almost 7 years
  • HoldOffHunger
    HoldOffHunger over 6 years
    This is the correct answer, although a simpler explanation may be found here: stackoverflow.com/questions/37349618/…
  • Codedreamer
    Codedreamer about 6 years
    Hello @Pang, you can check now, i think this might help. but better still you can still comment more issues.
  • supersan
    supersan almost 6 years
    thank you for this.. nothing else worked except this. now it's working fine! :)
  • therightstuff
    therightstuff over 4 years
    +hero status, just for '/'+userId+'/?fields=id,name,email' which isn't specified in the documentation
  • therightstuff
    therightstuff over 4 years
    or without specifying the fields parameter '/me/?fields=id,name,email' which isn't specified in the documentation
  • Lilleman
    Lilleman over 4 years
    Love an answer that does not assume the use of an SDK that is not needed.