55 lines
1.5 KiB
PHP
55 lines
1.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Services\Firebase;
|
||
|
|
|
||
|
|
use Illuminate\Support\Facades\Log;
|
||
|
|
use Kreait\Firebase\Exception\FirebaseException;
|
||
|
|
use Kreait\Firebase\Exception\MessagingException;
|
||
|
|
use Kreait\Firebase\Factory;
|
||
|
|
use Kreait\Firebase\Messaging\CloudMessage;
|
||
|
|
use Kreait\Firebase\Messaging\Notification;
|
||
|
|
|
||
|
|
class FirebaseService
|
||
|
|
{
|
||
|
|
protected $messaging;
|
||
|
|
|
||
|
|
public function __construct()
|
||
|
|
{
|
||
|
|
$factory = (new Factory)
|
||
|
|
->withServiceAccount(storage_path('firebase/firebase_credentials.json'));
|
||
|
|
|
||
|
|
$this->messaging = $factory->createMessaging();
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Send FCM notification to a device token
|
||
|
|
*
|
||
|
|
* @return bool|string
|
||
|
|
*/
|
||
|
|
public function sendNotification(string $token, string $title, string $body, array $data = [])
|
||
|
|
{
|
||
|
|
$message = CloudMessage::withTarget('token', $token)
|
||
|
|
->withNotification(Notification::create($title, $body))
|
||
|
|
->withData($data);
|
||
|
|
|
||
|
|
try {
|
||
|
|
$this->messaging->send($message);
|
||
|
|
|
||
|
|
return true; // Notification sent successfully
|
||
|
|
} catch (MessagingException|FirebaseException $e) {
|
||
|
|
// Log the error
|
||
|
|
Log::error('Firebase notification failed', [
|
||
|
|
'token' => $token,
|
||
|
|
'title' => $title,
|
||
|
|
'body' => $body,
|
||
|
|
'data' => $data,
|
||
|
|
'error' => $e->getMessage(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
return $e->getMessage(); // Return error message
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|