【问题标题】:Pushing Notification to all users in Firebase向 Firebase 中的所有用户推送通知
【发布时间】:2021-03-30 08:09:19
【问题描述】:

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

【问题讨论】:

  • FCM 消息来自您用来发送它的后端。您可以使用任何您想要的主题名称。应用只需要订阅它,后端只需要定位它。
  • 您好@DougStevenson 感谢您的回复。我怎样才能创建一个主题并订阅应用程序。 (对不起,我是新手)

标签: android firebase firebase-cloud-messaging pyfcm


【解决方案1】:

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

现在您需要 2 个组件:移动和后端

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

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

【讨论】:

  • 太好了,谢谢。这正是我想要的。但是,当我使用它时出现错误。错误:``` message = messages.Message(NameError: name 'messaging' is not defined```。非常感谢任何帮助。@Jonathan Nolasco Barrientos
  • 当然,你首先需要导入消息:from firebase_admin import messaging,看看这个例子github.com/firebase/firebase-admin-python/blob/…
【解决方案2】:

要让 Android 客户端订阅某个主题,请按照subscribing to a topic 上的文档中的说明进行操作:

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

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

【讨论】:

    【解决方案3】:

    上述解决方案已过时。

    让我附上适用于 python 的 firebase-admin SDK 的最新实现。

    import firebase_admin
    from firebase_admin import credentials, messaging
    
    cred = credentials.Certificate(
        "<path-to-your-credential-json>")
    firebase_admin.initialize_app(cred)
    
    topic = 'notification'
    
    message = messaging.Message(
        notification=messaging.Notification(
            title='The weather changed', body='27 °C'),
        topic=topic,
    )
    response = messaging.send(message)
    
    print(response)
    

    *一些配置的注意事项:

    1. 在 Firebase 控制台的“项目设置”->“服务帐户”->“生成新私钥”下获取您的 credential.json
    2. 确保为服务器和客户端应用程序订阅了正确的主题名称。每个订阅相同主题的客户端应用程序,无论哪些设备都会收到相应的通知。

    祝你有美好的一天~

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多