使用 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);
                        }
                      });