Vue로 PWA 개발 - 그랜파 개발자
FCM을 보내기 위해서는 백엔드에서 전송하여야 합니다. 백엔드 로직을 사용하지만 이를 위하여 서버를 구축하지는 않습니다. Firebase Cloud Functions를 사용하여 FCM을 전송하려고 합니다.
To send Firebase Cloud Messaging (FCM) notifications from Firebase Cloud Functions, you will use the Firebase Admin SDK. Firebase Cloud Functions allow you to trigger backend logic (e.g., sending push notifications) automatically in response to database changes, HTTP requests, or other events.
Firebase Cloud Functions에서 FCM(Firebase Cloud Messaging) 알림을 보내려면 Firebase Admin SDK를 사용합니다. Firebase Cloud Functions를 사용하면 데이터베이스 변경, HTTP 요청 또는 기타 이벤트에 대한 응답으로 백엔드 로직(예: 푸시 알림 전송)을 자동으로 트리거할 수 있습니다.
Set Up Firebase Cloud Functions.
Firebase Cloud Functions 설정
Install Firebase Admin SDK.
Firebase Admin SDK를 설치합니다.
Create a Cloud Function to Send FCM.
FCM을 전송하기 위한 클라우드 기능을 생성합니다.
You need to set up Firebase Cloud Functions in your Firebase project.
Firebase 프로젝트에서 Firebase Cloud Functions를 설정해야 합니다.
firebase init functions
The Firebase Admin SDK allows your Cloud Functions to interact with Firebase services like Firestore, Authentication, and FCM.
Firebase Admin SDK를 사용하면 Cloud Functions가 Firestore, 인증, FCM과 같은 Firebase 서비스와 상호작용할 수 있습니다.
Inside the functions/ directory, install the Firebase Admin SDK:
'functions/' 디렉터리 내에 Firebase Admin SDK를 설치합니다.
cd functions
npm install firebase-admin
Inside your functions/index.js file, define a function to send push notifications using FCM.
functions/index.js 파일 내에서 FCM을 사용하여 푸시 알림을 보내는 함수를 정의하세요.
// Import required modules
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
admin.initializeApp();
// Function to send FCM notification
exports.sendNotification = functions.https.onCall(async (data, context) => {
// Extract the FCM token and message details from the function call data
const { token, title, body } = data;
// Check if the user is authenticated (optional)
if (!context.auth) {
throw new functions.https.HttpsError(
'unauthenticated',
'Only authenticated users can send notifications.'
);
}
// Message payload for the FCM notification
const message = {
notification: {
title: title,
body: body,
},
token: token, // User's FCM registration token
};
try {
// Send the FCM notification
const response = await admin.messaging().send(message);
console.log('Notification sent successfully:', response);
return { success: true, message: 'Notification sent successfully' };
} catch (error) {
console.error('Error sending notification:', error);
throw new functions.https.HttpsError(
'internal',
'An error occurred while sending the notification.'
);
}
});
FCM Token: The FCM token is sent to the function from the client app. This token uniquely identifies the device to send notifications to.
FCM 토큰: FCM 토큰은 클라이언트 앱에서 함수로 전송됩니다. 이 토큰은 알림을 보낼 장치를 고유하게 식별합니다.
Message Payload: The payload contains the notification’s title and body.
메시지 페이로드: 페이로드에는 알림의 '제목'과 '본문'이 포함됩니다.
admin.messaging().send(): This method sends the FCM message to the specified device using the token.
admin.messaging().send(): 이 메서드는 토큰을 사용하여 지정된 장치에 FCM 메시지를 보냅니다.
Error Handling: If there’s an issue, an error is thrown with a relevant message.
오류 처리: 문제가 있는 경우 관련 메시지와 함께 오류가 발생합니다.
Deploy the function to Firebase:
Firebase에 함수를 배포합니다.
firebase deploy --only functions
Once deployed, you can trigger this Cloud Function from your client-side application (e.g., a Vue.js app) using Firebase Functions' httpsCallable method.
배포한 후에는 Firebase Functions의 httpsCallable 메서드를 사용하여 클라이언트 측 애플리케이션(예: Vue.js 앱)에서 이 Cloud 함수를 트리거할 수 있습니다.
In your web or mobile app, you will call the Cloud Function using Firebase's httpsCallable() method. Here's how you can call the sendNotification function from a Vue.js component.
웹 또는 모바일 앱에서 Firebase의 httpsCallable() 메서드를 사용하여 Cloud 함수를 호출합니다. Vue.js 구성 요소에서 sendNotification 함수를 호출하는 방법은 다음과 같습니다.
import { getFunctions, httpsCallable } from "firebase/functions";
import { messaging } from "./firebase"; // Your Firebase config
async function sendPushNotification() {
const functions = getFunctions(); // Get a reference to Firebase Functions
// The FCM token of the recipient device
const token = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' });
const sendNotification = httpsCallable(functions, 'sendNotification');
// Call the cloud function to send the notification
try {
const result = await sendNotification({
token: token,
title: 'New Post Alert!',
body: 'Check out the new post on your favorite blog!',
});
console.log('Notification sent:', result);
} catch (error) {
console.error('Error sending notification:', error);
}
}
Set up Firebase Cloud Functions in your project.
프로젝트에 Firebase Cloud Functions를 설정합니다.
Install Firebase Admin SDK to use FCM from the backend.
백엔드에서 FCM을 사용하려면 Firebase Admin SDK를 설치하세요.
Create a Cloud Function (sendNotification) to send FCM notifications using admin.messaging().
admin.messaging()을 사용하여 FCM 알림을 보내는 Cloud 함수(sendNotification)를 만듭니다.
Deploy the function and call it from your client app using httpsCallable().
함수를 배포하고 httpsCallable()을 사용하여 클라이언트 앱에서 호출합니다.
Now, you have a working system for sending FCM push notifications from Firebase Cloud Functions.
이제 Firebase Cloud Functions에서 FCM 푸시 알림을 보내기 위한 작동 시스템이 완성되었습니다.