Firebase how to send Topic Notification

34,152

Solution 1

I fixed by replacing

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'          => $msg
);

To

$fields = array
(
    'to'  => '/topics/alerts',
    'notification'          => $msg
);

Solution 2

You can send the notifications without curl (which was not available on my server). I prepared a function which can send a notification to a specified topic:

sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "new_post", "YOUR_SERVER_KEY");

function sendNotification($title = "", $body = "", $customData = [], $topic = "", $serverKey = ""){
    if($serverKey != ""){
        ini_set("allow_url_fopen", "On");
        $data = 
        [
            "to" => '/topics/'.$topic,
            "notification" => [
                "body" => $body,
                "title" => $title,
            ],
            "data" => $customData
        ];

        $options = array(
            'http' => array(
                'method'  => 'POST',
                'content' => json_encode( $data ),
                'header'=>  "Content-Type: application/json\r\n" .
                            "Accept: application/json\r\n" . 
                            "Authorization:key=".$serverKey
            )
        );

        $context  = stream_context_create( $options );
        $result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
        return json_decode( $result );
    }
    return false;
}

Solution 3

i am work with google firebase many time and i suggest my simple code for send notification on topic.

public function test()
{
    // Method - 1
    // $fcmUrl = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1';
    // $notification = [
    //     "message" => [
    //         "topic" => "foo-bar",
    //         "notification" => [
    //             "body" : "This is a Firebase Cloud Messaging Topic Message!",
    //             "title" : "FCM Message",
    //         ]
    //     ]
    // ]; 

    // Method - 2 

    $fcmUrl = 'https://fcm.googleapis.com/fcm/send';



    $notification = [
        "to" => '/topics/cbtf',
            "data" => [
                "message" : "Messaging Topic Message!",
            ]
        ]
    ];


    $headers = [
        'Authorization: key=AIza...............klQ5SSgJc',
        'Content-Type: application/json'
    ];


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$fcmUrl);
    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($notification));
    $result = curl_exec($ch);
    curl_close($ch);

    return true;
}

Solution 4

You can send notification to any of a topic in firebase. And you can do it from any language it's just a http request but Always you have to maintain the JSON format so that you can catch notification from your android part from

 public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    Timber.d("Data Payload: " + remoteMessage.getData());
}

So You need to send below JSON format

{
 "to": "\/topics\/general",
 "data": {
 "data": {
  "title": "Database Notification",
  "message": "New Data Added"
   }
 }
}

So that you can get this data set from remoteMessage.getData()

Solution 5

With particular Topic

<?php

print "testing";

function sendPushnotification($data = array()) {

  $apiKey = '';


  $fields = array('to' => '/topics/EWAP' , 'notification' => $data);
  $headers = array('Authorization: key=' .$apiKey, 'Content-Type: application/json', 'priority' => 10);

  $url = 'https://fcm.googleapis.com/fcm/send';

  // var_dump($fields);

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  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);

  return json_encode($result, true);
}


$data = array(
  'title' => 'Today topic',
  'body' => 'done buddy'
);

var_dump(sendPushnotification($data));


?>
Share:
34,152

Related videos on Youtube

DIGITAL JEDI
Author by

DIGITAL JEDI

I am a Web and Android/IOS developer.

Updated on July 15, 2022

Comments

  • DIGITAL JEDI
    DIGITAL JEDI almost 2 years

    I am using below script to send notification to particular users:

    <?php
    // API access key from Google API's Console
    define( 'API_ACCESS_KEY', 'My_API_KEY' );
    $registrationIds = array( TOKENS );
    // prep the bundle
    $msg = array
    (
        'body'  => "abc",
        'title'     => "Hello from Api",
        'vibrate'   => 1,
        'sound'     => 1,
    );
    
    $fields = array
    (
        'registration_ids'  => $registrationIds,
        '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 );
    echo $result;
    ?>
    

    Script is working fine but how can i send notification to all user who installed my app. I created a topic in my app (alerts), and i can send notification to all users via firebase console. Can anyone guide me to update above script for topic.

    • Aacs
      Aacs almost 7 years
      Can you provide the code of Push notification part in the IDE? !I have coded the php script part I dont know how to send request to the Firebase server. Please share the codes in the IDE that handle the push notification !.
  • Hamzeh Soboh
    Hamzeh Soboh about 6 years
    What if I need to send to a specific subscriber?
  • Alberto Acuña
    Alberto Acuña almost 6 years
    what is registration_ids? or how to find it, i want so send a message to eveybody, thanks!
  • DIGITAL JEDI
    DIGITAL JEDI almost 6 years
    register id are the token values which is unique to each user
  • Alberto Acuña
    Alberto Acuña almost 6 years
    @DIGITALJEDI so what if i wanna send a notification to all users, and not to each by each, im not sure if im understandig it
  • DIGITAL JEDI
    DIGITAL JEDI almost 6 years
    then u just need to subscribe them to a topic like 'to' => '/topics/alerts' . Then all users which are subscribers by default will get noticfication
  • Vyshak Puthusseri
    Vyshak Puthusseri over 4 years
    How to create the topics and how do I know which users are under these topics
  • Vyshak Puthusseri
    Vyshak Puthusseri over 4 years
    @DIGITALJEDI where to predefine these topics
  • DIGITAL JEDI
    DIGITAL JEDI over 4 years
    @VyshakPuthusseri in your Firebase Account
  • Agniswar Chakraborty
    Agniswar Chakraborty almost 2 years
    the topic is created by the user who is using the app. Try to write a code where you can create a topic forcedly by the user...