I am using socialite to get the user access_token and use that token to get connect to the Google API Client in laravel. Everything is working fine. But I need to get the access token. But it is failed to get in the response. Let me know how to get the id_token from Google API client.
Here is my code
public function callback()
{
$user = \Socialite::driver('google')->user();
$idToken = $this->getIdToken($user);
var_dump($idToken);
}
public function getIdToken($user){
$google_client_token = [
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
'expires_in' => $user->expiresIn
];
$client = new Google_Client();
$client->setAccessToken(json_encode($google_client_token));
$oauth = new Google_Service_Oauth2($client);
$client->authenticate($_GET['code']); //exchange 'code' with access token, refresh token and id token
$accessToken = $client->getAccessToken();
$userData = $oauth->userinfo->get();
return $userData;
}
This worked for me, using the methods from Laravel's socialite documentation:
config/services add this to the array (with your own keys)
'google' => [
'client_id' => env('GOOGLE_API_ID'),
'client_secret' => env('GOOGLE_API_SECRET'),
'redirect' => env('APP_URL').'/auth/adwords/callback'
],
Set up your routes as per the docs, and then add these to your class and it will dump out the token and expires_in
public function redirectToProvider() {
return Socialite::with('google')->redirect();
}
public function handleProviderCallback(Request $request) {
$adwords_api_response = Socialite::with('google')->getAccessTokenResponse($request->code);
dd($adwords_api_response);
}
I had a similar issue where coming from an Android device I didn't have access to the access_token
so I had to pass an auth_token
instead. On the server side here's how I handled it to retrieve an access_token
.
$driver = Socialite::driver('google');
//In some cases coming from android an auth token may be required to get an access token
$access_token = $driver->getAccessTokenResponse($input['auth_token'])['access_token'];
$googleUser = $driver->userFromToken($access_token);
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.