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:
$serverKey
: Ganti dengan Server Key dari Firebase Console Anda (bagian "Cloud Messaging").$fcmToken
: Token perangkat yang diperoleh dari aplikasi frontend.- Payload: Mengirim data tambahan ke aplikasi frontend melalui parameter
data
.
Cara Menggunakan:
- Salin script di atas ke file PHP Anda.
- Pastikan server Anda mendukung cURL.
- Ganti
YOUR_SERVER_KEY_HERE
dengan server key Firebase Anda. - 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:
- Buat Service Account Key dari Firebase Console.
- 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
Fitur | Metode Lama (Server Key) | Metode Baru (OAuth Token) |
---|---|---|
Endpoint | /fcm/send | /v1/projects/{projectId}/messages:send |
Autentikasi | Server Key | OAuth 2.0 (Service Account) |
Keamanan | Moderate | Tinggi |
Kontrol Proyek | Global Server Key | Granular (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.