Jonah Katz
Jonah Katz

Reputation: 5298

Facebook request access token and get email

I have a facebook login script for my site that currently works fine. I want to add the ability to request the email from user, along with the current basic info. I know i need to request an access token, but icant quite figure out how. Here's my current code:

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
            'cookie' => true
        ));
$session = $facebook->getSession();

if (!empty($session)) {
    # Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
    try {
        $uid = $facebook->getUser();


        $user = $facebook->api('/me/');

Upvotes: 4

Views: 4662

Answers (2)

Needhi Agrawal
Needhi Agrawal

Reputation: 1326

You have to provide an extended permission for email at the time of login..
 $access_token = $this->facebook->getAccessToken();
        //check permissions list
        $permissions_list = $this->facebook->api('/me/permissions', 'GET', array('access_token' => $access_token));
        $permissions_needed = array('email');
        foreach ($permissions_needed as $perm) {
            if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
                $login = $facebook->getLoginUrl(array('scope' => 'email,user_birthday',
                'redirect_uri' => your site redirectUri,
                'display' => 'popup'
            ));
                header("location:$login");
            }
        }
        $user = $facebook->getUser();
        if ($user) {
            try {
                $userInfo = $facebook->api("/$user");
            } catch (FacebookApiException $e) {
                echo $e->getMessage();
            }
        }
        print_r($userInfo);

Upvotes: 3

Snouto
Snouto

Reputation: 1031

Have a look at the server-side authentication process - this is where you pass through the permissions you want (known as "scope"). The user will be presented with a login panel if they are not already logged in, and then afterwards a separate permissions panel for any permissions above basic you are requesting and that they haven't already granted. You will then receive an auth token or a code that can be exchanged for a token, and you use this to then further query the user and get their email details in the response.

Good luck!

Upvotes: 1

Related Questions