PHP code example of swanflutter / notification-master

1. Go to this page and download the library: Download swanflutter/notification-master library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

swanflutter / notification-master example snippets


use SwanFlutter\NotificationMaster\FirebasePush;

$push = new FirebasePush('/path/to/service-account.json');

// or pass the decoded array directly:
$push = new FirebasePush([
    'type'         => 'service_account',
    'project_id'   => 'my-project',
    'private_key'  => '-----BEGIN RSA PRIVATE KEY-----...',
    'client_email' => '[email protected]',
]);

return [
    // Path to your Firebase service-account JSON (or the decoded array).
    'credentials' => env('FIREBASE_CREDENTIALS', storage_path('app/firebase/service-account.json')),

    // Validate payload without sending to devices (staging/testing).
    'dry_run' => env('PUSH_DRY_RUN', false),

    // Automatic retries on transient errors (429 / 5xx). Set 0 to disable.
    'retries'        => env('PUSH_RETRIES', 1),
    'retry_delay_ms' => env('PUSH_RETRY_DELAY_MS', 500),

    // Polling mode store driver: 'cache' (default) or 'array' (in-memory).
    'poll_store' => env('PUSH_POLL_STORE', 'cache'),

    // TTL in seconds for the cache-backed poll store.
    'poll_ttl' => env('PUSH_POLL_TTL', 86400),
];

use SwanFlutter\NotificationMaster\FirebasePush;
use SwanFlutter\NotificationMaster\Message;

$push = new FirebasePush(config('push-notification.credentials'));

$push->sendToToken(token: 'device-registration-token', title: 'Hello', body: 'World');

$push->sendToTopic(topic: 'news', title: 'Breaking News', body: 'Something just happened.');

use SwanFlutter\NotificationMaster\Message;

$push->send(
    Message::create()
        ->toCondition("'sports' in topics || 'tech' in topics")
        ->title('Multi-topic alert')
        ->body('This goes to sports and tech subscribers.')
);

$tokens = ['token-1', 'token-2', 'token-3'];

$results = $push->sendToMany($tokens, Message::create()
    ->title('Broadcast')
    ->body('Hello everyone!')
);

foreach ($results as $token => $result) {
    if ($result['success']) {
        echo "Sent to {$token}\n";
    } else {
        echo "Failed for {$token}: {$result['error']}\n";
    }
}

use SwanFlutter\NotificationMaster\Message;

$message = Message::create()
    ->toToken('device-token')
    ->title('Flash Sale!')
    ->body('50% off — today only.')
    ->image('https://cdn.example.com/banner.jpg')
    ->data([
        'route'      => 'shop',
        'product_id' => '42',
    ])
    ->ttl(3600)
    ->android([
        'priority'     => 'high',
        'notification' => [
            'channel_id' => 'promotions',
            'sound'      => 'default',
        ],
    ])
    ->apns([
        'payload' => [
            'aps' => [
                'sound' => 'default',
                'badge' => 1,
            ],
        ],
    ])
    ->webpush([
        'notification' => ['icon' => '/icon.png'],
    ])
    ->analyticsLabel('flash_sale_july');

$push->send($message);

$push->sendRaw([
    'message' => [
        'token'        => 'device-token',
        'notification' => ['title' => 'Raw', 'body' => 'Payload'],
    ],
]);

// Messages are validated but NOT delivered.
$push->dryRun()->send($message);

// 3 retries, 1 second base delay (doubled each attempt).
$push->withRetries(3, 1000)->send($message);

use Illuminate\Notifications\Notification;
use SwanFlutter\NotificationMaster\Message;

class OrderShipped extends Notification
{
    public function via(object $notifiable): array
    {
        return ['fcm'];
    }

    public function toFcm(object $notifiable): Message
    {
        return Message::create()
            ->title('Your order has shipped!')
            ->body("Order #{$this->order->id} is on its way.")
            ->data(['order_id' => (string) $this->order->id]);
    }
}

// In your User model:
public function routeNotificationForFcm(): string
{
    return $this->fcm_token;
}

