Mani Sankar
Mani Sankar

Reputation: 821

Firebase message not received while using api

I am using Firebase API using php and sending the post data using JSON format. The response is giving me the message_id but the message is not getting delivered.

When I used the Firebase Console instead of API with the same fields, it got delivered successfully.

My php code:

<?php

$json_data = '{ "data": { 
                  "title": "Hey you got a message",
                  "text": "Hi from firebase api"
                },
                "to": "/topics/all",
                "priority": "high"
              }';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: application/json',
                                            'Authorization:key="Used my server key here"'
                                          ));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>

Response:

{"message_id":64666973642901*****}

PS: Used asterisks to hide information.

UPDATE: The message is being delivered when I set the to field to a particular token. But not working when it is set to topics/all. Is there any other way we can send it to all those that are associated to the app just like in the console?

Upvotes: 4

Views: 591

Answers (1)

Mani Sankar
Mani Sankar

Reputation: 821

I finally found out. At first our app will not contain any topics and we have to create them explicitly.

Use the following method in your app to subscribe for a topic

FirebaseMessaging.getInstance().subscribeToTopic("NAME OF TOPIC");

So to send it to all app users use the above method to make each of your user to subscribe for a particular topic. I created it with a name "all".

Now set your to field in JSON HTTP POST request to topics/NAME OF TOPIC or topics/all in my case.

NOTE: While subscribing to a topic, new topic will be created automatically if no topic exists by that name.

Upvotes: 3

Related Questions