How to send push notifications without using Fireb

2019-07-30 15:24发布

问题:

I have an app that has a messaging feature via Firebase. It works within the app and I have a firebase observer setup to grab new messages in realtime. What I don't know how to do is trigger push notifications under that observer as well.

I've implemented Firebase Cloud Messaging into my app so that I can send a notification to my console, but am having trouble finding a resource that is for iOS or that doesn't just end at using the console to send a single message.

I know this a broad question, and it might be labelled "Off-topic" but if I could be directed towards any more related resources, I'd greatly appreciate it!

回答1:

There is an API for sending messages with Firebase Cloud Messaging. Instead of repeating it here, I recommend you check out the FCM server documentation. It basically takes the form of a HTTP POST request, such as this example from the docs:

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message",
      }
   }
}

To send messages to devices you will need to specify the so-called FCM server key. As its name applies, this key should only be used in trusted environments, such as a server that you control, your development machine, or Cloud Functions for Firebase. The reason for this is that someone who has your FCM server key can send unlimited messages to all users of your app.

There is also a Firebase Admin SDK that makes it easier to call the FCM server API to send messages on platforms that it supports. For more on this option, see the FCM Admin SDK documentation. That turns the above into something like this (on Node.js):

admin.messaging().send({
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "This is an FCM notification message!",
      "title" : "FCM Message",
      }
   }
})


回答2:

You can send it with Postman or something like that. You have to do POST-request to https://fcm.googleapis.com/fcm/send

Set headers:

Content-Type: application/json

Authorization: key=<legacy_server_key or server_key>

It has to look like

Authorization:key=AAAAwrVC26k:APA91bHz_ZRBjyoyevnVi0oey8yO_om9av_-YeUq........

And body of notification:

{
 "to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification"
 },
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}