lilHar
lilHar

Reputation: 1862

Attempting to Log user in with facebook api, and returning email address in a php site

This is my code thus far:

<div id='fb-root'></div>
  <script src='http://connect.facebook.net/en_US/all.js'></script>
  <script>
     FB.init({ 
        appId:'xxxxxxxxxxxx', cookie:true, 
        status:true, xfbml:true , oauth:true, channelUrl:'http://www.federationofhumanity.com/facebookconnect/channel.html'
     });</script><fb:login-button show-faces='true' width='200' max-rows='1' perms='user_birthday,user_online_presence,user_website,email'>Login using Facebook</fb:login-button><script>
    FB.getLoginStatus(function(response) {
        if (response.authResponse) {
            document.getElementById('fb-root').innerHTML = '';

        } else {
            document.getElementById('fb-root').innerHTML = '';
        }
    });
    if ($user) 
    </script>    

(FYI, this code is included in php script via a readfile command.) As it is, I can show someone as "logged in", but I have nothing to differentiate them from a normal user on the website. My website is php based. I need to get their primary email address so the site can use it and provide the personalized experience they're coming to the site for. I need to somehow get their email address and turn it into a variable for the php to use. Help please?

Upvotes: 0

Views: 565

Answers (1)

Ted S
Ted S

Reputation: 337

After the user authenticates your application, Facebook can return them to a URL you set [add the paramater onlogin='window.location="https://graph.facebook.com/oauth/authorize?client_id=XXXXX&redirect_uri=http://www.yoursite.com/facebookscript; ?>&r="+window.location.href;']

This script can then pull their email address from Facebook using the PHP SDK now that you have authorization to use it.

// call up the php SDK
require './facebook/facebook.php';

// now connect to facebook with our secret information
$facebook = new Facebook(array(
  'appId'  => XXXXXXX,
  'secret' => XXXXXXX,
  'cookie' => true
));

// get the facebook user id
$fb_user = $facebook->getUser();

// try to get their email address
try {
  $user_info = $facebook->api('/me'); // this is their profile basics
} catch (FacebookApiException $e) {
    echo "something went wrong: ". $e; die;
}

// print email address
echo "your email address is: ". $user_info['email']

You can also grab the email out with the JavaScript SDK using the response.authResponse function you currently have left blank. But you still need a script to kick in to process it and register them [likely via ajax] -- I'd suggest letting the user confirm their email address as some people will want to switch accounts.

Upvotes: 1

Related Questions