这是API调用的代码并通过Facebook登录。 问题是,当它重定向到Facebook时,它不会登录。 我的代码的哪一部分是错的,我该如何解决?
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$url = $_REQUEST['lasturl'];
$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');
} catch (Exception $e) {
}
if (!empty($user)) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}
答案 0 :(得分:0)
实际上代码很好,获取登录凭据应该可以正常工作。但问题出在这里。
if (!empty($user))
我认为在使用API调用获取用户信息之前,您应先将其放在第一位。如果函数getUser返回一个ID,那么您不需要获取当前会话来获取用户信息。
答案 1 :(得分:0)
尝试以下代码:$session = $facebook->getSession();
不起作用
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$uid = $facebook->getUser();
if ($uid) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$user = $facebook->api('/me');
} catch (Exception $e) {
}
if ($uid) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}