volk/php-firebase-cloud-messaging

Firebase Cloud Messaging (FCM) SDK for PHP applications

dev-master 2025-04-14 15:04 UTC

This package is auto-updated.

Last update: 2025-04-14 15:06:25 UTC


README

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send notifications at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention.

This PHP SDK provides a clean and simple way to send push notifications with Firebase Cloud Messaging from your PHP applications.

Latest Stable Version License PHP Version

Features

  • Compatible with PHP 7.1+ and Laravel 5.5+
  • Send notifications to single devices, multiple devices (up to 1000), or topics
  • Support for notification messages (visible) and data messages (invisible payload)
  • Configure message priority, time to live, and more
  • Laravel integration with auto-discovery and notification channel
  • Symfony integration
  • Easy to use and extend

Installation

composer require volk/php-firebase-cloud-messaging

Laravel 5.5+ Integration

This package supports Laravel 5.5+ with auto-discovery. Once you install the package, it will be automatically registered.

Add your Firebase Server Key to your .env file:

FCM_SERVER_KEY=your_firebase_server_key_here

And add the configuration to config/services.php:

'fcm' => [
    'key' => env('FCM_SERVER_KEY'),
],

Then you can use the Facade:

use Firebase\CloudMessaging\Laravel\Facades\FCM;
use Firebase\CloudMessaging\RequestResponse\Message;

$message = new Message();
$message->setNotification([...]);
$response = FCM::send($message);

Or use the notification channel:

// Create a notification class
class PushNotification extends Notification
{
    public function via($notifiable)
    {
        return ['fcm'];
    }
    
    public function toFcm($notifiable)
    {
        return (new Message())
            ->setNotification([
                'title' => 'Notification Title',
                'body' => 'Notification Body',
            ])
            ->setToken($notifiable->fcm_token);
    }
}

// Send the notification
$user->notify(new PushNotification());

Basic Usage

// Initialize the FCM client with your Firebase server key
$fcmClient = new FCMClient('YOUR_FIREBASE_SERVER_KEY');

// Create a new message
$message = new Message();

// Configure the notification (visible to users)
$message
    ->setNotification([
        'title' => 'Hello World',
        'body' => 'This is a test notification',
        'sound' => 'default',
        'badge' => '1'
    ])
    // Add message data (invisible payload)
    ->setData([
        'key1' => 'value1',
        'key2' => 'value2'
    ])
    // Target a specific device
    ->setToken('DEVICE_FCM_TOKEN')
    // Or target multiple devices
    // ->setTokens(['TOKEN1', 'TOKEN2', 'TOKEN3'])
    // Or target a topic
    // ->setTopic('news')
    // Add optional parameters
    ->setPriority(Priority::HIGH)
    ->setTimeToLive(86400); // 1 day in seconds

// Send the message
$response = $fcmClient->send($message);

// Check the response
echo $response->getStatusCode(); // 200 if successful
$result = $response->getResult();

Targeting Options

FCM messages can be sent to three types of targets:

  1. Single Device: Send to a specific FCM registration token

    $message->setToken('DEVICE_FCM_TOKEN');
  2. Multiple Devices: Send to multiple FCM registration tokens (up to 1000 tokens)

    $message->setTokens(['TOKEN1', 'TOKEN2', 'TOKEN3']);
  3. Topic: Send to devices subscribed to a topic

    $message->setTopic('news');

Message Types

Notification Messages

Notification messages display an alert, badge, or sound to notify the user about an incoming message. FCM handles displaying the notification on the user's device.

$message->setNotification([
    'title' => 'Notification Title',
    'body' => 'Notification Body',
    'image' => 'https://example.com/image.png', // Optional
    'sound' => 'default',
    'badge' => '1',
    'click_action' => 'OPEN_ACTIVITY' // Optional: action when notification is tapped
]);

Data Messages

Data messages contain your custom key-value pairs that are invisible to the user. Your client app is responsible for processing data messages.

$message->setData([
    'score' => '850',
    'time' => '2:45',
    'type' => 'sports',
    'custom_data' => '{"key": "value"}'
]);

Advanced Options

Message Priority

Set the priority of the message:

// Available options: Priority::HIGH, Priority::NORMAL
$message->setPriority(Priority::HIGH);

Time To Live (TTL)

Set how long (in seconds) the message should be kept if the device is offline:

$message->setTimeToLive(259200); // 3 days in seconds

Collapse Key

Group multiple messages with the same collapse key to ensure only the last message is delivered when the device comes online:

$message->setCollapseKey('updates');

Content Available

For iOS, enable background updates when data arrives:

$message->setContentAvailable(true);

Mutable Content

For iOS, allow notification service extensions to modify the notification:

$message->setMutableContent(true);

Error Handling

try {
    $response = $fcmClient->send($message);
    
    if ($response->isSuccess()) {
        echo "Message sent successfully!";
        $result = $response->getResult();
        
        // Check for successful tokens
        if (isset($result['success'])) {
            echo "Successful messages: " . $result['success'];
        }
        
        // Check for failed tokens
        if (isset($result['failure'])) {
            echo "Failed messages: " . $result['failure'];
            
            // Get detailed error information
            foreach ($result['results'] as $index => $tokenResult) {
                if (isset($tokenResult['error'])) {
                    echo "Token at index $index failed: " . $tokenResult['error'];
                }
            }
        }
    } else {
        echo "Failed to send message. Status code: " . $response->getStatusCode();
        echo "Error message: " . $response->getErrorMessage();
    }
} catch (FCMException $e) {
    echo "FCM error: " . $e->getMessage();
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}

Response Fields

Field Type Description
multicast_id string Unique ID identifying the multicast message
success integer Number of messages that were successfully processed
failure integer Number of messages that could not be processed
canonical_ids integer Number of results with canonical registration token
results array Array of objects representing the status of each token

Examples

Check the examples directory for more detailed examples:

Development & Contribution

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.