Laravel Socialite - get user details by token

2019-05-03 09:11发布

I'am developing android application with facebook login and laravel REST API server. After user login on mobile, app get token which is sent to my server. On server I want get facebook user details by token.

Facebook SDK for PHP provides methods for that:

$session = new FacebookSession('token');
$me = (new FacebookRequest($session, 'GET', '/me',))->execute()->getGraphObject(GraphUser::className());

Can Laravel Socialite obtain user facebook details based on that token? Or just use that Facebook SDK?

3条回答
干净又极端
2楼-- · 2019-05-03 09:19

You can also extend your Socialite Facebook Provider.

For example;
Create a class as SocialConnect in App/Library folder

namespace App\Library;

use Laravel\Socialite\Two\FacebookProvider;

    class SocialConnect extends FacebookProvider {

        public function userFromToken($access_token)
        {
            $user = $this->mapUserToObject($this->getUserByToken($access_token));
            return $user->setToken($access_token);
        }
    }

Then add these lines in boot method on your App/Providers/AppServiceProvider.php

 $socialite = $this->app->make('Laravel\Socialite\Contracts\Factory');
    $socialite->extend(
        'SocialConnect',
        function ($app) use ($socialite) {
            $config = $app['config']['services.facebook'];
            return $socialite->buildProvider(SocialConnect::class, $config);
        }
    );

Ready for use!

Socialite::driver('SocialConnect')->userFromToken($accessToken)

You can also add new methods as you wish in your SocialConnect class.

查看更多
冷血范
3楼-- · 2019-05-03 09:39

There is a method getUserByToken implemented in the Facebook Service Provider, however it's protected and only used internally to get the user details.

So you're better off using the Facebook SDK.

查看更多
我命由我不由天
4楼-- · 2019-05-03 09:41

I submitted a pull request to the repo which was accepted to the 2.o branch. You should be able to call Socialte::driver('facebook')->userFromToken($token) now.

https://github.com/laravel/socialite/pull/126

Cheers.

查看更多
登录 后发表回答