简体   繁体   English

Facebook PHP SDK-即使从Facebook注销,用户仍显示为登录Web应用程序

[英]Facebook PHP SDK - User still shows as logged in on web app even though logged out of Facebook

I'm working on a website for myself in order to provide coaching to people who are interested in joining fitness challenge groups. 我正在为自己创建一个网站,以便为有兴趣加入健身挑战小组的人们提供指导。 To do this, I've decided to use Facebook as my platform for group correspondence. 为此,我决定使用Facebook作为我进行团体通信的平台。 Subsequently, I've begun working on incorporating Facebook login into my website (www.fitnesschallenges.net) and am mapping Facebook users who join a group to the corresponding group's database within my site. 随后,我开始着手将Facebook登录信息整合到我的网站(www.fitnesschallenges.net)中,并将加入群组的Facebook用户映射到我网站中相应群组的数据库。

The platform I'm using for my site is Wordpress and I've had to be somewhat creative in order to get the login / logout features working properly as a Wordpress plugin (by creating go between scripts - fblogin.php and fblogout.php). 我在我的网站上使用的平台是Wordpress,为了使登录/注销功能可以作为Wordpress插件正常工作(通过在脚本之间创建go-fblogin.php和fblogout.php),我必须具有一定的创造力。 。 Thus far, everything appears to work as it should with one exception... when a user logs out of Facebook, my site continues to show them as logged in. 到目前为止,一切似乎都可以正常工作,唯一的例外是……当用户注销Facebook时,我的网站继续将其显示为已登录。

I've done a number of searches for this particular problem, of which there are some others who've experienced the same behavior. 我已经针对此特定问题进行了许多搜索,其中有些人也经历了相同的行为。 The result of my searches leads me to believe it has to do with sessions and/or establishing authentication tokens, but I'm very much a novice programmer and am looking for some direction on this. 搜索的结果使我相信它与会话和/或建立身份验证令牌有关,但是我是一名新手程序员,并且正在为此寻找一些方向。

Thanks in advance. 提前致谢。

userreg.php ` 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' );

?>` ?>`

fblogin.php 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);
}

?>` ?>`

fblogout.php 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);
}

?>` ?>`

EDIT: A server side access token and user's actual facebook login status are independent of each other. 编辑:服务器端访问令牌和用户的实际Facebook登录状态是彼此独立的。 After getting a better understanding of your question, what you are trying to do is see the actual Facebook login status of a user. 在更好地理解您的问题之后,您要尝试的是查看用户的实际Facebook登录状态。 You are not actually having an issue getting user's data from the API. 从API获取用户数据实际上并没有问题。 The best solution will be to use the Facebook Javascript API and the FB.getLoginStatus function: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ 最好的解决方案是使用Facebook Javascript API和FB.getLoginStatus函数: https : //developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

You can place this in your themes header.php file, or use a Wordpress filter to insert it after the opening <body> tag: 您可以将其放在主题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>

Then place this in your page somewhere to be updated with the status: 然后将其放置在您页面中要更新状态的位置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM