Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fcmhttpbundle Laravel Package

digitalap/fcmhttpbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require digitalap/fcmhttpbundle in your Laravel project (note: this is a Symfony bundle, so you’ll need to adapt it for Laravel via Symfony Bridge or use it in a Symfony-based Laravel app like Lumen).

  2. Configuration Add the FCM API key to your .env:

    FCM_API_KEY=your_server_key_here
    

    Create a config file (e.g., config/fcm.php) to mirror the Symfony bundle’s YAML:

    return [
        'authentication_api_key' => env('FCM_API_KEY'),
    ];
    
  3. First Use Case Send a basic notification to a single device:

    use DigitalAp\FcmHttpBundle\Notification;
    use DigitalAp\FcmHttpBundle\Message;
    
    $notification = new Notification('Hello', 'This is a test notification');
    $message = new Message(['device_token_here']);
    $message->setNotification($notification);
    
    // Inject the FCM sender service (see "Implementation Patterns" for DI setup)
    $fcmSender = app('fcm_http.send');
    $fcmSender->send($message);
    

Implementation Patterns

Workflows

  1. Notification vs. Data Payload

    • Use Notification for user-facing alerts (title/body/sound).
    • Use Data payload (via $message->setData(['key' => 'value'])) for background processing (e.g., syncing data).
    • Rule: A Message must have either a Notification or Data, but not both (FCM enforces this).
  2. Batching Tokens The bundle auto-batches tokens in chunks of 1,000 (FCM’s limit). For 1,500 tokens:

    $message = new Message(range(1, 1500)); // Automatically split into 2 requests.
    
  3. Service Integration

    • Laravel Service Provider: Register the bundle’s services in AppServiceProvider:
      public function register() {
          $this->app->bind('fcm_http.send', function ($app) {
              return new \DigitalAp\FcmHttpBundle\Sender(
                  $app['config']['fcm.authentication_api_key']
              );
          });
      }
      
    • Controller Injection:
      public function sendNotification(FcmSender $fcmSender) {
          // Use $fcmSender->send($message)
      }
      
  4. Customizing Headers Extend the Sender class to add headers (e.g., for priority):

    class CustomFcmSender extends \DigitalAp\FcmHttpBundle\Sender {
        protected function getHeaders() {
            $headers = parent::getHeaders();
            $headers['X-Priority'] = 'high';
            return $headers;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle

    • Last updated in 2016 (pre-FCM v1 API). The HTTP v1 endpoint requires changes to the Sender class (e.g., adding Authorization: key=... header instead of Authorization: Bearer ...).
    • Fix: Override the getHeaders() method in a custom Sender class to use HTTP v1 format:
      protected function getHeaders() {
          return [
              'Content-Type'  => 'application/json',
              'Authorization' => 'key=' . $this->apiKey,
          ];
      }
      
  2. Token Validation

    • The bundle doesn’t validate tokens before sending. Always sanitize/validate tokens server-side (e.g., check against a device_tokens table).
  3. Error Handling

    • FCM returns HTTP 4xx/5xx codes. The bundle doesn’t parse responses by default. Extend the Sender to log errors:
      public function send(Message $message) {
          try {
              $response = $this->httpClient->post($this->url, [
                  'headers' => $this->getHeaders(),
                  'body'    => json_encode($message->toArray()),
              ]);
              if ($response->getStatusCode() !== 200) {
                  throw new \RuntimeException($response->getBody());
              }
          } catch (\Exception $e) {
              \Log::error('FCM Error: ' . $e->getMessage());
              throw $e;
          }
      }
      
  4. Configuration Quirks

    • The bundle expects fcm_http.autentication_api_key in YAML. Use config('fcm.authentication_api_key') in Laravel (adjust keys to match your config file).

Tips

  1. Testing Use Firebase’s debug token (dY...) to test notifications without hitting rate limits.

  2. Performance

    • Batch tokens to minimize API calls (the bundle handles this, but ensure your token list is optimized).
    • Cache API responses if retrying failed messages (e.g., with Laravel’s Cache facade).
  3. Extending Functionality

    • Add Topics: Modify the Message class to support topics:
      public function addTopic($topic) {
          $this->data['topic'] = $topic;
      }
      
    • Conditional Messages: Use FCM’s condition attribute to target devices with specific data:
      $message->setCondition('"priority" in topics/"news" || "priority" == "high"');
      
  4. Logging Log all FCM payloads for debugging:

    \Log::debug('FCM Payload', ['payload' => $message->toArray()]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php