Advertisement
paulportellimt

handleWebhookNotification

Mar 20th, 2025
164
0
29 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.24 KB | None | 0 0
  1. /**
  2.  * Handle incoming webhook notification and sync events
  3.  *
  4.  * @param array $headers
  5.  * @return bool
  6.  */
  7. public function handleWebhookNotification(array $headers)
  8. {
  9.     try {
  10.         $channelId = $headers['X-Goog-Channel-ID'] ?? null;
  11.         $resourceId = $headers['X-Goog-Resource-ID'] ?? null;
  12.         $resourceState = $headers['X-Goog-Resource-State'] ?? null;
  13.        
  14.         if (!$channelId || !$resourceId) {
  15.             Log::error('Missing required webhook headers');
  16.             return false;
  17.         }
  18.        
  19.         // Find the relevant webhook in our database
  20.         $webhook = CalendarWebhook::where('channel_id', $channelId)
  21.             ->where('resource_id', $resourceId)
  22.             ->first();
  23.            
  24.         if (!$webhook) {
  25.             Log::error('Webhook not found for channel: ' . $channelId);
  26.             return false;
  27.         }
  28.        
  29.         $user = User::find($webhook->user_id);
  30.        
  31.         if (!$user) {
  32.             Log::error('User not found for webhook: ' . $webhook->id);
  33.             return false;
  34.         }
  35.        
  36.         // Set user's token for API access
  37.         if ($user->google_token) {
  38.             $this->client->setAccessToken($user->google_token);
  39.            
  40.             // Refresh token if expired
  41.             if ($this->client->isAccessTokenExpired()) {
  42.                 $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
  43.                 $user->google_token = $this->client->getAccessToken();
  44.                 $user->save();
  45.             }
  46.         }
  47.        
  48.         if ($resourceState === 'sync') {
  49.             // This is just a sync message, no action needed
  50.             return true;
  51.         } elseif ($resourceState === 'exists' || $resourceState === 'not_exists') {
  52.             // Get the sync token to do a partial sync
  53.             $syncToken = $webhook->sync_token ?? null;
  54.            
  55.             // Process changes from Google Calendar
  56.             $this->syncEvents($user, $webhook->calendar_id, $syncToken);
  57.            
  58.             return true;
  59.         }
  60.        
  61.         return false;
  62.     } catch (\Exception $e) {
  63.         Log::error('Error handling Google Calendar webhook: ' . $e->getMessage());
  64.         return false;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement