Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase how to send Topic Notification

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.

like image 719
DIGITAL JEDI Avatar asked Feb 22 '17 06:02

DIGITAL JEDI


People also ask

What is topic notification?

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.


4 Answers

I fixed by replacing

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

To

$fields = array
(
    'to'  => '/topics/alerts',
    'notification'          => $msg
);
like image 107
DIGITAL JEDI Avatar answered Oct 18 '22 19:10

DIGITAL JEDI


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;
}
like image 34
Ambrus Tóth Avatar answered Oct 18 '22 20:10

Ambrus Tóth


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;
}
like image 40
Harsukh Makwana Avatar answered Oct 18 '22 18:10

Harsukh Makwana


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()

like image 2
pavel Avatar answered Oct 18 '22 19:10

pavel