Firebase Notifications through server-side code

17,053

Solution 1

Yes,you can.

1) Firstly, get the server key of your firebase project:

Project Settings -> Cloud Messaging Tab -> Copy the Server key.

2) Now, here is a sample php script to send notification to a specific device:

<?php
$ch = curl_init("https://fcm.googleapis.com/fcm/send");

//The device token.
$token = "device_token_here";

//Title of the Notification.
$title = "The North Remembers";

//Body of the Notification.
$body = "Bear island knows no king but the king in the north, whose name is stark.";

//Creating the notification array.
$notification = array('title' =>$title , 'body' => $body);

//This array contains, the token and the notification. The 'to' attribute stores the token.
$arrayToSend = array('to' => $token, 'notification' => $notification);

//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);

//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key= your_server_key_here';

//Setup curl, add headers and post parameters.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);       

//Send the request
curl_exec($ch);

//Close request
curl_close($ch);

?>

3) Output on execution:

{"multicast_id":8XXXD,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:14XX"}]} 

Solution 2

@Narendra Naidu, Hi you can try this code snippet for server side push notification. create simple java class in your sever side project code and add this method with parameter you also need some firebase credential to do this. please try following.

// Method to send Notifications from server to client end.
public final static String AUTH_KEY_FCM = "ApidhfkIjd_cAdhpa-ZZ065hskiH53Hw3g";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
// userDeviceIdKey is the device id you will query from your database     
public static void pushFCMNotification(String userDeviceIdKey) throws     Exception{

String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
String FMCurl = API_URL_FCM;     

URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");

JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title");   // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}

Please go through this ref document:

  1. https://firebase.google.com/docs/cloud-messaging/http-server-ref
  2. https://firebase.google.com/docs/cloud-messaging/server

it provides you server end information for sending notification from your server to - firebase server-to client application. Also, Find this below plain java code file (server end class) from which you will get some quick idea on same.

Please do let me know if I can be of further assistance.

Solution 3

Mostly! The documentation is under Firebase Cloud Messaging: https://firebase.google.com/docs/cloud-messaging/downstream

The main difference is that messages sent from the Notifications console get some automatic Firebase Analytics tracking: for messages you send yourself you may want to add some events to track manually.

Share:
17,053
Narendra Naidu
Author by

Narendra Naidu

Updated on June 07, 2022

Comments

  • Narendra Naidu
    Narendra Naidu almost 2 years

    The new Firebase notifications service allows us to use a Console UI to post notifications to all mobile app users.

    But I could not find any REST API for the Firebase Notifications Service. I want to send notifications to mobile users automatically through server-side code based on an event. Does Firebase Notifications Service have an API that can be accessed over HTTP/S?

  • Narendra Naidu
    Narendra Naidu almost 8 years
    Thanks Ian. Will try this out.
  • ZLNK
    ZLNK over 7 years
    it's necessary to add a ";" at the end of $title, change the name of $arryToSend to $arrayToSend, but the code works very well. Thanks!
  • Priya
    Priya about 7 years
    hi Sandeep_Devhare, do u have any java class to send notification for multiple device using Fcm.
  • Sandeep Devhare
    Sandeep Devhare about 7 years
    @Priya, Actually FCM provides two ways to target a message to multiple devices: Topic messaging which allows you to send a message to multiple devices that have opted in to a particular topic. Device group messaging which allows you to send a message to multiple devices that belong to a group you define. Please refer official document for this firebase.google.com/docs/cloud-messaging/android/send-multip‌​le Thanks.
  • Garjpreet Singh
    Garjpreet Singh almost 7 years
    Hi this code does not work on a server having SSL security. It gives me exception "No Subject alternative DNS name matching fcm.googleapis.com". Any idea about this exception?
  • Sandeep Devhare
    Sandeep Devhare almost 7 years
    @GarjpreetSingh, Use an 'ldaps' connection URL and set 'secure' attribute to 'false' in the user directory to use an SSL connection that will not verify if the hostname and certificate match.
  • Sandeep Devhare
    Sandeep Devhare almost 7 years
    @GarjpreetSingh, May be SSL certificate got expired, So disable the SSL check in source code. try some code to disable SSL check also try with above method which I mention in previous comment.
  • Poeja Network
    Poeja Network over 6 years
    Where to add this code and also how to call this on button click?