PHP code example of andydefer / push-notifier

1. Go to this page and download the library: Download andydefer/push-notifier 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/ */

    

andydefer / push-notifier example snippets




ndydefer\PushNotifier\Core\NotificationFactory;

// 1. Créer une factory
$factory = new NotificationFactory();

// 2. Créer un service Firebase à partir du fichier JSON
$firebaseService = $factory->makeFirebaseServiceFromJsonFile(
    __DIR__ . '/storage/firebase-credentials.json'
);

// 3. Envoyer une notification simple
$deviceToken = 'votre_token_appareil_fcm';

$response = $firebaseService->sendInfo(
    $deviceToken,
    'Bonjour !',
    'Ceci est ma première notification push.'
);

if ($response->success) {
    echo "Notification envoyée avec succès ! ID : " . $response->messageId;
} else {
    echo "Échec de l'envoi : " . $response->errorMessage;
}

$factory = new NotificationFactory();

// Créer un service de différentes manières
$service = $factory->makeFirebaseServiceFromJsonFile($jsonPath);
$service = $factory->makeFirebaseServiceFromJsonString($jsonContent);
$service = $factory->makeFirebaseServiceFromArray($configArray);
$service = $factory->makeFirebaseServiceFromEnv($_ENV);

// Exemple : Utiliser un client HTTP personnalisé
use App\Services\MyCustomHttpClient;

$factory = new NotificationFactory(
    new MyCustomHttpClient() // Injecté ici
);
$service = $factory->makeFirebaseServiceFromJsonFile($jsonPath);

use Andydefer\PushNotifier\Dtos\FcmMessageData;

// Notification d'information (title et body uniquement)
$info = FcmMessageData::info('Mise à jour', 'Nouvelle version disponible.');

// Notification silencieuse (avec connected: true par défaut)
$ping = FcmMessageData::ping();

$message = FcmMessageData::make(
    type: 'CHAT_MESSAGE',
    data: [
        'title' => 'Nouveau message',
        'body' => 'Vous avez reçu un message',
        'senderId' => '123',
        'senderName' => 'Jean',
        'conversationId' => '456'
    ]
);

$tokens = ['token1', 'token2', 'token3'];
$message = FcmMessageData::make('PROMO', [
    'title' => 'Promo Flash',
    'body' => '-50% sur tout !'
]);

$results = $firebaseService->sendMulticast($tokens, $message);

foreach ($results as $token => $response) {
    if ($response->success) {
        // Succès
    } else if ($response->isInvalidToken()) {
        // Token invalide, à supprimer
    }
}

if ($firebaseService->validateToken($deviceToken)) {
    // Token valide
} else {
    // Token invalide, à supprimer
}

try {
    $response = $firebaseService->send($token, $message);
} catch (FcmSendException $e) {
    $errorResponse = FcmResponseData::fromError(
        $e->getErrorCode() ?? 'UNKNOWN',
        $e->getMessage(),
        $e->getStatusCode()
    );

    if ($errorResponse->isInvalidToken()) {
        // Marquer le token comme invalide
    } elseif ($errorResponse->isQuotaExceeded()) {
        // Gérer le dépassement de quota
    }
}

// Via fichier JSON (recommandé)
$service = $factory->makeFirebaseServiceFromJsonFile('/path/to/credentials.json');

// Via chaîne JSON
$jsonContent = file_get_contents('/path/to/credentials.json');
$service = $factory->makeFirebaseServiceFromJsonString($jsonContent);

// Via tableau PHP
$config = [
    'project_id' => 'votre-projet-id',
    'client_email' => 'firebase-adminsdk-xxx@...',
    'private_key' => "-----BEGIN PRIVATE KEY-----\nMII...\n-----END PRIVATE KEY-----\n",
];
$service = $factory->makeFirebaseServiceFromArray($config);

// Via variables d'environnement
$service = $factory->makeFirebaseServiceFromEnv($_ENV);