untuk Menyimpan Token kita perlu membuat migrasi dan model. bisa dengan command seperti berikut
php artisan make:model FirebaseAuthToken -m
Setelah dibuat. buka file nya dan sesuaikan seperti berikut
public function up(): void
{
Schema::create('firebase_auth_tokens', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->cascadeOnUpdate()->cascadeOnDelete();
$table->string('token');
$table->timestamps();
});
}
Buka File config/services.php dan tambahkan kode berikut.
'firebase' => [
'project_id' => env('FIREBASE_PROJECT_ID'),
'file_json' => env('FIREBASE_CONFIG_FILE')
],
Jangan lupa tambah juga di ENV Varibale nya
FIREBASE_PROJECT_ID=blablablaaaa....
FIREBASE_CONFIG_FILE=blablablaaaa....
buat file baru dengan nama FirebaseMessagingService.php di App\Services
<?php
namespace App\Services;
use Google_Client;
use Illuminate\Support\Facades\Storage;
class FirebaseMessagingService
{
public function sendNotification($title, $body, $token, $payload = null)
{
$jsonConfig = config('services.firebase.file_json');
$projectId = config('services.firebase.project_id');
$credentialsFilePath = storage_path('app/json/'.$jsonConfig);
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->refreshTokenWithAssertion();
$client = $client->getAccessToken();
$access_token = $client['access_token'];
$headers = [
"Authorization: Bearer $access_token",
'Content-Type: application/json'
];
$data = [
"message" => [
"token" => $token,
"notification" => [
"title" => $title,
"body" => $body,
],
"data" => $payload
]
];
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output for debugging
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
\Log::error('FCM Notification Error: ' . $err);
} else {
$responseData = json_decode($response);
\Log::info('FCM Notification Sent: ' . json_encode($responseData));
}
}
}
- Import
use App\Services\FirebaseMessagingService;
- Gunakan
public function sendNotification(FirebaseMessagingService $firebaseMessagingService)
{
$users = User::whereHas('firebaseTokens')->get();
foreach ($users as $user) {
$firebase = FirebaseAuthToken::where('user_id', $user->id)
->orderBy('id', 'desc')
->first();
if ($firebase) {
$firebaseMessagingService->sendNotification($this->notif_title, $this->notif_body, $firebase->token);
}
}
}
contoh diatas untuk mengirim ke seluruh pengguna yang memiliki token