Skip to content
Advertisement

Retrieving facebook user access token with socialite on laravel 5.4

I am trying to get user access token so I can send CURL request through Guzzle to Facebook’s Graph API to get user’s friends that are using the app. But I can’t seem to be able to obtain it. Here’s my controller:

<?php
namespace AppHttpControllers;

use IlluminateHttpRequest;
use GuzzleHttpExceptionGuzzleException;
use GuzzleHttpClient;
use Socialite;

class SocialFriendsController extends Controller
{

    public function getFacebookFriends()
    {

    $user = Socialite::driver('facebook')->user();
    $access_token = $user->token;

    $client = new Client();
    $body = $client->get('https://graph.facebook.com/v2.11/me/friends', [
        'query' => [
            'access_token' => '$access_token',
        ]
    ])->getBody();

        $result = GuzzleHttpjson_decode($body, 1);
    return view('pages.admin.posts.create', ['result' => $result]);
   }

}

Advertisement

Answer

A couple of things to note. First of all, the following part of your code won’t work the way you expect it to:

'access_token' => '$access_token',

You’re trying to do variable interpolation, which doesn’t work when you use single quotes ('). You should use double quotes ("$access_token") instead, or since you’re not actually doing anything else with that string, you could just remove the quotes altogether.

Secondly, when doing Facebook logins (In your case, using Socialite) the access token you receive from Facebook is single use (I think so anyway – at least from my own experience). When you do Socialite::driver('facebook')->user(), Socialite is actually using the access token to grab the user object. If you attempt to use it again, Facebook will return an error.

Socialite is probably not the way to go to achieve what you’re trying to do. I would suggest using the Facebook SDK directly to get what you’re after.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement