42

I prepared the receiver for FCM and can send a notification to all devices.

gcm-http.googleapis.com/gcm/send with this link can send to target users who is registered and post to the target devices like below json :

 {
     "notification": {
                "title": "sample Title",
                "text": "sample text"   },   
        "to" : "[registration id]"
         }

However, I need to send notifications to target users which I choose, via email or name...etc . For example:

{
     "notification": {
                "title": "sample Title",
                "text": "sample text"   },   
        "to" : "[email or name or sex ...]"
         }

How can I do that? Do I need to create a web server or something else?

Olcay Sönmez
  • 602
  • 1
  • 7
  • 16

2 Answers2

45

Did I need to create a web server

Yes. You need a place where you can map name/email to registration IDs. These registration IDs must be included in the request to FCM, for example

{
    'registration_ids': ['qrgqry34562456', '245346236ef'],
    'notification': {
        'body': '',
        'title': ''
    },
    'data': {

    }
}

will send the push to 'qrgqry34562456' and '245346236ef'.

The registration ID you use in the call is the one that's called 'token' in this callback in the app.

public class MyService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
    }
}
Tim
  • 41,901
  • 18
  • 127
  • 145
  • thanks for your response. It's helpful for me . I read almost all document from FCM.There wirte same thing like your answer. I want to be sure. because I think there is a server for notification. – Olcay Sönmez Jun 08 '16 at 11:36
  • 3
    is registration_id and registration token same thing? – Angga Ari Wijaya Sep 15 '16 at 14:22
  • 2
    @AnggaAriWijaya yes – Tim Sep 15 '16 at 14:23
  • good , but id you can get from FirebaseInstanceId.getInstance().getToken() or class AppFirebaseMessageingService: FirebaseMessagingService() { override fun onNewToken(token: String?) { super.onNewToken(token) } override fun onMessageReceived(msg: RemoteMessage?) { super.onMessageReceived(msg)}} – John Albert Nov 07 '18 at 12:00
  • So if I get this right after we get the registration ID, we need to do a postback at our own endpoint to save the registration ID along with the unique identifier of the user in our system. And there is no way for firebase to save that data for us? – TheWebGuy Feb 02 '19 at 12:45
  • 2
    @TheWebGuy yes. How would you tell firebase who to send a message to if you can't tell them who it is? – Tim Feb 02 '19 at 21:56
0

you can send message to other device using this code. there is no need of server in this code.

public  String send(String to,  String body) {
            try {

                final String apiKey = "AIzaSyBsY_tfxxxxxxxxxxxxxxx";
                URL url = new URL("https://fcm.googleapis.com/fcm/send");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + apiKey);
                conn.setDoOutput(true);
                JSONObject message = new JSONObject();
                message.put("to", to);
                message.put("priority", "high");

                JSONObject notification = new JSONObject();
               // notification.put("title", title);
                notification.put("body", body);
                message.put("data", notification);
                OutputStream os = conn.getOutputStream();
                os.write(message.toString().getBytes());
                os.flush();
                os.close();

                int responseCode = conn.getResponseCode();
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + message.toString());
                System.out.println("Response Code : " + responseCode);
                System.out.println("Response Code : " + conn.getResponseMessage());

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // print result
                System.out.println(response.toString());
                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "error";
        }
Durgesh Kumar
  • 935
  • 10
  • 17
  • 4
    This is not recommended way because anyone can get your API key by using tools like Smali2Java and can send the notification to anyone. – kunwar97 Nov 26 '17 at 08:27
  • that's the part of hacking, and Yeah I also don't recommend this but I was giving the answer that we can do it from here too, we can secure that part by encrypting the key if needed. and yes thanks for letting me know this. – Durgesh Kumar Nov 26 '17 at 08:56
  • 1
    How will we use this? – Tarlan Ahad Dec 26 '17 at 19:48
  • just provide token_id of receiver and body which you want to send. Also do not forget to change api key – Durgesh Kumar Jan 14 '18 at 11:48
  • 10
    *we can secure that part by encrypting the key* - that's not true – Tim Feb 21 '18 at 22:04
  • could you please share a sample of body? in java string that you have passed as a parameter – Jay Dwivedi May 29 '19 at 01:52
  • `FireBase fb = new FireBase(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("status", params[0]); jsonObject.put("title", "Request " + params[0]); jsonObject.put("from", preferences.getString("name", "")); jsonObject.put("token_id", preferences.getString("token_id", "")); } catch (Exception e) { e.printStackTrace(); } fb.send(requester_token, jsonObject.toString());` – Durgesh Kumar Jun 06 '19 at 04:46
  • 6
    Do not do this. Your private api key is for your use on hardware under your control. Do not distribute it publicly. – Caleb_Allen Sep 06 '19 at 00:29