Facebook PHP SDK - 即使退出Facebook,用户仍然显示登录Web应用程序

时间:2014-01-02 01:08:40

标签: php facebook sdk facebook-php-sdk logout

我正在为自己的网站工作,以便为有兴趣加入健身挑战小组的人提供指导。为此,我决定使用Facebook作为我的群组通信平台。随后,我开始将Facebook登录纳入我的网站(www.fitnesschallenges.net),并将加入群组的Facebook用户映射到我网站中相应群组的数据库。

我用于我网站的平台是Wordpress,为了让登录/注销功能作为Wordpress插件正常工作(通过在脚本之间创建--fblogin.php和fblogout),我必须要有点创意。 .PHP)。到目前为止,一切似乎都有效,但有一个例外......当用户退出Facebook时,我的网站会继续将其显示为已登录。

我已经针对这个特殊问题进行了大量搜索,其中还有一些人经历过相同的行为。我的搜索结果让我相信它与会话和/或建立身份验证令牌有关,但我是一个新手程序员,我正在寻找一些方向。

提前致谢。

userreg.php `

    global $wpdb;
    // Remember to copy files from the SDK's src/ directory to a
    // directory in your application on the server, such as php-sdk/
    require_once(plugin_dir_path( __FILE__ ) . "facebook-php-sdk/src/facebook.php");

    $loginscript = plugins_url( 'fblogin.php', __FILE__ );
    $logoutscript = plugins_url( 'fblogout.php', __FILE__ );
    $challengeid = $atts['challengeid'];

    $config = array(
        'appId' => '#################',
        'secret' => '#################',
        'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
    );

    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();

    if($user_id) {
        // We have a user ID, so probably a logged in user.
        // If not, we'll get an exception, which we handle below.
        try {

            $user_profile = $facebook->api('/me','GET');

            function test_input($data) {
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
            }

            $id = test_input($user_profile['id']);
            $name = test_input($user_profile['name']);
            $first_name = test_input($user_profile['first_name']);
            $last_name = test_input($user_profile['last_name']);
            $link = test_input($user_profile['link']);
            $username = test_input($user_profile['username']);
            $gender = test_input($user_profile['gender']);
            $email = test_input($user_profile['email']);
            $timezone = test_input($user_profile['timezone']);
            $locale = test_input($user_profile['locale']);
            $verified = test_input($user_profile['verified']);

            $table_name= $wpdb->prefix . "fcm_fbusercreds";
            $currentmember_result = $wpdb->get_results(
                "
                SELECT *
                FROM $table_name
                WHERE id = $id
                "
            );

            if(empty($currentmember_result)){
                $wpdb->insert( $table_name, array( 'lastupdated' => current_time('mysql'), 'id' => $id, 'name' => $name, 'first_name' => $first_name, 'last_name' => $last_name, 'link' => $link, 'username' => $username, 'gender' => $gender, 'email' => $email, 'timezone' => $timezone, 'locale' => $locale, 'verified' => $verified, 'coach' => "0" ) );
            } else {
                foreach ($currentmember_result as $result){
                    $wpdb->update( $table_name, array( 'lastupdated' => current_time('mysql'), 'name' => $name, 'first_name' => $first_name, 'last_name' => $last_name, 'link' => $link, 'username' => $username, 'gender' => $gender, 'email' => $email, 'timezone' => $timezone, 'locale' => $locale, 'verified' => $verified, 'coach' => "0" ), array( 'id' => $result->id ) );
                }
            }

            return '<a href="' . $logoutscript . '?final=0&ls=' . $logoutscript . '&site=' . site_url() . '&pp=' . $_SERVER['REQUEST_URI'] . '"><img src="' . plugins_url( 'images/fb_logout.png' , __FILE__ ) . '" width="240" height="30" alt="" /></a>';

        } catch(FacebookApiException $e) {
            // If the user is logged out, you can have a 
            // user ID even though the access token is invalid.
            // In this case, we'll get an exception, so we'll
            // just ask the user to login again here.

            error_log($e->getType());
            error_log($e->getMessage());
            return '<a href="' . $loginscript . '?redirect=1&site=' . site_url() . '&pp=' . $_SERVER['REQUEST_URI'] . '&ls=' . $loginscript . '"><img src="' . plugins_url( 'images/fb_login.png' , __FILE__ ) . '" width="240" height="30" alt="" /></a>';
        }   
    } else {
        // No user, print a link for the user to login
        return '<a href="' . $loginscript . '?redirect=1&site=' . site_url() . '&pp=' . $_SERVER['REQUEST_URI'] . '&ls=' . $loginscript . '"><img src="' . plugins_url( 'images/fb_login.png' , __FILE__ ) . '" width="240" height="30" alt="" /></a>';
    }
}

add_shortcode( 'fcmreg', 'fcm_fb' );

&GT;`

