yaza-putu / laravel-google-drive-storage

Laravel Google Drive Storage, You can store file like S3 AWS in laravel , this package allow to store file to google drive
MIT License
125 stars 29 forks source link

Is there a way to get the Google File ID? #15

Open JosephSilber opened 1 month ago

JosephSilber commented 1 month ago

I want to redirect my users to the Google Drive interface, to show the file in their viewer. To construct the URL, I need the file ID. Is that exposed somehow?

yrey420 commented 1 month ago

I work it out with the name of the folder, it worked for me tho. i could upload folder and subfolders into any folder and go on with out any kind of problem.

See that this is your problem, you should try to build the url through the name of the folders.

JosephSilber commented 1 month ago

Thanks 🙏

Can you please show me how to construct the URL to the Google Drive web interface using just the folders?

yrey420 commented 1 month ago

Hey dude, sadly i've been having all kind of issues, regarding to the yaza to use it fully.

i highly recommend you to use the direct Google Drive API V3, it's honestly super easy to do.

if you need more information you can email me at yreysepulveda@gmail.com or yrey415@unab.edu.co.

I advanced waaaaay faster using the direct API, i am able to create folders and files, edit them with no problem at all, it's super easy with the API.

I can show you the google controller you need to start working with

class GoogleAuthController extends Controller { // Redirige al usuario a Google para la autenticación public function redirectToGoogle() { $clientId = env('GOOGLE_DRIVE_CLIENT_ID'); $redirectUri = env('GOOGLE_REDIRECT_URI'); $url = "https://accounts.google.com/o/oauth2/auth?" . http_build_query([ 'client_id' => $clientId, 'redirect_uri' => $redirectUri, 'response_type' => 'code', 'scope' => 'https://www.googleapis.com/auth/drive', // Scope para Google Drive 'access_type' => 'offline', // Para recibir el refresh token 'prompt' => 'consent', // Solicitar consentimiento para el refresh token ]);

    return redirect()->away($url);
}

public function handleGoogleCallback(Request $request)
{
    $code = $request->input('code');
    $clientId = env('GOOGLE_DRIVE_CLIENT_ID');
    $clientSecret = env('GOOGLE_DRIVE_CLIENT_SECRET');
    $redirectUri = env('GOOGLE_REDIRECT_URI');

    $response = Http::asForm()->post('https://oauth2.googleapis.com/token', [
        'code' => $code,
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'redirect_uri' => $redirectUri,
        'grant_type' => 'authorization_code',
    ]);

    $data = $response->json();

    // Verifica si el token de acceso se obtuvo correctamente
    if (isset($data['access_token'])) {
        // Guarda los tokens en la sesión o en la base de datos según sea necesario
        GoogleToken::updateOrCreate(
            ['id' => 1], // Siempre usa el mismo ID para sobreescribir el registro
            [
                'access_token' => $data['access_token'],
                'refresh_token' => $data['refresh_token'],
            ]
        );
        // Aquí puedes redirigir a la vista donde quieras mostrar la información de Google Drive
        return view('home');
    } else {
        // Manejar el error si no se obtuvo el token
        return redirect()->route('login')->withErrors(['error' => 'No se pudo obtener el token de acceso']);
    }
}

public function refreshAccessToken()
{

    $googleToken = GoogleToken::find(1); // Obtén el primer (y único) registro
    $refreshToken = $googleToken->refresh_token;
    $clientId = env('GOOGLE_DRIVE_CLIENT_ID');
    $clientSecret = env('GOOGLE_DRIVE_CLIENT_SECRET');

    $response = Http::asForm()->post('https://oauth2.googleapis.com/token', [
        'refresh_token' => $refreshToken,
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'grant_type' => 'refresh_token',
    ]);

    $data = $response->json();

    if (isset($data['access_token'])) {
        // Actualiza el token de acceso en la base de datos
        $googleToken->access_token = $data['access_token'];
        $googleToken->refresh_token = $data['refresh_token'];
        $googleToken->save(); // Guarda los cambios

        return response()->json(['message' => 'Token de acceso refrescado correctamente.']);
    } else {
        // Manejar el error si no se pudo refrescar el token
        return redirect()->route('login')->withErrors(['error' => 'No se pudo refrescar el token de acceso']);
    }
}

}

and the routes you need in your software to get the initials tokens.

Route::get('/login/google', [GoogleAuthController::class, 'redirectToGoogle'])->name('google.login'); Route::get('/callback', [GoogleAuthController::class, 'handleGoogleCallback'])->name('google.callback');

NOTE: I did not use any library, i only used HTTP request, which honestly is one of the best ways to handle API request most of the times, well in my experience, it can be otherwise.