简体   繁体   中英

Firebase subscribe to a topic dynamically

I have a scenario in my app such that, a certain event occurs and I have a list of user-id/tokens and I need to send the notification to all of those n devices. To trigger the fcm with n tokens, n time will not be feasible so I should create a topic dynamically and subscribe those n users's device id/ token to that topic.

I know I can do it from the client app, but is it possible to do that from backend. I am using Phoenix as my backend.

I found the way, writing this answer in case it help others in future

Yes Its possible to create a topic dynamically if we have the list of valid registration token s

This is the endpoint url if you want to generate a topic, given you have a list of users-

https://iid.googleapis.com/iid/v1:batchAdd

The Authorization header contains-

Content-Type- application/json
Authorization- key=<your-server-key>

The body parameters look like-

{
"to": "/topics/<topic name>",
    "registration_tokens": [
        "token1",
        "token2"
    ]
}

And now the topic is created,

You can easily sen message to that topic with- https://fcm.googleapis.com/fcm/send

Authorization token is same as previous one

And body as-

{
"priority": "HIGH",
    "notification": {
        "title": "New Text Message",
        "image": "https://firebase.google.com/images/social.png",
        "body": "Hello how are you?"
    },
    "to": "/topics/<topic name>"
}

To trigger the fcm with n tokens, n time will not be feasible

Using topics does not inherently change how FCM message delivery works. When you use a topic, the Google servers keep a mapping of that topic to the subscribed tokens. So when you call the API to send a message to a topic, the Google servers fan-out from that topic to the tokens, and then deliver the message with the same infrastructure as when you call the API with the tokens yourself.

Since you already have the tokens, so it might be simpler to just send to them directly, rather than creating a one-off topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM