skip to Main Content

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]);
   }

}

3

Answers


  1. 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.

    Login or Signup to reply.
  2. Once you have followed the previous answer to fix the reference to $access_token you can do the following steps with the facebook SDK to retrieve a long lived token from Facebook so you can make many calls to the API. The default auth token will work for 2 hours after which you will need to re-initiate the oAuth flow to get a new token. A long lived token gets you 2 months of access before having to do the oAuth again.
    https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension

    $facebook = new FacebookFacebook();
    $client = $facebook->getOAuth2Client();
    $twoMonthToken = $client->getLongLivedAccessToken($twoHourToken);
    

    Update the user with the $twoMonthToken

    Login or Signup to reply.
  3. $user = Socialite::driver('facebook')->userFromToken($access_token);

    You can simply pass your access_token like above that will return user info.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search