Search code examples
phpfacebooklaravelfacebook-php-sdklaravel-5

Laravel 5 get user info from facebook


I'm trying to get an user id from Facebook with the Facebook PHP-sdk with Laravel 5. I did a lot of search on the errors I got, but none of the answers helped.

Set keys:

use Facebook\FacebookSession;
FacebookSession::setDefaultApplication('XXX' , 'XXX');

Redirect to Facebook:

public function getFacebook()
{
    $helper = new FacebookHandler(url('settings/set_facebook'));
    return Redirect::to($helper->getLoginUrl());
}

Get the info:

public function setFacebook()
{
    try{
        $session = new FacebookSession(\Session::get('state'));
        $request = new FacebookRequest($session, 'GET', '/me');
        $response = $request->execute();
        $graphObject = $response->getGraphObject()->asArray();
        dd($graphObject);
    } catch(Exception $e){
        dd(
            $e->getMessage(),
            $e->getCode(),
            $e
        );
    }
}

Code for Laravel sessions:

use Facebook\FacebookRedirectLoginHelper;
use Illuminate\Support\Facades\Session;

class FacebookHandler extends FacebookRedirectLoginHelper
{
    protected function storeState($state)
    {
        Session::put('state', $state);
    }

    protected function loadState()
    {
        return $this->state = Session::get('state');
    }
}

Output:

"Invalid OAuth access token."

190

FacebookAuthorizationException {#215 ▶}

What am I doing wrong?


Solution

  • use Laravel Socialite. It supports facebook, twitter, google+ and github. and also easy to use.