我有一个带有 Firebase Cloud Messaging 的 Flutter 应用程序。基本上,它将用户文档链接到 FCM 设备令牌。计划是每次用户向聊天或群聊发送消息时,在相同的发送方法上,都会调用像这样的另一种方法:
static void sendNotificationToUsers(
{required List<String> recepients,
required String title,
required Map<String, String> payload}) {
for (String to in recepients) {
_fcm.sendMessage(
to: to,
data: payload,
);
}
}
问题是
.sendMessage
已被弃用。它将于 2024 年 6 月被删除!我看到了关于迁移到不同 API 的这篇文章。因此,我在 pubspec.yaml 上保留了 firebase_messaging: ^14.9.1
,以实现其令牌功能,并且还添加了 firebase_cloud_messaging_flutter
,它让您输入 json 凭据,然后启动“服务器”。如果我要替换上面代码中的 _fcm.sendMessage,它将看起来像这样:
//We create the FCM server up here
//servviceAccountFileContent contains my credentials
final fcmServer = FirebaseCloudMessagingServer(
serviceAccountFileContent,
);
//Then we send the notification
var result = await fcmServer.send(
FirebaseSend(
validateOnly: false,
message: FirebaseMessage(
notification: FirebaseNotification(
title: title,
body: 'body',
),
data: payload,
android: const FirebaseAndroidConfig(
ttl: '3s',
/// Add Delay in String. If you want to add 1 minute delat then add it like "60s"
notification: FirebaseAndroidNotification(
icon: 'ic_notification',
color: '#009999',
),
),
token: to,
),
),
);
对于许多用户互相发送消息来说,拥有多个“服务器”实例是否可持续?它具有可扩展性吗?允许每个用户使用我的项目凭据是“良好做法”吗?如果没有,有什么替代方案?
提前感谢大家,祝您度过愉快的一天。
🚨 在发送给用户的应用程序中包含项目的服务帐户详细信息是一个令人难以置信的安全风险。这些凭据可用于获得对您的项目的完全管理访问权限。请不要永远这样做。🚨
一般来说,需要调用 FCM REST API 来指定仅应在受信任环境中使用的凭据。原因是任何拥有此类凭据的人都可以向所有用户发送他们想要的任何消息 - 这也是一个安全风险。
请参阅如何使用 Firebase Messaging 发送一对一消息以获得更好的解决方案。