Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

websanova's avatar

Using socialite with an API?

I'm trying to use Laravel Socialite package over an api. I try to pass the code into my api to fetch the user but it keeps giving me an error:

Fatal error: Call to a member function pull() on null

Since I'm doing the request over an API, I take the following steps.

  1. send a request to api for the url to fetch the code:

    Socialite::with('facebook')->stateless()->redirect()->getTargetUrl()

  2. Then make a request with the above fetched url, which redirects with the code parameter.

  3. Send the code to the api and fetch the user:

    $fb_user = Socialite::with('facebook')->user();

This is where it crashes. I'm not sure why.

I've used the package before and it works fine when I just have an app that reloads the page. But when I send it to an api (on a different domain) it crashes. I'm thinking there is some issue with how the code is generated. Is there anyway to fix this?

0 likes
14 replies
websanova's avatar
websanova
OP
Best Answer
Level 1

Found out my issue, have to use stateless in both calls:

Socialite::with('facebook')->stateless()->redirect()->getTargetUrl()

$fb_user = Socialite::with('facebook')->stateless()->user();
6 likes
reiphoton's avatar

@websanova I'm sorry I'm trying to do the exact same thing based on your idea but I can't understand what you mean by making a request with the fetched url (getTargetUrl()) in this case.

I'm using React JS and I'm not sure what to do with the target URL. I don't want to webpage to end up at just the token I've generated or the backend. Any help is appreciated. Thanks.

Also CC'ing @isaackearl because I read most of his stuff to get through to where I am now. Thanks!!

reiphoton's avatar

Eh lemme reply to my own question. I took a break, tunnel vision was locking my brain in.

First I made my callback the same as my frontend url so: http://localhost:3000/auth/google/callback/ for my Google Provider callback in my Laravel app/services.php. Don't forget to allow the URL(s) on the respective social login provider dev consoles and make sure to restart your sever.

Then on my React frontend, with the URL now redirecting with the code param as a variable which I parsed with my library of choice 'query-string' to get the code text/token.

Then I made an axios POST request to the backend with the code attached to the end of the url...

http://localhost:8000/social/auth/google/callback/code=gibBeriShStriNgYouGotHere and Socialite did the rest... With some help from https://isaacearl.com/blog/stateless-socialite to understand. After which I returned to my frontend a JWTAuth Token, just like with my regular email+password login. Yay!

6 likes
andrewastone's avatar

@reiphoton Hello, thanks to replying to your reply with more information! I'm in the same boat (laravel backend + react fronted) trying to get social login implemented.

I have my callback url: http://localhost:8000/login/facebook/callback?code=gibBeriShStriNgYouGotHere

...which lands on the front-end, where a component parses the code param successfully and send it to a dispatcher containing the axios POST request.

axios.post(`http://localhost:8000/login/facebook/callback?code=${code}`);

This is where I'm having trouble... did you set up a new laravel POST route to a controller action? I'm not sure how you were able to return the Token, and how "Socialite did the rest".

I'd appreciate it so much if you can help me wrap my head around this as you were able to. Thanks!

1 like
abdullahalharun's avatar

@andrewastone Replying as if anyone have the same problem, send it as a get request like this,

useEffect(() => { const loginWithGoogle = async () => { await csrf();

  axios
    .get(`/api/login/google/callback?code=${router.query.code}`)
    .then(() => {
      router.push("/dashboard");
    });
};

if (router.query.code) {
  loginWithGoogle();
}

}, [router.query.code]);

1 like
qwertynik's avatar

@reiphoton Thanks for posting the solution. I am unable to follow the steps and get it working though. In addition to that, I have a couple of questions.

  1. How are the email and password passed to the Social provider?
  2. How is the redirect handled and the response sent back to the frontend?

Thanks!

1 like
njoguamos's avatar

Use api to generate authorisation url. Redirect the user to this url so that they can get authorizaiton code.

 $url = Socialite::driver('google')
            ->stateless()
            ->redirect()
            ->getTargetUrl();

Submit a POST or GET request using fetch/axios and include the authorization code. Attache the code manully to your socialite as follows.

$socialUser = Socialite::driver(driver: 'google')
                ->with(['code' => $request['code']]) // <-- include the code manually
                ->stateless()
                ->user();
2 likes
mohamedelghool671's avatar

how i can make the same operation which i make it in web i want to make it with api for mobile (socialite operation ) how i can do (i try alot but i can't understand it and code don't work )

mohamedelghool671's avatar

statless not work i want to understand why and i want to understand process of registration with socialite by api (in web i unstrad well but when i try it in api i can't understand any thing) :

Route::post('login/{provider}/callback', function (Request $request, $provider) { try {

    $accessToken = $request->input('access_token');

  
    $userSocial = Socialite::driver($provider)->stateless()->userFromToken($accessToken);


    $user = User::updateOrCreate([
        'email' => $userSocial->getEmail(),
    ], [
        'first_name' => $userSocial->getName(),
        'last_name' => $userSocial->getName(),
        'provider_id' => $userSocial->getId(),
    ]);

    // إنشاء توكن للمستخدم وإرجاعه للموبايل
    $token = $user->createToken('auth_token')->plainTextToken;

    return response()->json([
        'user' => $user,
        'access_token' => $token,
        'token_type' => 'Bearer',
    ]);
} catch (\Exception $e) {
    return response()->json(['error' => 'Authentication failed'], 401);
}

});

1 like

Please or to participate in this conversation.