fblogin.php

`

$config = array(
    'appId' => '###################',
    'secret' => '###################',
    'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);

$redirect = $_GET['redirect'];
$site = $_GET['site'];
$pagepath = $_GET['pp'];
$ls = $_GET['ls'];

if(isset($_GET['error'])){
    header("Location: " . $site . $pagepath);
    exit;
}

$facebook = new Facebook($config);
$user_id = $facebook->getUser();

// If redirect is one, then this is for regular user registration
// if redirect is two, then this is for coach registration
if($redirect == 1){
    $params = array(
        'scope' => 'email',
        'redirect_uri' => $ls . '?redirect=' . $redirect . '&site=' . $site . '&pp=' . $pagepath . '&ls=' . $ls
    );
} elseif($redirect == 2) {
    $params = array(
        'scope' => 'email, user_online_presence, create_event, manage_friendlists, publish_actions, manage_pages',
        'redirect_uri' => $ls . '?redirect=' . $redirect . '&site=' . $site . '&pp=' . $pagepath . '&ls=' . $ls
    );
}

$login_url = $facebook->getLoginUrl($params);

if($user_id) {
    // We have a user ID, so probably a logged in user.
    // If not, we'll get an exception, which we handle below.
    try {
        header("Location: " . $site . $pagepath);
    } catch(FacebookApiException $e) {
        // If the user is logged out, you can have a 
        // user ID even though the access token is invalid.
        // In this case, we'll get an exception, so we'll
        // just ask the user to login again here.
        header("Location: " . $login_url);
        error_log($e->getType());
        error_log($e->getMessage());
    }   
} else {
    // No user, print a link for the user to login
    header("Location: " . $login_url);
}

&GT;`

fblogout.php

`

$config = array(
    'appId' => '################',
    'secret' => '################',
    'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);

$ls = $_GET['ls'];
$site = $_GET['site'];
$pagepath = $_GET['pp'];
$final = $_GET['final'];

$facebook = new Facebook($config);
$params = array('next' => $ls . '?final=1&ls=' . $ls . '&site=' . $site . '&pp=' . $pagepath);
$logoutUrl = $facebook->getLogoutUrl($params);

if($final == 0){
    header("Location: " . $logoutUrl);
}

if($final == 1){
    $facebook -> destroySession();
    header("Location: " . $site . $pagepath);
}

&GT;`

1 个答案:

答案 0 :(得分:0)

编辑:服务器端访问令牌和用户的实际Facebook登录状态彼此独立。在更好地理解您的问题之后,您要做的是查看用户的实际Facebook登录状态。实际上,从API获取用户数据并不存在问题。最好的解决方案是使用Facebook Javascript API和FB.getLoginStatus函数:https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

您可以将其放在主题header.php文件中,或使用Wordpress过滤器在开头<body>标记后插入它:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: 'YOUR_APP_ID', // App ID
            channelUrl: 'channel.html', // Channel File
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        FB.getLoginStatus(function(response) {

            if (response.status === 'connected') {
                var uid = response.authResponse.userID;
                jQuery('#facebook_status').html('User is logged into Facebook and Fitnesschallenges.net app');
            } else if (response.status === 'not_authorized') {
                jQuery('#facebook_status').html('User is logged into Facebook but not Fitnesschallenges.net app');
            } else {
                jQuery('#facebook_status').html('User is not logged into Facebook');
            }
        });

    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    }(document));
</script>d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    }(document));
</script>

然后将其放在您的页面中,以更新状态:

<div id="facebook_status"></div>