How to use FCM topics for notification in chat app

2019-08-25 13:39发布

I am make chat feature with Flutter and Firestore backend.

Every message is new document in Firestore collection with UID and text field. Chat is 1:1 and random so no know who user will talk to before enter chat. DocID in chat collection are all auto-id.

I have read can use topics to manage send notification. This should be easier than use individual device fcm token.

Anyone know how to implement use topic for this random 1:1 chat app?

2条回答
仙女界的扛把子
2楼-- · 2019-08-25 13:50

I found Frank's comment really interesting about the "sorted userID composed key". I would probably use that as the chat key in the database (realtime/firestore), however, for the notifications I think I would still use a topic for each user - this way I would be able to avoid notifying the user who posted the message. If that wouldn't be an issue, then just go for just one topic per chatroom.

Also mentioning Frank, I would probably use extra keys in all topic names to make them really difficult to guess. (but add that later so you don't get distracted with non core stuff)

In this answer you have an example of how to post the notifications with a onCreate trigger to a topic (from a functions backend).

In the flutter code, you can use subscribeToTopic from the firebase_messaging plugin to start listening to a topic.

Note: if your app will support user log-off [probably it will :)], then you'll also have to delete the token in the device to avoid receiving notifications from the last logged user.

查看更多
三岁会撩人
3楼-- · 2019-08-25 14:00

You can definitely use a separate topic for each 1:1 conversation, for example with the naming scheme I described here: Best way to manage Chat channels in Firebase. But there are some things to consider which, as Doug already pointed out in his comment, leads most developers to not solely use FCM for their chat apps.

For example: FCM topics are not secured. This means that anyone who finds out the topic ID can subscribe to it, and thus overhear the 1:1 conversation. And while you can generate topics that are hard to guess, you should not rely on not knowing the topic ID as a security mechanism.

Another reason to consider alternatives is that FCM messages are transient: once they are delivered there is no longer any trace of them. With your current Firestore implementation you can query the database to get all messages to show, while with a pure FCM implementation you will have to build your own database (if that is required for your app).

For these reasons most chat apps I know of use a combination of FCM (for push notifications) and an online database (for persistence) as their backend services.

查看更多
登录 后发表回答