$user->notify(new OrderShipped($order));

use SwanFlutter\NotificationMaster\Laravel\Facades\PushNotification;
use SwanFlutter\NotificationMaster\Message;

PushNotification::sendToToken(token: 'device-token', title: 'Hi', body: 'Hello from facade!');

PushNotification::send(
    Message::create()->toTopic('alerts')->title('Alert')->body('Pay attention.')
);

use SwanFlutter\NotificationMaster\Polling\NotificationPoller;
use SwanFlutter\NotificationMaster\Message;

$poller = app(NotificationPoller::class);

$id = $poller->enqueue(
    recipientId: (string) $user->id,
    message: Message::create()
        ->title('New message')
        ->body('You have a new message from Alice.')
        ->data(['chat_id' => '99']),
);

$poller->enqueue(
    recipientId: (string) $user->id,
    message: $message,
    deliverAt: new \DateTimeImmutable('+30 minutes'),
);

// routes/api.php
Route::middleware('auth:sanctum')->get('/notifications/poll', function (Request $request) {
    $poller        = app(\SwanFlutter\NotificationMaster\Polling\NotificationPoller::class);
    $notifications = $poller->poll((string) $request->user()->id);

    return response()->json(['notifications' => $notifications]);
});

use SwanFlutter\NotificationMaster\Contracts\PushNotificationInterface;
use SwanFlutter\NotificationMaster\Polling\NotificationPoller;

$results = app(NotificationPoller::class)->flushAndSend(
    deviceToken: $user->fcm_token,
    recipientId: (string) $user->id,
    sender:      app(PushNotificationInterface::class),
);

use SwanFlutter\NotificationMaster\Polling\Store\PollStoreInterface;

class DatabasePollStore implements PollStoreInterface
{
    public function push(string $recipientId, array $notification): void
    {
        DB::table('push_notifications')->insert([
            'recipient_id' => $recipientId,
            'payload'      => json_encode($notification),
            'delivered'    => false,
            'created_at'   => now(),
        ]);
    }

    public function pending(string $recipientId): array
    {
        return DB::table('push_notifications')
            ->where('recipient_id', $recipientId)
            ->where('delivered', false)
            ->get()
            ->map(fn($row) => json_decode($row->payload, true))
            ->toArray();
    }

    public function markDelivered(string $recipientId, array $ids): void
    {
        DB::table('push_notifications')
            ->where('recipient_id', $recipientId)
            ->whereIn(DB::raw("JSON_UNQUOTE(JSON_EXTRACT(payload, '$.id'))"), $ids)
            ->update(['delivered' => true]);
    }

    public function purge(string $recipientId): void
    {
        DB::table('push_notifications')
            ->where('recipient_id', $recipientId)
            ->delete();
    }
}

use SwanFlutter\NotificationMaster\Polling\Store\PollStoreInterface;

$this->app->bind(PollStoreInterface::class, DatabasePollStore::class);

use SwanFlutter\NotificationMaster\Exceptions\SendingFailedException;
use SwanFlutter\NotificationMaster\Exceptions\PushNotificationException;

try {
    $push->send($message);
} catch (SendingFailedException $e) {
    // FCM-level error
    logger()->error('FCM error', [
        'message' => $e->getMessage(),
        'fcm'     => $e->getFcmResponse(),
    ]);
} catch (PushNotificationException $e) {
    // Any other package error (credentials, auth, validation)
    logger()->error('Push error: ' . $e->getMessage());
}

use SwanFlutter\NotificationMaster\Polling\NotificationPoller;
use SwanFlutter\NotificationMaster\Polling\Store\ArrayPollStore;
use SwanFlutter\NotificationMaster\Message;

$store  = new ArrayPollStore();
$poller = new NotificationPoller($store);

$poller->enqueue('user-1', Message::create()->toToken('t')->title('Hi')->body('Test'));

$pending = $poller->poll('user-1');
assert(count($pending) === 1);
assert($poller->count('user-1') === 0); // marked delivered
bash
php artisan vendor:publish --tag=push-notification-config