googleapis / google-api-php-client

A PHP client library for accessing Google APIs
Apache License 2.0
9.22k stars 3.52k forks source link

No me da el token de Refresco, obtengo el token de accesso y todo pero el de refresco no me lo da por mas que intente forzarlo y yano se que hacer #2472

Closed HectorGamboa closed 11 months ago

HectorGamboa commented 1 year ago
public function saveTokenGoogle(Request $request)
{
        $code = $request->token;
        $user = User::where('id', auth()->id())->first();
        // Crear un objeto cliente de Google con el código de acceso
        if ($user->token_google == null) {

            try {
                $client = new Google_Client(
                    ['access_type' => 'offline',]
                );
                $client->setDeveloperKey("196231045278-q00u3ckcf9viup9ptsp6qcr74vhke2cs.apps.googleusercontent.com");
                $client->setApplicationName('ClinicaHoper');
                $client->addScope(Google_Service_Calendar::CALENDAR . ' offline_access');
                $client->setAuthConfig(json_decode(Storage::get("client_secret.json"), true));
                $client->setRedirectUri($this->getCalendarRedirectUriG());
                 $client->setAccessType('offline');
                $client->setApprovalPrompt('force');
                $client->setIncludeGrantedScopes(true);
                $token = $client->fetchAccessTokenWithAuthCode($code);

                return  $token;
                if (isset($token['refresh_token'])) {
                    $refreshToken = $token['refresh_token'];
                    // Guarda el refresh token en algún lugar seguro para usarlo en futuras autenticaciones
                    // Por ejemplo, puedes almacenarlo en la base de datos o en un archivo protegido.
                    // Aquí solo se muestra como ejemplo de cómo obtenerlo.

                } else {
                    // No se pudo obtener el refresh token

                    return $token;
                }

                return $token = $client->getRefreshToken();
                $user->token_google = $token['access_token']; // actualizar el nombre
                $user->code_google = $code;
                $user->save(); // guardar los cambios en la base de datos
            } catch (Exception $e) {
                Log::error($e->getMessage());
                throw new Exception("Error al actualizar el usuario.$e");
            }

            if (is_object($user)) {
                $data = [
                    "code" => 200,
                    "status" => "success",
                    "user" => $user,
                    "message" => 'Cuenta  vinculada',

                ];
            } else {
                $data = [
                    "code" => 400,
                    "status" => "error",
                    "message" => "Ocurrió un error con el token del user.",
                ];
            }
            return response()->json($data, $data["code"]);
        } else {
            $data = [
                "code" => 200,
                "message" => 'Cuenta ya vinculada',
            ];

            return response()->json($data, $data["code"]);
        }
}
saranshdhingra commented 11 months ago

Hi @HectorGamboa When you're initializing the client, you can try and use 'prompt' => 'consent' option to force generate the access token and refresh token every time.

$client = new \Google_Client([
    'access_type' => 'offline',
    'prompt' => 'consent'
]);

A side effect is that this will force the approval UI to be visible every time.

From what I understand, this happens because the Oauth server responds with the refresh_token only the first time you authenticate in a time window, after that you only get the access token. Using the prompt option forces the server to return a refresh token every time.