57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
// Impor Firebase Admin SDK
|
|
import { initializeApp, cert, getApp, getApps } from "firebase-admin/app";
|
|
import { getMessaging } from "firebase-admin/messaging";
|
|
import path from "path";
|
|
import fs from 'fs/promises'
|
|
|
|
|
|
// Fungsi untuk mengirim notifikasi FCM
|
|
export async function sendFCMNotification(token: string) {
|
|
const serviceAccount = await fs.readFile(path.join(process.cwd(), "key.json"));
|
|
if(getApps().length === 0){
|
|
initializeApp({
|
|
credential: cert(JSON.parse(serviceAccount.toString())),
|
|
});
|
|
}
|
|
|
|
try {
|
|
// Konfigurasi pesan
|
|
const message = {
|
|
notification: {
|
|
title: "Judul Notifikasi",
|
|
body: "Ini adalah isi notifikasi",
|
|
},
|
|
token,
|
|
data: {
|
|
key1: "value1",
|
|
key2: "value2",
|
|
},
|
|
// Opsional: konfigurasi Android
|
|
android: {
|
|
priority: "high",
|
|
notification: {
|
|
sound: "default",
|
|
channelId: "default_channel",
|
|
},
|
|
},
|
|
// Opsional: konfigurasi APNS (iOS)
|
|
apns: {
|
|
payload: {
|
|
aps: {
|
|
sound: "default",
|
|
},
|
|
},
|
|
},
|
|
};
|
|
|
|
// Kirim pesan
|
|
const response = await getMessaging().send(message as any);
|
|
console.log("Notifikasi berhasil dikirim:", response);
|
|
return response;
|
|
} catch (error) {
|
|
console.error("Error mengirim notifikasi:", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
sendFCMNotification('c89yuexsS_uc1tOErVPu5a:APA91bEb6tEKXAfReZjFVJ2mMyOzoW_RXryLSnSJTpbIVV3G0L_DCNkLuRvJ02Ip-Erz88QCQBAt-C2SN8eCRxu3-v1sBzXzKPtDv-huXpkjXsyrkifqvUo') |