React Native Expo 앱에서 FCM 푸시 알림을 받기 위한 설정은 위 포스팅을 확인하시면 됩니다.
https://nonmajor-be-developer.tistory.com/entry/React-Native-Expo-FCM-%ED%91%B8%EC%8B%9C-%EC%95%8C%EB%A6%BC-%EC%84%A4%EC%A0%95
React Native Expo FCM 푸시 알림 설정
본 포스팅에서 다뤄볼 것1. Firebase FCM2. FCM 서비스 계정 키 얻기3. FCM 서비스 키 얻기4. Expo, FCM push token 얻기5. push 알림 채널 및 설정6. 포그라운드 알림 설정7. 포그라운드 알림 처리8. 알림 클릭 처
nonmajor-be-developer.tistory.com
서버에서 FCM 푸시 알림을 보내기 위해선 firebase FCM 서비스 계정 키가 필요합니다.
해당 키와 연결되어 빌드된 앱에만 푸시 알림을 보내기 위한 검증이라고 생각하시면 됩니다. 권한이 없는 자가 앱에 푸시 알림을 보내는 것을 방지하기 위한 필수 조건입니다.
1. FCM 서비스 계정 키 발급
기존에 발급받은 서비스 계정 키가 없다면, 아래 링크 포스팅에서 2. FCM 서비스 계정 키 얻기를 참고해 주세요.
* 서비스 계정 키 json은 아래 예시처럼 key와 value가 있습니다.
{
"type": "service_account",
"project_id": "xxxxxx-xxxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----xxxxxx",
"client_email": "xxxxxxxxxxxx",
"client_id": "000000000000000000",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/xxxxx",
"universe_domain": "googleapis.com"
}
React Native Expo FCM 푸시 알림 설정
본 포스팅에서 다뤄볼 것1. Firebase FCM2. FCM 서비스 계정 키 얻기3. FCM 서비스 키 얻기4. Expo, FCM push token 얻기5. push 알림 채널 및 설정6. 포그라운드 알림 설정7. 포그라운드 알림 처리8. 알림 클릭 처
nonmajor-be-developer.tistory.com
만약 기존 서비스 계정 키를 분실하였다면 새로 발급받아야 하며 기존 키는 사용이 불가능합니다.
https://console.firebase.google.com/
로그인 - Google 계정
이메일 또는 휴대전화
accounts.google.com
2. Node FCM 초기 설정
이미 backend 초기 설정이 되어있는 경우 생략하셔도 됩니다.
패키지 생성
npm init
1. FCM 서비스 계정 키 발급에서 받은 json 파일을 루트 위치에 저장합니다.
Node.js 환경에서 FCM 푸시 알림을 보내는 방법은 두 가지가 있습니다.
1. GoogleAuth 인증 방식을 이용한 axios 방식
2. Firebase Admin SDK을 이용한 방식
두 방식 모두 아직 유효하고 많이 사용 중이므로 프로젝트 특성에 맞게 적합한 방식을 선택해 사용하면 되겠습니다.
다른 google cloud 서비스와 연계하지 않는다면 직관적이고 firebase에 특화된 두 번째 방식을 추천합니다.
3. GoogleAuth 인증 방식
GoogleAuth 인증 방식도 인증 토큰 발행 방식에 따라 두 가지 방법이 있습니다.
첫 번째 JWT 직접 사용하여 토큰을 얻는 방식
https://docs.expo.dev/push-notifications/sending-notifications-custom/#fcmv1-server
Send notifications with FCM and APNs
Learn how to send notifications with FCM and APNs.
docs.expo.dev
import { JWT } from 'google-auth-library';
function getAccessTokenAsync(
key: string // Contents of your FCM private key file
) {
return new Promise(function (resolve, reject) {
const jwtClient = new JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/cloud-platform'],
null
);
jwtClient.authorize(function (err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
공식문서에 나와있는 인증 방식입니다.
두 번째 google-auth 라이브러리를 사용해 자동으로 인증을 관리하고 클라이언트를 생성하여 토큰을 얻는 방식
https://firebase.google.com/docs/cloud-messaging/auth-server?hl=ko#provide-credentials-using-adc
전송 요청 승인 | Firebase Cloud Messaging
2024년 데모 데이에서, Firebase를 사용하여 AI 기반 앱을 빌드하고 실행하는 방법에 관한 데모를 시청하세요. 지금 시청하기 의견 보내기 전송 요청 승인 컬렉션을 사용해 정리하기 내 환경설정을
firebase.google.com
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
두 가지 방식의 차이는 크게 없지만 보안과 유지보수 측면에서 최신 방식인 두 번째 방법을 추천합니다.
const { GoogleAuth } = require("google-auth-library");
const axios = require("axios");
// 서비스 계정 키 파일
// 수정 1: 서비스 계정 키 파일 경로를 수정합니다.
const serviceAccount = require("./yeonhub-7cbc9-firebase-adminsdk-qbr9d-f0329aef64.json");
// FCM URL 주소
// 수정 2: FCM URL 주소를 수정합니다.
const FCM_URL =
"https://fcm.googleapis.com/v1/projects/yeonhub-7cbc9/messages:send";
const sendNotification = async (token) => {
try {
// 인증 토큰 생성
const auth = new GoogleAuth({
credentials: serviceAccount,
scopes: ["https://www.googleapis.com/auth/firebase.messaging"],
});
// 인증 토큰 획득
const client = await auth.getClient();
// 액세스 토큰 획득
const accessToken = await client.getAccessToken();
// 요청 헤더
const headers = {
Authorization: `Bearer ${accessToken.token}`,
"Content-Type": "application/json",
};
// 요청 데이터
const requestBody = {
message: {
token: token,
notification: {
title: "알림 제목 - axios",
body: "알림 내용 - axios",
},
data: {
customData1: "value1-axios",
customData2: "value2-axios",
customData3: "value3-axios",
},
android: {
notification: {
channel_id: "announce",
sound: "default",
},
},
},
};
// FCM 요청 전송
const response = await axios.post(FCM_URL, requestBody, { headers });
console.log("Successfully sent message:", response.data);
} catch (error) {
console.error("Error sending message:", error.response?.data || error);
}
};
// 알림을 받는 디바이스의 FCM 토큰
// 수정 3: 알림을 받는 디바이스의 FCM 토큰을 수정합니다.
const fcmToken = "eLW_6RnXQNqKG6P5uhBeYk:APA91bFhoHqYV7nXri4MMAOwW0c9eRJxkKfrayds93TRUlKRo5I38JadwsV5cECbr5qIuhWihiN464V_RkbRk8oNpFDzWgaqVXME3p3IkmUJzIds9fTOvl8";
sendNotification(fcmToken);
📢 수정할 사항
1. serviceAccount 변수에 본인의 서비스 계정 키의 path를 넣어주세요. (경로, 파일명 주의)
2. FCM_URL 주소를 본인에 맞게 수정해 주세요 서비스 계정 키 json의 project_id에 명시되어 있습니다.
3. fcmToken 변수에도 마찬가지로 본인의 fcm token을 넣어주시면 됩니다.
필요한 라이브러리를 설치합니다.
npm install google-auth-library axios
1. 서비스 계정 키 기반으로 인증 토큰 발급
2. 액세스 토큰 헤더에 담기
3. 알림의 내용이 되는 요청 데이터 작성
4. FCM_URL로 body, 헤더 전송
위 순서로 로직이 흘러가며 알림 요청이 전송됩니다.
4. Firebase Admin SDK 방식
firebase admin 라이브러리는 firebase에 특화되었기 때문에 코드를 더 간단하게 구현할 수 있습니다.
const admin = require("firebase-admin");
// 서비스 계정 키 파일
// 수정 1: 서비스 계정 키 파일 경로를 수정합니다.
const serviceAccount = require("./yeonhub-7cbc9-firebase-adminsdk-qbr9d-f0329aef64.json");
// Firebase Admin 초기화
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const sendNotification = async (token) => {
const message = {
notification: {
title: "알림 제목 - firebase-admin",
body: "알림 내용 - firebase-admin",
},
token: token,
data: {
customData1: "value1-firebase-admin",
customData2: "value2-firebase-admin",
customData3: "value3-firebase-admin",
},
android: {
notification: {
channel_id: "announce",
sound: "default",
},
},
};
try {
const response = await admin.messaging().send(message);
console.log("Successfully sent message:", response);
} catch (error) {
console.error("Error sending message:", error);
}
};
// 알림을 받는 디바이스의 FCM 토큰
// 수정 2: 알림을 받는 디바이스의 FCM 토큰을 수정합니다.
const fcmToken =
"eLW_6RnXQNqKG6P5uhBeYk:APA91bFhoHqYV7nXri4MMAOwW0c9eRJxkKfrayds93TRUlKRo5I38JadwsV5cECbr5qIuhWihiN464V_RkbRk8oNpFDzWgaqVXME3p3IkmUJzIds9fTOvl8";
sendNotification(fcmToken);
📢 수정할 사항
1. serviceAccount 변수에 본인의 서비스 계정 키의 path를 넣어주세요. (경로, 파일명 주의)
2. fcmToken 변수에도 마찬가지로 본인의 fcm token을 넣어주시면 됩니다.
firebase-admin 라이브러리 설치
npm install firebase-admin
본 예시 코드를 활용해 특정 날짜/시간에 알림을 보내거나(crontab 스케줄러) 특정 이벤트 상황에서 해당 유저에게만 알림을 보낼 수 있습니다. 또한 유저마다 다른 내용, 정보를 담아 보낼 수 있습니다.
각자 상황에 맞는 요구사항을 충족할 수 있는 기능들을 프로그래밍해 보시길 바랍니다.
⚠️ 서비스 계정 키, FCM token, Axios 사용 시 FCM_URL 수정할 사항들을 모두 체크 후 사용해 주세요.
https://github.com/yeonhub/yeonhub-post/tree/noti
GitHub - yeonhub/yeonhub-post
Contribute to yeonhub/yeonhub-post development by creating an account on GitHub.
github.com