Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MikasaAck's avatar

Google Calendar Api tokens not being refreshed

I am trying to add and get events from google calendar API through my Laravel App. I used Socialite for the consent screen for the first time to get the access and refresh token. I get them successfully, but once an hour expires (Which means the access token expires) I cannot get another access token from the refresh token. When I log the content of the : dd($client->fetchAccessTokenWithRefreshToken($refreshToken)); I get this error: Could not determine client ID from request.

public function redirectToGoogle()
    {
        $scopes = [
            'https://www.googleapis.com/auth/userinfo.email',
            'https://www.googleapis.com/auth/userinfo.profile',
            'openid',
            'https://www.googleapis.com/auth/calendar',
        ];
    
        return Socialite::driver('google')
            ->scopes($scopes)
            ->with(["access_type" => "offline", "prompt" => "consent select_account"])
            ->redirect();
    }

    public function handleGoogleCallback()
    {
        $user = Socialite::driver('google')->stateless()->user();
        // Save the access token to your user's account
        auth()->user()->update([
          'google_access_token' => $user->token,
          'google_refresh_token' => $user->refreshToken,
      ]);

        return redirect()->route('events.index')->with('message', 'Google Calendar access granted');
    }

    public function create(Request $request)

{
  $user = auth()->user();

  // Check if the user has a stored access token and refresh token
  if (!$user->google_access_token ) {
      return redirect()->route('events.index')->with('message', 'Google Calendar access not granted');
  }

  // Create a Google Client instance and set the access token
  $client = new Google_Client();
  $client->setAccessToken($user->google_access_token);

  // Check if the access token is expired
  if ($client->isAccessTokenExpired()) {
      // Use the refresh token to obtain a new access token
      $refreshToken = $user->google_refresh_token;
      $client->fetchAccessTokenWithRefreshToken($refreshToken);
      dd($client->fetchAccessTokenWithRefreshToken($refreshToken));

      
      // Update the user's access token in the database
      $user->update(['google_access_token' => $client->getAccessToken()['access_token']]);
      $client->setAccessToken($user->google_access_token);


  }



    // Collect user input
    $title = $request->input('title');
    $description = $request->input('description');
    $id_prospect = $request->input('id_prospect');
  
    $prospect = DB::connection('prospects')
    ->table('companies')
    ->where('id', $id_prospect) // Filter by the authenticated user's ID
    ->get()->first();
    

    
    $startDateTime = Carbon::parse($request->input('startdate'))->format('Y-m-d\TH:i:sP');
    $endDateTime = Carbon::parse($request->input('enddate'))->format('Y-m-d\TH:i:sP');
          
            
    // Create a new instance of the Google Calendar service
    $calendarService = new Google_Service_Calendar($client);

    // Prepare event data from the user's input
    $event = new Google_Service_Calendar_Event(array(
        'summary' => $title,
        'description' => $description,
        'start' => array(
            'dateTime' => $startDateTime,
          ),
          'end' => array(
            'dateTime' => $endDateTime,
          ),
        'reminders' => array(
          'useDefault' => FALSE,
          'overrides' => array(
            array('method' => 'email', 'minutes' => 24 * 60),
            array('method' => 'popup', 'minutes' => 10),
          ),
        ),
        'attendees' => array(
            array('email' => $prospect->email),
          ),
      ));

    // Specify the calendar ID where the event should be inserted (usually 'primary')
    $calendarId = 'primary';

    // Insert the event
    $createdEvent = $calendarService->events->insert($calendarId, $event);
    $eventsAPI = $calendarService->events->listEvents($calendarId);
    //dd($events);

        // Store event in your database
        Event::create([
          'title' => $title,
          'startdate' => $startDateTime,
          'enddate' => $endDateTime,
          'description'=>$description,
          'id_prospect'=>$id_prospect
      ]);

    // Redirect or return a response
    return redirect()->route('myprospects')->with([
      'message' => 'Event created successfully',
      'eventsAPI' => $eventsAPI, // Assuming $events is the array of Google Calendar events
  ]
  );
}

0 likes
0 replies

Please or to participate in this conversation.