Facebook PHP SDK - User still shows as logged in o

2019-08-09 06:02发布

问题:

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. 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.

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). 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.

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 `

    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

`

$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

`

$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);
}

?>`

回答1:

EDIT: A server side access token and user's actual facebook login status are independent of each other. After getting a better understanding of your question, what you are trying to do is see the actual Facebook login status of a user. You are not actually having an issue getting user's data from the 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/

You can place this in your themes header.php file, or use a Wordpress filter to insert it after the opening <body> tag:

<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>