Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Socialite + Making API calls after login

Tags:

php

oauth

laravel

Laravel 5, Socialite, and google/apiclient packages.

Source code: https://github.com/svpernova09/meatings

I have socialite working fine with Google for logging users in.

I'm trying to make an API call in a different method to fetch Calendar events as the logged in user. I'm getting stuck with what tokens to use where.

The error I'm getting is:

"error" : "invalid_grant",

"error_description" : "Code was already redeemed."

My method:

public function show($user_id)
{
    $user = $this->user->find($user_id);

    $client = new Google_Client();
    $client->setClientId(env('GOOGLE_CLIENT_ID'));
    $client->setClientSecret(env('GOOGLE_CLIENT_SECRET'));
    $client->setRedirectUri(env('GOOGLE_CALLBACK_URL'));
    
    $client->authenticate($user->code);
    $service = new Google_Service_Calendar($client);

    $calendarId = $user->calendar_id;
    $optParams = array(
        'maxResults' => 5,
        'orderBy' => 'startTime',
        'singleEvents' => TRUE,
        'timeMin' => date('c'),
    );
    $results = $service->events->listEvents($calendarId, $optParams);
    $events = [];
    if (count($results->getItems()) > 0) {
        foreach ( $results->getItems() as $event ) {
            $events[] = $event;
        }
    }

    return view('users.calendar')->with('events', $events);
}

The Laravel output is:

Google_Auth_Exception in OAuth2.php line 127: Error fetching OAuth2 access token, message: 'invalid_grant'

$user-code looks like: 4/hfPzDrOHyaEv3asdfadsfasdfDw72nXIl0rt2boUpGj7hM.Um5wPgCeasdfasdfafd1t6qxkmwI

Any guidance would be great. I'm not getting anywhere with the google guides.

like image 987
joepferguson Avatar asked Jun 02 '15 03:06

joepferguson


1 Answers

Calendar uses a different scope than social login. You have to ask for permission again. You can check the documentation of the Calendar API and try it out on Google Playground.

Also Google returns "Code was already redeemed." because you already have an access token for the public information of the user with your code.

like image 164
fehim Avatar answered Oct 22 '22 06:10

fehim