Ahmad Sanusi Official Let’s Talk
Ahmad Sanusi Official Website
  • Home
  • About
  • Project
  • Blog
  • Al Quran Digital
  • Al Quran Digital Lite
  • Contact

Cara mengirimkan notifikasi menggunakan Firebase Cloud Messaging (FCM) dengan PHP

Cara mengirimkan notifikasi menggunakan Firebase Cloud Messaging (FCM) dengan PHP
  • Administrator
    Written by

    Administrator

  • Category

    PHP Tips dan Trik

  • Date

    17 Januari 2025

Untuk mengirimkan notifikasi melalui  Firebase Cloud Messaging (FCM) ada beberapa cara/metode pengiriman, yaitu:

1. Metode Lama / Legacy (Server Key)

  • Masih didukung untuk kompatibilitas dengan sistem yang ada.
  • Menggunakan Server Key yang diperoleh dari Firebase Console.
  • Script di atas menggunakan metode ini.

Di bawah ini adalah contoh script untuk mengirimkan notifikasi melalui FCM menggunakan metode lama atau legacy: 

<?php
function sendFCMNotification($fcmToken, $title, $body, $data = []) {
    $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
    // Ganti dengan Server Key Anda dari Firebase Console
    $serverKey = 'YOUR_SERVER_KEY_HERE';
    // Data payload yang akan dikirim
    $notification = [
        'title' => $title,
        'body' => $body,
        'sound' => 'default', // Opsional
    ];
    $payload = [
        'to' => $fcmToken, // Token perangkat penerima
        'notification' => $notification,
        'data' => $data, // Data tambahan (opsional)
    ];
    // Inisialisasi cURL
    $ch = curl_init();
    // Konfigurasi cURL
    curl_setopt($ch, CURLOPT_URL, $fcmUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: key=' . $serverKey,
        'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    // Eksekusi permintaan
    $response = curl_exec($ch);
    // Periksa error
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        return [
            'success' => false,
            'error' => $error,
        ];
    }
    // Tutup koneksi cURL
    curl_close($ch);
    // Kembalikan respons dari FCM
    return [
        'success' => true,
        'response' => json_decode($response, true),
    ];
}
// Contoh penggunaan fungsi
$fcmToken = 'FCM_TOKEN_DEVICE_HERE'; // Ganti dengan FCM token perangkat
$title = 'Judul Notifikasi';
$body = 'Isi pesan notifikasi.';
$data = [
    'key1' => 'value1',
    'key2' => 'value2',
];
$result = sendFCMNotification($fcmToken, $title, $body, $data);
// Debugging hasil
header('Content-Type: application/json');
echo json_encode($result);

Penjelasan:

  1. $serverKey: Ganti dengan Server Key dari Firebase Console Anda (bagian "Cloud Messaging").
  2. $fcmToken: Token perangkat yang diperoleh dari aplikasi frontend.
  3. Payload: Mengirim data tambahan ke aplikasi frontend melalui parameter data.

Cara Menggunakan:

  1. Salin script di atas ke file PHP Anda.
  2. Pastikan server Anda mendukung cURL.
  3. Ganti YOUR_SERVER_KEY_HERE dengan server key Firebase Anda.
  4. Jalankan script ini di server dan pastikan token perangkat valid untuk menerima notifikasi.

Catatan: Metode ini tetap berfungsi, tetapi Firebase menyarankan untuk beralih ke metode OAuth Token untuk peningkatan keamanan dan fleksibilitas.

2. Metode Baru (OAuth Token)

  • FCM HTTP v1 API menggunakan OAuth 2.0 Bearer Token.
  • Lebih aman karena memungkinkan kontrol lebih granular terhadap akses API.
  • URL endpoint FCM HTTP v1: https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send

Keuntungan menggunakan metode baru ini diantaranya:

  • Dukungan granular untuk proyek tertentu.
  • Dapat mengelola akses melalui Google Cloud IAM.

Contoh Script PHP dengan OAuth Token

Jika ingin menggunakan API terbaru (HTTP v1) dengan OAuth Token, berikut adalah contohnya:

Langkah-Langkah:

  1. Buat Service Account Key dari Firebase Console.
  2. Instal library untuk autentikasi, seperti google/apiclient.

Contoh Script

<?php
require 'vendor/autoload.php';
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
function sendFCMNotificationV1($projectId, $message) {
    // Path ke file service account JSON Anda
    $serviceAccountPath = 'path/to/your-service-account.json';
    // Autentikasi menggunakan service account
    $credentials = new ServiceAccountCredentials(
        'https://www.googleapis.com/auth/cloud-platform',
        $serviceAccountPath
    );
    $middleware = new AuthTokenMiddleware($credentials);
    $stack = HandlerStack::create();
    $stack->push($middleware);
    // Guzzle HTTP client
    $client = new Client(['handler' => $stack]);
    // Endpoint FCM HTTP v1
    $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";
    // Kirim request
    $response = $client->post($url, [
        'headers' => [
            'Authorization' => 'Bearer ' . $credentials->fetchAuthToken()['access_token'],
            'Content-Type' => 'application/json',
        ],
        'json' => $message,
    ]);
    return json_decode($response->getBody(), true);
}
// Contoh payload FCM HTTP v1
$projectId = 'YOUR_PROJECT_ID';
$message = [
    'message' => [
        'token' => 'FCM_DEVICE_TOKEN',
        'notification' => [
            'title' => 'Judul Notifikasi',
            'body' => 'Isi Pesan Notifikasi',
        ],
        'data' => [
            'key1' => 'value1',
            'key2' => 'value2',
        ],
    ],
];
try {
    $response = sendFCMNotificationV1($projectId, $message);
    echo json_encode($response);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

 

Perbedaan Utama

FiturMetode Lama (Server Key)Metode Baru (OAuth Token)
Endpoint/fcm/send/v1/projects/{projectId}/messages:send
AutentikasiServer KeyOAuth 2.0 (Service Account)
KeamananModerateTinggi
Kontrol ProyekGlobal Server KeyGranular (IAM Permissions)

 

Metode mana yang harus dipilih?

  • Metode Lama (Server Key): Jika proyek Anda sudah menggunakan ini dan belum memerlukan fitur granular.
  • Metode Baru (OAuth): Direkomendasikan untuk proyek baru atau jika Anda menginginkan kontrol akses yang lebih baik.

 

Share:
PHP Codeigniter Composer
Blog

Popular post

Cara Mengatasi Error ONLY_FULL_GROUP_BY di Database MySQL
  • 8 Juli 2021

Cara Mengatasi Error ONLY_FULL_GROUP_BY di Database MySQL

Membuat Format Tanggal Hijriyah Bahasa Indonesia Dengan Librari PHP
  • 23 Agustus 2021

Membuat Format Tanggal Hijriyah Bahasa Indonesia Dengan Librari PHP

Cara Menghapus Cache Git
  • 18 November 2023

Cara Menghapus Cache Git

Tutorial Menginstall Codeigniter 3 dengan Composer
  • 10 Juli 2021

Tutorial Menginstall Codeigniter 3 dengan Composer

Le t’s work together

Based in Indonesia |

Looking for a hectic web developer?

[email protected]

Want a more in-depth look at my history?

-

©2025 Ahmad Sanusi Official Website, All Rights Reserved

Back to Top