使用Graph API PHP SDK获取Facebook用户电子邮件

时间:2016-01-21 05:43:08

标签: php facebook email facebook-graph-api

我使用Facebook的图形API与php我试图获取用户信息以登录用户访问我的网站但经过大量搜索和阅读后我获得了所有必需的数据期待电子邮件。

<?php
include_once('../dashboard/includes/db_connection.php');
// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( '1393606834280204','3faf1ede6ccc48d6adf096f1a6850359' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://lhefficise.com/facebook/fbconfig.php' );
try {
    $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
  // When Facebook returns an error
} catch( Exception $ex ) {
  // When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
    // graph api request for user data
    $request = new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,last_name,name,email' );
    $response = $request->execute();
    // get response
    $graphObject = $response->getGraphObject();

    // $fbid = $graphObject->getProperty('id');              // To Get Facebook ID
    // $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
    // $fbfirstname = $graphObject->getProperty('name'); // To Get Facebook First Name
    // $fblastname = $graphObject->getProperty('name'); // To Get Facebook First Name
    // $femail = $graphObject->getProperty('email');    // To Get Facebook email ID
    $obj = $graphObject->asArray();
    echo "<pre>";
    print_r($obj);exit;
} else {
    $loginUrl = $helper->getLoginUrl();
    header("Location: ".$loginUrl);
}
?>

我发送/me?fields=id,first_name,last_name,name,email请求,但我没有收到电子邮件,其他所有信息都没问题。

Array
(
    [id] => xxxxxxxxxx83xxxx
    [first_name] => Shan
    [last_name] => Khaliq
    [name] => Shan Khaliq
)

在获取记录时我可能做错了什么..

我已经拥有电子邮件权限,请检查该链接。

http://prntscr.com/9steek

提前致谢。

1 个答案:

答案 0 :(得分:1)

我刚发布此消息后就知道了。

$loginUrl = $helper->getLoginUrl(array('scope' => 'email'));

我需要让scop从facebook获取登录URL。

伙计们,感谢我非常适合这个问题。