使用 Admin SDK(Node js)

首先啟動 firebase sdk 和 admin SDK

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

admin.initializeApp({
  credential: admin.credential.cert({
        //your admin credential certificate generated from the console. Follow this [link][1].
    }),
  databaseURL: "https:///<PROJECT_NAME>.firebaseio.com"
});

像第一個示例中那樣建立有效負載 JSON 字串。

var payload = {
              notification: {
                title: "Title of the notification,
                body: "Body of the notification",
              },
              data:{
                //required key value pair
              }
            };

然後呼叫不同的 send 方法傳送通知。

主題

admin.messaging().sendToTopic("/topic/", payload)
              .then(function(response) {
                console.log("Successfully sent message:", response);
              })
              .catch(function(error) {
                console.log("Error sending message:", error);
              });
            });

對於裝置

admin.messaging().sendToDevice(token, payload).then(response=>{
                       response.results.forEach((result, index) => {
                        const error = result.error;
                        if (error) {
                          console.error('Failure sending notification to', tokens, error);
                        } else{
                          console.log('Sucessfully sent to '+tokens);
                        }
                      });