google fetch refresh token code example
Example: get refresh token google api
$token = '{"access_token":"' . $token_data->access_token . '","expires_in":' . $token_data->expires_in . ',"scope":"https:\/\/www.googleapis.com\/auth\/business.manage","token_type":"' . $token_data->token_type . '","created":' . $token_data->created . '}';
$client = new \Google_Client();
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/../../../../public/assets/client_secrets.json');
$client->addScope(\Google_Service_MyBusiness::BUSINESS);
// Set the access token on the client.
try {
if ( $client->isAccessTokenExpired() )
{
$this->refreshAccessToken($token_data, $client, 'gmb_user', $user_id, $brand->id);
}
else{
$client->setAccessToken($token);
}
}
catch (\Exception $exception){
}
private function refreshAccessToken ($token_data, $client, $table, $user_id, $brand_id) {
Log::info('Token Expired 1:'.json_encode($token_data->refresh_token));
Log::info('Old Token:'.json_encode($token_data->access_token));
$access_token = $client->fetchAccessTokenWithRefreshToken($token_data->refresh_token);
Log::info('Renewed Token:'.json_encode($access_token));
$client->setAccessToken($access_token);
$result = DB::table($table)
->where(['owner_id' => $user_id, 'brand_id' => $brand_id])
->update(['access_token' => $client->getAccessToken()["access_token"],
'expires_in' => $client->getAccessToken()["expires_in"],
'token_type' => $client->getAccessToken()["token_type"],
'created' => $client->getAccessToken()["created"]
]);
}