向 Firebase 中的所有用户推送通知

时间:2020-12-20 07:47:11

标签: android firebase firebase-cloud-messaging pyfcm

我正在尝试使用 python 向所有用户发送推送通知。但是,我知道使用应用程序无法做到这一点,您必须使用主题(据我所知)。 有没有办法可以从应用程序中创建主题? 谢谢 编辑:我对 firebase 完全陌生(如果我很困难,很抱歉)

2 个答案:

答案 0 :(得分:1)

要为 Android 客户端订阅主题,请按照 subscribing to a topic 上的文档中所示执行操作:

FirebaseMessaging.getInstance().subscribeToTopic("weather")

然后,您可以从可信环境(例如您的开发机器、您控制的服务器或 Cloud Functions)向该主题发送消息。有关此示例,请参阅 How do you send a Firebase Notification to all devices via CURL?

答案 1 :(得分:1)

首先你需要了解一个主题不需要创建(它会自动创建),你只需要定义主题名称,例如如果你正在创建应用程序以在天气变化时接收推送通知,那么主题名称可以是“天气”。

现在你需要两个组件:移动和后端

1.移动:在您的移动应用中,您只需要 integrate the Firebase SDKsubscribe to the topic“天气”,您是如何做到的?

Firebase.messaging.subscribeToTopic("weather")

不要忘记检查文档。

2.后端: 在您的服务器中,您需要实现基于 FCM SDK 的发送方脚本。 如果您是初学者,我建议您使用 Postman 发送推送通知,然后将 FCM 集成到您的后端应用中。

您可以通过 Postman 发送此有效负载(不要忘记在标头中设置您的 API KEY)

https://fcm.googleapis.com/fcm/send

{
  "to": "/topics/weather",
  "notification": {
    "title": "The weather changed",
    "body": "27 °C"
  }
}

如果可行,您可以add FCM SDK to your backend

$ sudo pip install firebase-admin
default_app = firebase_admin.initialize_app()

最后你可以send notifications as documentation says

from firebase_admin import messaging

topic = 'weather'

message = messaging.Message(
    notification={
        'title': 'The weather changed',
        'body': '27 °C',
    },
    topic=topic,
)
response = messaging.send(message)

此处有更多详细信息:https://github.com/firebase/firebase-admin-python/blob/eefc31b67bc8ad50a734a7bb0a52f56716e0e4d7/snippets/messaging/cloud_messaging.py#L24-L40

您需要对文档保持耐心,希望我有所帮助。

相关问题