Facebookのシングルサインオンは機能していますが(ほとんどの場合)、何らかの理由でエラーが発生することがあります。Facebookに転送してURLに転送するphpsdkログインを使用するフォールバックメソッドを作成しようとしています。Facebookが自分のページにリダイレクトすると、URLの$_GET['session']の下にセッションデータが表示されます。 json文字列として、その文字列を使用して有効なAPI呼び出しを行う方法を理解する必要があります。
<?php
require_once "facebook_sdk.php";
$facebook = new Facebook(array('appId' => '123','secret' => '456','cookie' => true,));
$session = null;
$_fb_profile = null;
$session = $facebook->getSession();
//get links for login/logout
$loginUrl = $facebook->getLoginUrl();
$logoutUrl = $facebook->getLogoutUrl();
if($session){
try {
$facebook_id = $facebook->getUser();
$_fb_profile = $facebook->api('/me'); //if not null valid session
$facebook_name = $_fb_profile['name'];
$facebook_link = $_fb_profile['link'];
}
catch (FacebookApiException $e) {
echo $e;
}
}
//there is not a valid session though the single sign on FBML button, try checking php login
if(!$_fb_profile){
$session = $_GET['session'];//json string from facebook
$session = json_decode($session);//make into an array
try {
$facebook->setSession($session,true);//need to set the session some how with $_GET['session']
$facebook_id = $facebook->getUser();
$_fb_profile = $facebook->api('/me');
$facebook_name = $_fb_profile['name'];
$facebook_link = $_fb_profile['link'];
}
catch (FacebookApiException $e) {
die($e); //getting invalid OAuth access token
}
}
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php if(!$session || !$_fb_profile){
//user is not logged in show FBML button and php login link
echo "<fb:login-button perms='email,user_birthday,user_education_history,read_friendlists,publish_stream'></fb:login-button>
<p class='small' style='float:right;'>Having trouble? try <a href='$loginUrl'>logging in here</a></p>";
}
else{
//user has logged in
echo "You are logged into facebook as <a href='$facebook_link'>$facebook_name</a>";
}?>
</body>
</html>