Can't get userdata from Facebook SDK

时间:2019-05-31 11:51:08

标签: php wordpress facebook-graph-api facebook-php-sdk

I'm making a voting application in WordPress, where users can make votes on posts.

To vote, users do not need to have an actual user in WordPress, but instead need to login with Facebook. Then the vote is stored in a custom table, containing an ID, post_id and facebook_id.

But I'm having problems retrieving the userdata of the current facebook user.

For some reason it always fails when trying to get the accessToken, which according to the documentation is need to retrieve the userdata. I've also tried to follow the documentation strictly, but it's the same result. The accessToken cannot be retrieved.

Here's how to voting flow should work:

  1. A list of posts is shown, each with a voting-button and a vote-counter.
  2. When a user is clicking the vote button, a Facebook Login Prompt should appear if not already logged in. If already logged in / after logging in, an ajax call is sent along with the page-id and facebook-id.
  3. The data is then stored in the custom table and the vote is complete.

The storing part is already working, when I'm using a static string as the facebook-id. The problem lies solely in the implementing of Facebook.

I've added the Facebook SDK with composer like this: composer require facebook/graph-sdk

Note: I'm developing in the sage theme from roots.


Here's current my code:

JS:

$(function() {
    $('.vote-btn').on('click', function() {

        let page_id = $(this).data('page-id');

        FB.getLoginStatus(function(response) {
            if(response.status === 'connected') {
                makeVote(page_id);
            } else {
                loginWithFacebook(),
            }
        }
    });
};

function makeVote(id) {
    $.post('', {id: id}, function() {
        // Success
    }).fail(function() {
        // Fail
    }).always(function() {
        $('.loader').hide();
    });
}

function logInWithFacebook() {
    FB.login(function(response) {
        if (response.authResponse) {
            alert('You are logged in & cookie set!');
            // Now you can redirect the user or do an AJAX request to
            // a PHP script that grabs the signed request from the cookie.
        } else {
            alert('User cancelled login or did not fully authorize.');
        }
    });
    return false;
}

PHP

namespace App\Controllers;

use Sober\Controller\Controller;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

class TemplateVoting {

    private $post_id:
    private $fb_id;
    private $wpdb;

    public function __construct() {
        $this->wpdb = $GLOBALS['wpdb'];
    }

    public function __after() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            $this->post_id = $_POST['id'];
            $this->addVote();
        }
    }

    private function addVote() {
        if( !is_int( $this->fb_id() ) ) {
            return;
        }
        $this->wpdb->insert("wp_post_votings", [
            "post_id" => $this->post_id,
            "fb_id"   => $this->fb_id(),
        ]);
    }

    private function fb_id() {
        try {
            $response = $fb->get('/me?fields=id', $this->getToken());
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            return $e->getMessage();
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            return $e->getMessage();
        }

        $user = $response->getGraphUser();
        return $user['id'];
    }

    private function initApi() {
        $facebook = new Facebook([
            'app_id' => env('FB_APP_ID'),
            'app_secret' => env('FB_APP_SECRET'),
            'default_graph_version' => 'v3.3',
        ]);
    }

    private function getToken() {
        $fb = $this->initApi();

        $helper = $fb->getJavaScriptHelper();

        try {
            $accessToken = $helper->getAccessToken();
        } catch(FacebookResponseException $e) {
            return $e->getMessage();
        } catch(FacebookSDKException $e) {
            return $e->getMessage();
        }

        if (!isset($accessToken)) {
            return '';
        }

        return $accessToken->getValue();
    }

}

End of body-tag

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = '//connect.facebook.net/en_US/sdk.js';
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


window.fbAsyncInit = function() {
    FB.init({
        appId: 'app_id', // True app_id is inserted in real project
        cookie: true, // This is important, it's not enabled by default
        version: 'v2.10'
    });
};

I haven't worked with the Facebook SDK or the Graph API before so I'm very lost here.

Anyone knows what I'm doing wrong?

0 个答案:

没有答案