Aug 4, 2024
0
Level 1
Api refresh token not getting refresh . please check code
My google login code
public function googleLogin(Request $request) {
if (Auth::check()) {
return redirect('/dashboard');
}
$google_oauthV2 = new \Google_Service_Oauth2($this->gClient);
if ($request->get('code')){
$this->gClient->authenticate($request->get('code'));
$request->session()->put('token', $this->gClient->getAccessToken());
}
if ($request->session()->get('token')){
$this->gClient->setAccessToken($request->session()->get('token'));
}
if ($this->gClient->getAccessToken()) {
// Get the user's profile information
$googleUserInfo = $google_oauthV2->userinfo->get();
$googleUserId = $googleUserInfo->getId();
$googleUserEmail = $googleUserInfo->getEmail();
$googleUserName = $googleUserInfo->getName();
$user = User::where('google_id', $googleUserId)->first();
if (!$user) {
// If user does not exist, create a new user
$userEmail = $google_oauthV2->userinfo->get()->getEmail();
$user = User::create([
'google_id' => $googleUserId,
'name' => $googleUserName, // Set a default name
'email' => $googleUserEmail, // Use the user's email
// Other user fields as needed
]);
}
// Update user's access token and save
$user->access_token = json_encode($request->session()->get('token'));
$user->save();
// checking drive
// Access Google Drive using the authenticated client
// $driveService = new \Google_Service_Drive($this->gClient);
// try {
// // List files in the user's Google Drive
// $files = $driveService->files->listFiles();
// // Process the files or perform any desired operations
// foreach ($files as $file) {
// echo "File Name: " . $file->name . "<br>";
// }
// // You can also upload, download, or manipulate files as needed
// } catch (\Google_Service_Exception $e) {
// // Handle any errors that may occur
// echo "Error: " . $e->getMessage();
// }
// cecking Drive
Auth::login($user);
$user = Auth::user();
// Retrieve folders associated with the user
$user_payments = UserPayment::where('user_id', $user->id)->get();
$folders = CreateFolder::where('user_id', $user->id)->get();
// dd($folders);
return view('admin.dashboard', compact('folders', 'user', 'user_payments')); // Redirect to the admin dashboard
} else {
// Handle the case when access token is not available
// Redirect the user to the Google login URL
$authUrl = $this->gClient->createAuthUrl();
return redirect()->to($authUrl);
}
}
My drive uploading code
public function googleDriveFileUploadOutSide(Request $request) { // Get the folder ID from the request input $folderId = $request->input('folder_id');
// Retrieve the CreateFolder model using the folder ID
$folder = CreateFolder::where('folder_id', $folderId)->firstOrFail();
// Get the user_id from the CreateFolder model
$userId = $folder->user_id;
// Retrieve the user using the user_id
$user = User::findOrFail($userId);
// Set the user's access token
$accessToken = json_decode($user->access_token, true);
$this->gClient->setAccessToken($accessToken);
// Initialize the Google Drive service
$service = new \Google_Service_Drive($this->gClient);
// Check if the access token is expired
if ($this->gClient->isAccessTokenExpired()) {
// Refresh the access token
$refreshToken = $this->gClient->getRefreshToken();
$newAccessToken = $this->gClient->fetchAccessTokenWithRefreshToken($accessToken);
// Update the user's access token in the database
$user->access_token = json_encode($newAccessToken);
$user->save();
// Set the new access token
$this->gClient->setAccessToken($newAccessToken);
}
// Loop through each uploaded file and upload it to Google Drive
foreach ($request->file('uploaded_files') as $file) {
// Set the file metadata for Google Drive
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => $file->getClientOriginalName(),
'parents' => [$folderId], // Set the folder ID as the parent
]);
// Upload the file
$service->files->create(
$fileMetadata,
[
'data' => file_get_contents($file),
'mimeType' => $file->getClientMimeType(),
'uploadType' => 'multipart',
]
);
// Store the file locally (if needed)
$fileName = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . uniqid() . '.' . $file->getClientOriginalExtension();
$file->storeAs('public/uploads', $fileName);
$file->move(public_path('uploads/'), $fileName);
// Update the CreateFolder record with the new image (if needed)
if ($request->has('id')) {
$id = $request->id;
$existingImages = $folder->images ? explode(',', $folder->images) : [];
$existingImages[] = $fileName; // Add the new file to existing images
$uniqueImageNames = array_unique($existingImages);
$commaSeparatedFileNames = implode(',', $uniqueImageNames);
$folder->images = $commaSeparatedFileNames;
$folder->save();
}
}
return redirect()->back()->with('success', 'Files uploaded successfully.');
}
i want to upload files to drive but it gives error after exipiring. sometimes it gives error of invalid token format but main concern is refreshing token. kindly help me
Please or to participate in this conversation.