当他按下我在 index.php 中的链接时,我正在尝试将用户登录并注册到我的数据库中。我在整个互联网上搜索了答案。我在这段代码上工作了超过 4 天,并以多种方式编写了它,但没有一个解决了由令牌引起的这个 oauhexception 问题。所以我把它放在一个循环中,有时它会起作用。为什么?为什么有时有效,有时无效?
这是我的 fbLogin.php
session_start();
if(!(isset($_SESSION['fb']))){
$fb=new FbConnection();
$url=$fb->getLoginUrl();
$_SESSION['fb']=$fb;
header("Location: $url");
exit;
}
$fb=$_SESSION['fb'];
try{
$fbUser=$fb->getUser();
}catch(Exception $e){
sleep(3);
header("Location: fbLogin.php");
exit;
}
这是我的 Facebook 连接
class FbConnection{
private $facebook;
public function __construct(){
$this->facebook=new Facebook(array(
'appId' => '******',
'secret' => '*******',
));
}
public function getUser(){
$user=$this->facebook->getUser();
if($user){
try {
$this->facebook->api('/me');
}catch(Exception $e){
print("errore preso<br>");
error_log($e);
$user = null;
//self::reloadToken();
}
}
$user=$this->facebook->api('/me');
$name=$user['first_name'];
$lastName=$user['last_name'];
$email=$user['email'];
$sex=$user['gender'];
$birthday=$user['birthday'];
$res=$this->facebook->api('me?fields=third_party_id');
$tpid=$res['third_party_id'];
//print($tpid."<br>");
$fbUser=new FacebookUser($name, $lastName, $email, $sex, $birthday, $tpid);
return $fbUser;
}
public function getConnectionStatus(){
if($_SESSION['user']->third_party_id)
return true;
return false;
}
public function connect(){
if($_SESSION['user']->third_party_id)
throw new FacebookAlreadyConnectedException('Questo account è già associato ad un account Facebook');
$fbUser=$this->getUser();
$user=$_SESSION['user'];
$result=UserManager::searchByContent('third_party_id', $fbUser->third_party_id);
if($result) throw new FacebookAlreadyRegisteredException('Questo account Facebook è già registrato');
else
$user->third_party_id=$fbUser->third_party_id;
}
public function getLogoutUrl(){
if(!self::getConnectionStatus())
return 'index.php';
$params = array( 'next' => *****' );
return $this->facebook->getLogoutUrl($params); // $params is optional.
}
public function getLoginUrl(){
$params=array('scope' => 'email, user_birthday',
'redirect_uri' => ***/fbLogin.php);
return $this->facebook->getLoginUrl($params);
}
}
这是 index.php 上的链接代码
Accedi Tramite Facebook
有什么问题?它有时会循环,有时会起作用。
循环位于 try/catch 块中,因为 fb->getUser() 使用无效令牌调用 facebook->api 类方法引发的 oAuthException。它继续循环,因为它在试图获取新令牌的页面上再次重定向。但是我怎样才能得到一个有效的令牌呢?