I am trying to upload a file to google drive.but when i upload for the first time it works fine after a while I get refresh token must be passed in or set as part of setAccessToken
I am following this tutorial Laravel 9 Google Drive File Upload/Store Tutorial.
I have searched Google and other answers on stack overflow as well most of them said that I have to add $gClient->setAccessType("offline");
still after adding that I get the error
I have already tried these answers
public function googleDriveFilePpload($company_id)
{
$gClient = new \Google_Client();
$gClient->setApplicationName('Application Name'); // ADD YOUR AUTH2 APPLICATION NAME (WHEN YOUR GENERATE SECRATE KEY)
$gClient->setClientId('My CLient ID'); //Client ID
$gClient->setClientSecret('My Secret ID'); //Secret ID
$gClient->setRedirectUri(route('google.login'));
$gClient->setDeveloperKey('API KEY'); //Google Project API Key
$gClient->setScopes(array(
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive'
));
$gClient->setAccessType("offline");
$gClient->setApprovalPrompt("force");
$service = new \Google_Service_Drive($gClient);
$user = APIsTokens::where('siteName', Auth::user()->id)->latest()->first();
$gClient->setAccessToken(json_decode($user->token, true));
if ($gClient->isAccessTokenExpired()) {
$refreshTokenSaved = $gClient->getRefreshToken();
$gClient->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
$updatedAccessToken = $gClient->getAccessToken();
$updatedAccessToken['refresh_token'] = $refreshTokenSaved;
$gClient->setAccessToken($updatedAccessToken);
$user->access_token = $updatedAccessToken;
$user->save();
}
$item = BackupHistory::where('Company_id', $company_id)->latest()->first();
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => 'Database Backup',
'mimeType' => 'application/vnd.google-apps.folder'
));
$folder = $service->files->create($fileMetadata, array('fields' => 'id'));
printf("Folder ID: %s\n", $folder->id);
$file = new \Google_Service_Drive_DriveFile(array('name' => $item->name, 'parents' => array($folder->id)));
$result = $service->files->create($file, array(
'data' => file_get_contents(storage_path('app/databaseBackup/' . $company_id . '/' . $item->name)),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
));
return redirect('backup');
}