【问题标题】:How to send simple "push notification" from one device to other device?如何将简单的“推送通知”从一台设备发送到另一台设备?
【发布时间】:2021-07-11 05:02:39
【问题描述】:

我有一个使用 Flutter 制作的应用程序。我正在尝试编写一种方法让用户在我的应用程序中互相添加为朋友,但在此之前,我想将推送通知从一个设备发送到另一个设备。其实,我觉得如果我开始,我可以用我自己的算法解决剩下的。

我尝试过的方法:

  • 已安装 node.js
  • 来自项目终端:firebase 登录
  • firebase 初始化
  • 函数文件已创建并存在于我的项目中
  • 我有 index.ts 文件
  • 当应用打开时,我获得了每台设备的唯一令牌。

我想在 index.ts 文件中放一个简单的通知发送代码,但我做不到。这个通知应该可以在一台设备上运行到另一台设备上。

【问题讨论】:

    标签: android flutter dart google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

    这是发送设备到设备通知的简单解决方案。 首先创建json格式的参数,如下所示

        var params = {
      "to": "device token",
      "notification": {
      "title": "Notification Title",
      "body": "Notification Message",
      "sound": "default",
      },
      "data": {
        "customId": "01",
        "badge": 0,
        "alert": "Alert"
      }
    };
    

    然后var url = 'https://fcm.googleapis.com/fcm/send'; 作为 api 调用。 得到如下代码的响应

        var response = await http.post(url,
      headers: {
        "Authorization": "key= Web server Key over here",
        "Content-Type": "application/json"
      },body: json.encode(params)
    );
    
    if (response.statusCode == 200) {
      Map<String, dynamic> map = json.decode(response.body);
      print("fcm.google: "+map.toString());
    }
    else {
      Map<String, dynamic> error = jsonDecode(response.body);
      print("fcm.google: "+error.toString());
    }
    

    【讨论】:

    • 如何填写“Web server Key over here”部分?
    • 我尝试在移动应用中实现
    • 您从项目的 firebase 控制台获取密钥。是的,这是针对移动应用程序的。我也一直在我的移动应用程序中使用它。
    • 我找到了解决方案!我犯了一个错误,我得到的是 Web API Key 而不是 Server Key !谢谢
    • firebaser here 调用 FCM REST API 要求您在代码中指定 FCM server* 键。顾名思义,此密钥应仅用于服务器端代码或其他受信任的环境中。这样做的原因是任何拥有 FCM 服务器密钥的人都可以向您的所有用户发送他们想要的任何消息。通过在您的 Android 应用程序中包含此密钥,恶意用户可以找到它,并且您将用户置于危险之中。请参阅stackoverflow.com/a/37993724 以获得更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多