Panie i Panowie, They, Them and ktokolwiek jeszcze tam co by nikogo nie urazic ...
buduje w mojej laravelowej aplikacji wysylke przed google workspace z uzyciem OAuth2 do autentykacji ale
napotkalem problem z ktorym do tej pory sobie nie poradzilem.
Utworzylem aplikacje w Google, ustawilem scopes i wszystko dziala ale nie zwraca mi refresh tokena przy pierwszej autoryzacji. Przekopalem caly internet i wszystko co znalazlem to dodaj :
$client->addScope("email");
$client->acccess_type("offline");
$client->addScope("profile");
$client->setApprovalPrompt('force');
co uczynilem nie zmieniilo to jednak niczego, wyrzucilem polaczenie z konta Google, wywlilem rekordy z bazy zeby na czysto zainicjowac ponownie autoryzacje, pobranie tokenow itd
i nic, tak samo jak wczesniej dostaje token autoryzacyjny, emaila a refresh tokena jak nie bylo tak niema
Macie jakies doswiadczenie w tej kwestii ?
Podpowiedzcie jak zmusic Google zeby zwrocil refresh token
U innych providerow nie mialem problemu, nawet Zoho,Yahoo, Outlook365 , microsoft dzialaja bez najmniejszych problemow a G..... nie chce wspolpracowac
private function processGoogleClientConnection($sender) { Log::channel('mailcheck')->info("Processing Google Client connection for sender: {$sender->sender_id}"); // Initialize the Google Client $client = new Google_Client(); $client->setClientId(env('GOOGLE_CLIENT_ID')); $client->setClientSecret(env('GOOGLE_CLIENT_SECRET')); $client->setRedirectUri(env('GOOGLE_REDIRECT_URI')); $client->setAccessType('offline'); // Make sure to set this to get the refresh token $client->addScope(Google_Service_Gmail::GMAIL_SEND); $client->addScope(Google_Service_Gmail::GMAIL_READONLY); $client->addScope("email"); $client->accessType('offline'); $client->addScope("profile"); $client->setApprovalPrompt('force'); // Forces the consent screen to get the refresh token // Assuming $sender->code contains the OAuth2 code after user authorization $code = $sender->code; // The authorization code from Google // Send the POST request to get the OAuth token $response = Http::asForm()->post('https://oauth2.googleapis.com/token', [ 'code' => $code, 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'), 'redirect_uri' => env('GOOGLE_REDIRECT_URI'), 'grant_type' => 'authorization_code', 'access_type' => 'offline', // This ensures you get a refresh token 'prompt' => 'consent' // Forces the consent screen, needed for refresh token ]); // Check if the request was successful if ($response->failed()) { Log::channel('mailcheck')->error("Google OAuth token request failed for sender: {$sender->sender_id}"); return []; // Or handle the error appropriately } // Get the response data $data = $response->json(); // Log the tokens to ensure we're receiving them Log::channel('mailcheck')->info('Access Token: ', ['access_token' => $data['access_token']]); Log::channel('mailcheck')->info('Refresh Token: ', ['refresh_token' => $data['refresh_token']'No refresh token']);
// Save the tokens to the database $emailProvider = $sender->emailProvider; $emailProvider->provider_name = 'google'; $emailProvider->api_id = '2'; $emailProvider->access_token = $data['access_token']; $emailProvider->refresh_token = $data['refresh_token'];//null;
$emailProvider->save(); // Check if access token and refresh token are present $accessToken = $sender->access_token; $refreshToken = $sender->refresh_token; if (!$accessToken || !$refreshToken) { Log::channel('mailcheck')->error("Missing access or refresh token for sender: {$sender->sender_id}"); return []; } // Set the access token $client->setAccessToken($accessToken); // Refresh the access token if expired if ($client->isAccessTokenExpired()) { Log::channel('mailcheck')->info("Google Client token expired, refreshing..."); $client->fetchAccessTokenWithRefreshToken($refreshToken); $newAccessToken = $client->getAccessToken(); $sender->access_token = $newAccessToken['access_token']; $sender->save(); } // Create the Gmail service instance $service = new Google_Service_Gmail($client); try { Log::channel('mailcheck')->info("Successfully connected to Google Gmail API for sender: {$sender->sender_id}"); // Fetch all messages in the inbox (no date range) $messagesResponse = $service->users_messages->listUsersMessages('me', [ 'maxResults' => 100 // You can adjust the number here to limit the results ]); // Log the raw API response to verify if emails are returned Log::channel('mailcheck')->info("Google API raw response: " . json_encode($messagesResponse)); $emails = []; foreach ($messagesResponse->getMessages() as $message) { $messageDetails = $service->users_messages->get('me', $message->getId()); // Log the email details to see the headers and body Log::channel('mailcheck')->info("Message Details: " . json_encode($messageDetails->getPayload()->getHeaders())); $body = $this->getEmailBody($service, $messageDetails); Log::channel('mailcheck')->info("Email Body: " . $body); $emails[] = [ 'headers' => $messageDetails->getPayload()->getHeaders(), 'body' => $body, ]; } // Log the number of emails found Log::channel('mailcheck')->info("Found $emailsCount emails in INBOX for sender {$sender->sender_id}."); return $emails; } catch (\Google_Service_Exception $e) { Log::error("Google API error for sender {$sender->sender_id}: " . $e->getMessage()); return []; } catch (\Exception $e) { Log::error("Error fetching emails for sender {$sender->sender_id}: " . $e->getMessage()); return []; } }
Podpowiedzcie prosze
Pozdrawiam
phpamator
Może zamiast używać GoogleCLienta lepiej użyć Socialite ?
(moja aplikacja jest na Laravelu)