【问题标题】:Send notification over device using FCM and Flutter使用 FCM 和 Flutter 通过设备发送通知
【发布时间】:2021-07-23 12:12:44
【问题描述】:

目前我正在尝试向多个设备发送通知。我已经阅读了有关如何使用send notification to device group 的文档,他们提到我需要使用registration_ids: [...] 而不是to: token。我还在某处读到了他们提到的关于notification_key 的内容,它可以将通知发送到另一台设备。所以,我一直在寻找钥匙。但是,经过几天的浏览,我发现here 声明notification_key 已弃用。所以,我想问一下你们中是否有人知道如何在不使用控制台的情况下向多个设备发送通知。

这是我发送推送通知的代码段:

try {
  await http.post(
    Uri.parse('https://fcm.googleapis.com/fcm/send'),
    // Uri.parse('https://fcm.googleapis.com/fcm/notification'),

    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': 'key=$serverKey',
      'project_id':'....',
    },
    body: jsonEncode(
      <String, dynamic>{
        'notification': <String, dynamic>{
          'body': 'this is a body2',
          'title': 'this is a title'
        },
        'priority': 'high',
        'data': <String, dynamic>{
          'click_action':
          'FLUTTER_NOTIFICATION_CLICK',
          'id': '1',
          'status': 'done'
        },
        'registration_ids': ['fbN9aYoORhihksrTo7j5D2:APA91b......', 'fArqpgKrTJ0fL8SUKddy2F:APA91bFWf1cnVMS8.......'],
        // 'to': _token,
      },
    ),
  );
} catch (e) {
  print("error push notification");
}

如果我使用to 而不是registration_ids,它工作正常,但据我所知,如果我只想为一台设备发送通知,则使用 to。

我已经在这个问题上坚持了三天,仍然没有找到任何解决方案。他们中的大多数人都在使用控制台。你的帮助真的会让我很开心。提前谢谢!

【问题讨论】:

    标签: flutter dart push-notification firebase-cloud-messaging


    【解决方案1】:

    我找到了解决方案及其工作!

     var serverKey =
        'AAAAUb...';
    QuerySnapshot ref =
        await FirebaseFirestore.instance.collection('users').get();
    
    
    try {
      ref.docs.forEach((snapshot) async {
        http.Response response = await http.post(
          Uri.parse('https://fcm.googleapis.com/fcm/send'),
          headers: <String, String>{
            'Content-Type': 'application/json',
            'Authorization': 'key=$serverKey',
          },
          body: jsonEncode(
            <String, dynamic>{
              'notification': <String, dynamic>{
                'body': 'this is a body',
                'title': 'this is a title'
              },
              'priority': 'high',
              'data': <String, dynamic>{
                'click_action': 'FLUTTER_NOTIFICATION_CLICK',
                'id': '1',
                'status': 'done'
              },
              'to': snapshot.data() ['tokenID'],
            },
          ),
        );
      });
    } catch (e) {
      print("error push notification");
    }
    

    【讨论】:

    • firebaser here 调用 FCM REST API 要求您在代码中指定 FCM server* 键。顾名思义,此密钥应仅用于服务器端代码或其他受信任的环境中。这样做的原因是任何拥有 FCM 服务器密钥的人都可以向您的所有用户发送他们想要的任何消息。通过在您的应用程序本身中包含此密钥,恶意用户可以找到它,并且您将用户置于危险之中。请参阅stackoverflow.com/a/37993724 以获得更好的解决方案。
    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2019-10-23
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多