我试图使用Facebook的PHP SDK。调用Facebook检索用户信息的代码保存在名为fbcall.php的文件中。 fbcall.php页面是通过另一个名为index.php
的页面的href链接调用的整个代码(index.php):
<?php
echo "<a href=\"fbcall.php\">Login Here</a>";
?>
Index.php也是我的FacebookRedirectLoginHelper重定向网址。
我的问题是我没有在fbcall.php文件中看到以下语句的输出,我不知道为什么?
echo "Name: " . $user_profile->getName();
我感觉我的会话没有启动,但我确定如何验证这一点。如果它没有启动,那么我不确定我做错了什么,因为我在这里遵循Facebook的指导方针(或至少我认为我是)。
整个代码(fbcall.php):
<?php
session_start();
// Make sure to load the Facebook SDK for PHP via composer or manually
require_once 'autoload.php';
//require 'functions.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;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('AM USING MY APP ID HERE','AM USING MY SECRET KEY HERE');
$helper = new FacebookRedirectLoginHelper('http://localhost/facebook/index.php');
$params = array('email','public_profile', 'user_status', 'user_friends');
$loginUrl = $helper->getLoginUrl($params);
try {
$session = $helper->getSessionFromRedirect();
// var_dump($session);
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
if (isset($session)) {
var_dump($session);
}
else
{
$loginUrl = $helper->getLoginUrl();
header("location:".$loginUrl);
exit;
}
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
if(isset($session)) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
?>
答案 0 :(得分:0)
用户授予您的权限后,他/她将被重定向到index.php
(因为您的redirect_uri
)。
所以有两种解决方案:
- 将redirect_uri
更改为fbcall.php
- 将所有fbcall.php
逻辑移至index.php
,然后将header("location:".$loginUrl);
更改为echo "<a href=\"$loginUrl\">Login Here</a>";