问题描述
I want to create topics on firebase on runtime. As soon as admin creates a certain record in my database, I will create the respective topic so that users associated with that topic may receive notifications using firebase.
In case of fixed topic, I am able to send the notations successfully like this:
public static function SendFireBaseBroadCast($topicName, $title, $body) {
#API access key from Google API's Console
define('API_ACCESS_KEY', 'API_KEY');
$msg = array
(
'body' => $body,
'title' => $title,
'icon' => 'myicon', /* Default Icon */
'sound' => 'mySound'/* Default sound */
);
$fields = array
(
'to' => "/topics/" . $topicName,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}
How can I create topics though on runtime on firebase?
Firebase message topics cannot be created on their own - they start to exist as soon as one device is subscribed to them and stop to exist when no device is subscribed.
From a server perspective, you can send a message to any topic of your choice (as long as the name by itself is valid). Firebase will accept the message in any case and deliver it to all subscribed devices (0 if no device is subscribed).
If you want to publish the available topics provided by your application to all the clients of your application, you need to do this separately from Firebase (e.g. with an API endpoint).
If you rename a topic in your application, you will need to re-subscribe the clients to the new topic (and preferably unsubscribe them from the old one). You can do this with the Instance ID API (https://developers.google.com/instance-id/reference/server) per instance. Please note that it‘s currently not possible to retrieve a list of all devices subscribed to a topic. It‘s also not possible to rename a topic and move all subscribed devices from one topic to another. This is business logic that you would have to implement on your application‘s level.
The Firebase Admin SDKs provide methods to manage topic subscriptions, see https://firebase.google.com/docs/admin/setup for a list of official SDKs.
If you need/want to stick to PHP, there‘s an unofficial Admin SDK at https://github.com/kreait/firebase-php (Disclaimer: I‘m the maintainer)
这篇关于使用 PHP 在 Firebase 上创建主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!