Facebook请求访问令牌并获取电子邮件

时间:2012-07-13 14:59:43

标签: facebook facebook-graph-api

我的网站有一个facebook登录脚本,目前工作正常。我想添加从用户请求电子邮件的功能,以及当前的基本信息。我知道我需要一个访问令牌,但icant很清楚如何。这是我目前的代码:

$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/');

2 个答案:

答案 0 :(得分:3)

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);

答案 1 :(得分:1)

查看server-side authentication process - 这是您传递所需权限的位置(称为“范围”)。如果用户尚未登录,则会向用户显示登录面板,然后为用户提供单独的权限面板,以获取您要求的基本权限以及尚未授予的权限。然后,您将收到一个身份验证令牌或可以交换令牌的代码,然后您使用它来进一步查询用户并在响应中获取他们的电子邮件详细信息。

祝你好运!