Skip to content

Instantly share code, notes, and snippets.

@cakmalik
Last active October 30, 2024 08:22
Show Gist options
  • Save cakmalik/2b8fedf7e47d41b3736a06157c4c36d8 to your computer and use it in GitHub Desktop.
Save cakmalik/2b8fedf7e47d41b3736a06157c4c36d8 to your computer and use it in GitHub Desktop.
Contoh Pembuatan Service untuk Firebase Messaging Laravel

Buat Model dan Migration

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();
        });
    }

Setup

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....

Contoh Service

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));

        }
    }
}

Contoh Penerapan

  1. Import
use App\Services\FirebaseMessagingService;
  1. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment