简体   繁体   中英

Laravel Socialite + Making API calls after login

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM