7

Here's a link to the topic which described my initial problem.

In short: the problem is that in some cases facebook-graph-api doesn't return the email address of the user.

Other stackoverflow mates suggested to use his Facebook email if he has a user name (i.e. userName@facebook.com) which I've done. But what to do if the facebook user doesn't have "username" there too.

What would you recommend? To redirect him on the page asking his email address?

Community
  • 1
  • 1
Igor Markelov
  • 798
  • 2
  • 8
  • 16
  • Make sure to try your acess token with the [Graph API Explorer](https://developers.facebook.com/tools/explorer/) and make sure that the "email" permission on the left is *not greyed out*. I found that I was sending `scope: ['email']` at the wrong time. – a paid nerd Dec 02 '17 at 20:59

2 Answers2

3

if you are using PHP Sdk then this part is important:

// $facebook->api('/me?fields=id,email,first_name,last_name,gender,birthday');

$facebook = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}'
  ]);

$accessToken = !empty($_GET['accessToken'])?$_GET['accessToken']:'';
$facebook->setAccessToken($accessToken);
$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me?fields=id,email,first_name,last_name,gender,birthday');
     // your register function here
     // userSignup($user_profile);
  } catch (FacebookApiException $e) {
    //echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
  }
}
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130
2

There are several reasons why Facebook API doesn't return the email address. Some reasons are listed in https://developers.facebook.com/bugs/298946933534016

Different solutions were proposed to handle this case like in a discussion at https://github.com/mkdynamic/omniauth-facebook/issues/61

But I think using userName@facebook.com is not a good solution, because it's not a valid email, and userName might be not available either, and when you will try sending an email to the user, it will fail to deliver, etc.

Asking a user's email address also is not a good thing to do, since some users might refuse to provide their emails.

I recommend constructing such a fake mail like uid@facebook.yourdomain.com where uid is a user ID guaranteed always to return from Facebook, and a subdomain of your domain where you can handle such fake emails like you want.

Tom
  • 1,387
  • 3
  • 19
  • 30
link0ff
  • 2,744
  • 1
  • 22
  • 15