Dev/Firebase

Firebase Functions - FCM Push Message

healthyryu 2022. 2. 15. 15:23

Firebase 서비스 계정

: node.js 에서 FCM Push 를 보내기 위해서 필요한 계정

 

index.js

const functions = require("firebase-functions");
const admin = require("firebase-admin");

const express = require("express");
const cors = require("cors");

const app = express();

app.use(cors({ origin: true }));
app.use(require("./routes/sendmessage.routes"));
exports.app = functions.https.onRequest(app);

/**
router 사용하지 않고 index.js 에서 바로 구현 시
exports.sendPushMessage = functions.https.onRequest(async (req, res) => {
    const registrationTokens = 'Firebase Token';

    const message = {
        notification: {
            title : "제목 : 메세징 테스트",
            body : "내용 : 11:14"
        },
        token: registrationTokens
    };

    admin.messaging().send(message)
        .then((response) => {
            console.log('Successfully sent message: : ', response)
        }).catch(function (err) {
            console.log('Error Sending message!!! : ', err)
        });
})
*/

 

routes/sendmessage.routes.js

const { Router } = require("express");
const router = Router();

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Firebase 비공개 생성 키
var serviceAccount = require('./firebase_api_key.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});
admin.firestore().settings({ ignoreUndefinedProperties: true })

const registrationTokens = '전송할 Firebase 토큰 값'
router.get('/sendMessage', async (req, res) => {
    const message = {
        notification: {
            title: "제목 : 메세징 테스트",
            body: "내용 : 11:14"
        },
        data: {
            title : "제목 메세지",
            body : "내용!!! : 12:53"
        },
        token: registrationTokens
    };

    admin.messaging().send(message)
        .then((response) => {
            console.log('Successfully sent message: : ', response)
            return res.status(200).json(res);
        }).catch(function (err) {
            console.log('Error Sending message!!! : ', err)
            return res.status(500).json(err);
        });
});

// Firebase 등록된 토큰
const registeredTokens = ['토큰1', '토큰2'];
router.get('/sendMessages', async (req, res) => {
    const message = {
        notification: {
            title: '제목',
            body: '내용'
        },
        tokens: registeredTokens,
    };

    admin.messaging().sendMulticast(message)
        .then((response) => {
            console.log('Successfully sent message: : ', response)
        }).catch(function (err) {
            console.log('Error Sending message!!! : ', err)
        });
})

module.exports = router;
반응형

'Dev > Firebase' 카테고리의 다른 글

Firebase Functions with Flutter  (0) 2022.02.04
Firebase - Crashlytics / 스택 추적이 안된다....  (0) 2022.01.24