如何向主题发送通知

Mr *_* vd 3 dart firebase flutter firebase-cloud-messaging

我想要一个代码来将通知从一台设备发送到多台设备上的特定主题,并且我想在订阅该主题的设备上显示该通知?我将使用 firestore 来存储数据和存储令牌,并使用 Firebase 消息传递来发送通知

Fra*_*len 5

设备发送消息需要您调用 Firebase Cloud Messaging API 并指定 FCM 服务器密钥。顾名思义,此密钥只能在受信任的环境中使用,例如您的开发计算机、您控制的服务器或 Cloud Functions 等环境。之所以需要这样做,是因为拥有您的 FCM 服务器密钥的任何人都可以向您应用程序的所有用户发送消息。

最简单的开始方法是简单地运行curl命令或类似的命令,调用旧版FCM REST API。请参阅此处的示例:How can I send a Firebase Cloud Messaging notification without use the Firebase Console? 要发送到主题,请确保该to值类似于"/topics/your_topic"

对于更高的生产级别,您可能需要引入服务器或使用云功能。发送消息就变成了一个多步骤的过程,例如:

  1. 想要发送消息、将该消息写入数据库或调用 API 的客户端。
  2. 此写入操作会触发您的服务器或 Cloud Functions,后者会验证请求(确定该用户有权发送此消息)。
  3. 然后,服务器端代码调用 Firebase 管理 API 将消息发送到主题

有关此示例,请参阅repo中的此文件夹functions-samples

另请参阅:


Mr *_* vd 5

这是我发送特定主题通知的代码

我希望这对新开发人员有所帮助。

import 'package:http/http.dart' as http;

Future<void> sendNotification(subject,title) async{

final postUrl = 'https://fcm.googleapis.com/fcm/send';

String toParams = "/topics/"+'yourTopicName';

final data = {
"notification": {"body":subject, "title":title},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"sound": 'default',
"screen": "yourTopicName",
},
"to": "${toParams}"};

final headers = {
'content-type': 'application/json',
'Authorization': 'key=key'

};

final response = await http.post(postUrl,
body: json.encode(data),
encoding: Encoding.getByName('utf-8'),
headers: headers);

if (response.statusCode == 200) {
// on success do 
print("true");
} else {
// on failure do 
print("false");

}
}
Run Code Online (Sandbox Code Playgroud)

使用订阅

FirebaseMessaging _firebaseMessaging =  FirebaseMessaging();
_firebaseMessaging.subscribeToTopic("yourTopicName");
Run Code Online (Sandbox Code Playgroud)


cre*_*not 3

您可以使用和订阅主题firebase_messagingFirebaseMessaging.subscribeToTopic

FirebaseMessaging().subcribeToTopic('topic_name');
Run Code Online (Sandbox Code Playgroud)

您可以使用 Firebase 控制台或某些后端代码(例如在 Cloud Functions 中)向主题发送通知。

了解更多。