Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the email address of a Facebook user using the graph API?

I have read through this post over and over, and yet it doesn't make sense to me.

What I am trying to do is acquire a Facebook user's email address so that I can store it in a string and compare to see if it matches the emails of existing users in my MySQL database. I only need to to do this when the user first grants access rights to the app.

In the "Authenticated Referrals" section of my app developer interface, I have set "User & Friend Permissions" to include "email".

Within the "canvas" area of my site, I have this code:

include('facebook/base_facebook.php');
include('facebook/facebook.php');
$facebook = new Facebook(array(
    'appId'  => "XXXXXXXXXXXXXXX",
    'secret' => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
));
$user = $facebook->getUser();
if ($user)
{
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If I var_dup() $user, I can see the user id (though not much else) which seems to be correct, so I believe I'm connecting to the right place on Facebook.

But then there was this suggested line of code, which implies that it returns an email address, but when I echo it out to see what it looks like, it doesn't return an email address:

echo "<br/>" . $facebook->getLoginUrl(array('req_perms' => 'email'));

I kind of thought it wouldn't, as it doesn't look quite right to me, but on the other hand, I just have no idea what else to do with it or where to put it.

And then I also came across this post, which has code mixed in with the HTML in a way that baffles me even further.

Assuming that my user has granted permission for my app to see their email, isn't there a simple way of getting at it? Something an inexperienced programmer like myself can grasp?

like image 590
Questioner Avatar asked Feb 21 '23 02:02

Questioner


1 Answers

You are using outdated method. You can use the code below to retrieve the email.

You can find more information about Facebook Connect from : http://25labs.com/tutorial-integrate-facebook-connect-to-your-website-using-php-sdk-v-3-x-x-which-uses-graph-api/

$app_id     = "xxxxxxxxx";
$app_secret = "xxxxxxxxxx";
$site_url   = "xxxxxxxxxxxxx";

include_once "src/facebook.php";

$facebook = new Facebook(array(
    'appId'     => $app_id,
    'secret'    => $app_secret,
    ));

$user = $facebook->getUser();

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

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

if($user){
    Echo "Email : " . $user_profile['email'];
}
like image 151
Tebe Tensing Avatar answered Feb 24 '23 06:02

Tebe Tensing