如何使用Node.js向所有Android设备发送FCM通知

4
我想从Node.Js代码向使用Ionic t开发的我的Android应用发送通知。我已尝试以下代码并收到“其中一个主题、令牌或条件是必需的”的错误消息。如何在没有任何条件的情况下向所有用户发送通知?
var serviceAccount = require("/path/to/config.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myApp.firebaseio.com"
});

var message = {
    notification: {
      title: '$GOOG up 1.43% on the day',
      body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
    }
  };


admin.messaging().send(message).then(res=>{
    console.log("Success",res)
}).catch(err=>{
    console.log("Error:",err)
})
1个回答

8
如果您想向所有用户发送通知,则最好将用户注册到特定主题,例如food,然后注册到该主题的所有用户都将收到通知。
在您上面的代码中,出现错误是因为您没有提供要发送通知的对象。
如果token:
var registrationToken = 'YOUR_REGISTRATION_TOKEN'; <-- token of user
var message = {
notification: {
  title: '$GOOG up 1.43% on the day',
  body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
token: registrationToken
};

如果主题:
var topic = 'food';
var message = {
notification: {
  title: '$GOOG up 1.43% on the day',
  body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
  topic: topic
};

这里有更多信息:

https://firebase.google.com/docs/cloud-messaging/admin/send-messages

(注:该链接为Firebase的云消息传递文档,提供了发送消息的相关信息。)

2
有没有办法像在Firebase通知控制台中发送所有用户一样指定包? - Santosh Hegde
您想从控制台发送吗? - Peter Haddad
不,我想通过Node.JS代码发送。 但是我想要提到包名,就像我们在控制台中指定的那样,所有拥有该应用程序的用户都将收到通知。 - Santosh Hegde
啊,这是一个例子:https://stackoverflow.com/questions/40052813/android-push-notifcation-toward-an-specified-application-package(唯一的方法是通过主题)。 - Peter Haddad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接