Getting Facebook session on WordPress

BACKGROUND

We have a WordPress site that requires a special kind of Facebook authentication. The WP site needs to authenticate a user with a different app, and then log the user into the app. The web app is built by us, and it has an API that the WP site uses to interact with it. Before we all get rowdy, this whole authentication process works using a normal login form. Using the API, we can easily see that the user is or is not logged into the app, and display that on the WP site.

PROBLEM

As stated, we need Facebook authentication. I am using Facebooks PHP SDK v4 and have it built into a custom plugin so as to keep the code seperate from the theme. When a user clicks on the FB icon, it shows the popup with the correct redirect URL. After a while, this popup closes, but there is nothing in the result. A few well placed var_dumps reveal that I’m not getting anything back from FacebookRedirectLoginHelper. This means I can’t get the session which in turns means no user info.

Read More

CODE

As stated, I’ve created a plugin (ns-social.php) which handles everything. Here is that file:

/**
 * Plugin Name: NS Social Plugin
 */

require_once 'ns-social-init.php';
require_once 'ns-callback-functions.php';
require_once 'ns-facebook.php' ;

$fb = null;
add_action('plugins_loaded','load_fb');

function load_fb() {
    global $fb;
    $fb = new WP_Facebook();
}

/**
 * SOCIAL LOGIN CHECK
 */

function get_fb_url()
{
    global $fb;
    return $fb->login_url();
}

ns-social-init.php starts a session that FB can use:

/**
 * Any functions that are required during initialisation of WordPress or this plugin
 */
add_action('plugins_loaded', 'start_session');

function start_session()
{
    if (!session_id()) {
        session_start();
    }
}

ns-callback-functions.php contains all the callback functions for the redirects. These are all shortcodes that are placed in pages, so the url will be www.site.com/facebook-callback and that page will only have [facebook-callback] in it which will handle the request.

add_shortcode('facebook_callback', 'facebook_callback');
function facebook_callback()
{
    global $fb;
    if (isset($_GET['error'])) {
        if ($_GET['error'] == 'access_denied') {
            echo "<script>
                if(window.opener != null) {
                    window.close();
                }
            </script>";
            exit;
        }
    }
    $session = $fb->get_session();
    $userArr = $fb->get_user();
    $user['name']     = $userArr['first_name'];
    $user['surname']  = $userArr['last_name'];
    $user['email']    = $userArr['email'];
    $user['verified'] = $userArr['verified'];
    $_SESSION['registeruser'] = $user;
    $_SESSION['registertype'] = 'Facebook';
    $action = "";
    die(var_dump($_SESSION,true));
    if (user_exists($user['email'])) {
        $action = '?login';
    }
    wp_redirect(home_url('social-register/' . $action));
}

And last but not least, my ns-facebook.php file:

use FacebookFacebookRedirectLoginHelper;
use FacebookFacebookSession;
use FacebookFacebookRequest;

class WP_Facebook
{
    var $helper;
    var $session;
    var $permissions;
    var $loginurl;

    public function __construct()
    {
        // Initialize the SDK
        FacebookSession::setDefaultApplication('0appId145', '00hahaitsmysecret23523');
        $this->permissions = ['public_profile', 'email'];
        $this->helper = new FacebookRedirectLoginHelper(home_url('facebook-callback'));
        $this->loginurl = $this->helper->getLoginUrl($this->permissions);
    }

    /**
     * Returns the login URL.
     *
     * @return string
     */
    public function login_url()
    {
        return $this->loginurl;
    }

    /**
     * Returns the current user's info as an array.
     */
    public function get_user($session = null)
    {
        if(empty($session)) $session = $this->session;
        if($session) {
            /**
             * Retrieve User's Profile Information
             */
            // Graph API to request user data
            $request = new FacebookRequest($session, 'GET', '/me');
            $response = $request->execute();

            // Get response as an array
            $user = $response->getGraphObject()->asArray();

            return $user;
        }

        return false;
    }

    public function get_session() {
        try {
            $this->session = $this->helper->getSessionFromRedirect();
        } catch(FacebookRequestException $ex) {
            // When Facebook returns an error
        } catch(Exception $ex) {
            // When validation fails or other local issues
        }
        if ($this->session) {
            return $this->session;
        }
    }
}

WHAT HAVE I TRIED

I’ve gone through quite a few questions on SO. What I have noticed is, when I first run the page, my FBRLH_state in my session is, abcdef for example. But when I get a response after clicking the login button, my FBRLH_state is xyz. I don’t know if this has an effect on the outcome. If it could, how would I use this state? I don’t set it, I’m assuming that the FB SDK does.

TL;DR

FB PHP SDK v4 is not sending back anything when I use FacebookRedirectLoginHelper. Why would it do this, and how do I fix it?

Related posts

2 comments

  1. did you make a test with just the offical FacebookRedirectLoginHelper from official GitHub?
    I have used the Facebook SDK a couple of times and never had a problem with missing returns.

  2. So I fixed my issue with help from corvuszero’s comment.

    Here’s the code in my ns-facebook.php file:

    use FacebookFacebookSession;
    use FacebookFacebookRequest;
    use FacebookFacebookRedirectLoginHelper;
    class WP_Facebook
    {
        var $helper;
        var $session;
        var $permissions;
        var $loginurl;
    
        public function __construct()
        {
            // Initialize the SDK
            FacebookSession::setDefaultApplication('303664476506500', '0197b7f08cc46f051ddb92dfba077484');
            $this->permissions = ['public_profile', 'email'];
            $this->helper = new FacebookRedirectLoginHelper( home_url('facebook-callback') );
    
            try {
                $this->session = $this->helper->getSessionFromRedirect();
            } catch (FacebookRequestException $e) {
                // handler
            } catch (Exception $e) {
                // handler
            }
    
            if(isset($_SESSION['fb_token'])) {
                $this->session = new FacebookSession( $_SESSION['fb_token'] );
            }
    
            if($this->session) {
                $_SESSION['fb_token'] = $this->session->getToken();
            } else {
                $this->loginurl = $this->helper->getLoginUrl($this->permissions);
            }
        }
    
        /**
         * Returns the login URL.
         *
         * @return string
         */
        public function login_url()
        {
            return $this->loginurl;
        }
    
        /**
         * Returns the current user's info as an array.
         */
        public function get_user()
        {
            if($this->session) {
                /**
                 * Retrieve User’s Profile Information
                 */
                // Graph API to request user data
                $request = new FacebookRequest($this->session, 'GET', '/me');
                $response = $request->execute();
    
                // Get response as an array
                $user = $response->getGraphObject()->asArray();
    
                return $user;
            }
    
            return false;
        }
    
        public function get_session() {
            return $this->session;
        }
    }
    

Comments are closed.