且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Vapor 中向 Firebase Cloud Messaging API 发送 POST 请求

更新时间:2022-10-16 19:35:42

  1. sendNotification(payload:) 我有一个错字,我错过了 = 键后.应该是 "key=(fcmLegacyServerKey)"
  2. sendNotification(payload:) 中,不应该调用 payLoad.makeBody,我应该只是将 JSON 对象 payLoad 作为.post 请求的参数.
  3. 通知的 JSON 对象从一开始就明显格式错误.我想发送的消息类型是 notification,但我传入了一个名为 aps 的键.我应该已经传递了密钥 notification ,如下所示.

.

类 FirebaseRequester {让 fcmLegacyServerKey = "AIzaSy....vVos"func sendNotification(payLoad: JSON) throws ->回复 {var响应:响应?做 {让 responseFCM = 试试 drop.client.post("https://fcm.googleapis.com/fcm/send",标头:["Content-Type":"application/json","Authorization":"key=(fcmLegacyServerKey)"],询问: [:],正文:payLoad响应=响应FCM}捕捉让错误{让 message = error.localizedDescriptionlogErr.prints(消息:消息)throw Abort.custom(状态:.badRequest,消息:消息)}守卫让 rsp = response?.json else {let message = "在行 (#line) 上没有收到 json"drop.log.error(消息)logErr.prints(消息:消息)throw Abort.custom(状态:.badRequest,消息:消息)}回复回复!}//sendNotification() 结束}//类 FirebaseRequester 结束类 TestRouteNow {让 firebaseRequester: FirebaseRequester初始化(firebaseRequester:FirebaseRequester){self.firebaseRequester = firebaseRequester}func addRoutes(drop: Droplet) {drop.post("test", "notif", handler: postNotification)}func postNotification(request: Request) throws ->响应可表示{让 fcmDevice = "someDeviceTokenReceivedFromClientApp"让数据=尝试节点(节点:[标题":标题",正文":正文",声音":默认",徽章":60"])var payLoadObj = 尝试 JSON(节点:[通知":数据])payLoadObj["to"] = 尝试 JSON(节点: fcmDevice)做 {让 _ = 试试 firebaseRequester.sendNotification(payLoad: payLoadObj)}抓住{logErr.prints(消息:error.localizedDescription)}let message = "通知已发送"返回尝试 JSON(节点:[成功":消息])}}//课程结束//请求正文{"to" : "cQDtm_someDeviceTokenReceivedFromClient",优先级":高",通知": {"title":"预订改期",body":取消预订 7830593,3 月 12 日星期一",声音":默认",徽章":100"}}

I am trying to make a POST request to a Firebase Notifications API using Vapor 1.5 and Firebase Legacy Protocol, but I get failure response.

response is JSON(node: Node.Node.object(["multicast_id": Node.Node.number(5936281277445399934), "failure": Node.Node.number(0), "canonical_ids": Node.Node.number(0), "results": Node.Node.array([Node.Node.object(["message_id": Node.Node.string("0:1527074314969790%c7ade8b9f9fd7ecd")])]), "success": Node.Node.number(1)]))

EDIT Making the request through POSTMan fails with error "The request was missing an Authentication Key (FCM Token)."

class FirebaseRequester {
 let fcmLegacyServerKey = "AIzaSyDSuXXXXXXkCafTQay5_r8j3snvVos"

 func sendNotification(payLoad: JSON) throws -> Response {

    var response: Response?
    do {
        let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send", 
           headers: ["Content-Type":"application/json","Authorization": "key(fcmLegacyServerKey)"], 
           query: [:], 
          body: payLoad.makeBody())

        response = responseFCM

    }catch let error {
        let message = error.localizedDescription
        logErr.prints(message: message)
        throw Abort.custom(status: .badRequest, message: message)
    }

    guard let rsp = response?.json else {


        let message = "no json received on line (#line)"
        drop.log.error(message)
        logErr.prints(message: message)
        throw Abort.custom(status: .badRequest, message: message)
     }
  print("rsp in json format is (rsp)")
      return response!
 }//end of sendNotification()
}//end of class FirebaseRequester




      //make another class here and initialize it with  FirebaseRequester
      //get data from Client App 
      // validate data 
      // finally, create the payLoad and call sendNotification(:)
     //request should look like 
{
  "aps": {
    "alert": "Breaking News!",
    "sound": "default",
    "link_url": "https://raywenderlich.com"
 }
}

     let fcmKeyToSendTo = "someDeviceTokenKeyReceivedFromClient_biHZNI-e9E53WEkCzrki"

            let data = try Node(node: ["alert": "alert", "sound": "sound", "link_url": "https://www.someWebsite.com"])

     var payLoadObj = try JSON(node: ["aps" : data])
     payLoadObj["to"] = try JSON(node: fcmKeyToSendTo)

            do {
                let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
            }catch{
                logErr.prints(message: error.localizedDescription)
            }

            let message = "notification Sent"
            return try JSON(node:["success":message])

  1. In sendNotification(payload:) I had a typo, I missed = after key. It should have been "key=(fcmLegacyServerKey)"
  2. In sendNotification(payload:), payLoad.makeBody should not be called, I should have just passed the JSON object payLoad as an argument to the .post request.
  3. The JSON object of the notification was clearly badly formatted from the outset. The message type I wanted to send was notification, but I was passing in a key named aps. I should have passed key notification as shown below.

.

class FirebaseRequester {

  let fcmLegacyServerKey = "AIzaSy....vVos"

  func sendNotification(payLoad: JSON) throws -> Response {

  var response: Response?
   do {
     let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send", 
       headers: ["Content-Type":"application/json","Authorization": "key=(fcmLegacyServerKey)"], 
       query: [:], 
      body: payLoad

      response = responseFCM

  }catch let error {
     let message = error.localizedDescription
     logErr.prints(message: message)
     throw Abort.custom(status: .badRequest, message: message)
 }
   guard let rsp = response?.json else {

    let message = "no json received on line (#line)"
    drop.log.error(message)
    logErr.prints(message: message)
    throw Abort.custom(status: .badRequest, message: message)
   }
    return response!
  }//end of sendNotification()
}//end of class FirebaseRequester



class TestRouteNow {

  let firebaseRequester: FirebaseRequester

  init(firebaseRequester: FirebaseRequester) {
     self.firebaseRequester = firebaseRequester
  }

  func addRoutes(drop: Droplet) {
     drop.post("test", "notif", handler: postNotification)
  }

   func postNotification(request: Request) throws -> ResponseRepresentable {

   let fcmDevice = "someDeviceTokenReceivedFromClientApp"
   let data = try Node(node: ["title": "title","body": "body", "sound": "default", "badge":"60"])

    var payLoadObj = try JSON(node: ["notification": data])
    payLoadObj["to"] = try JSON(node: fcmDevice)

      do {
        let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
            }catch{
                logErr.prints(message: error.localizedDescription)
            }

            let message = "notification Sent"
            return try JSON(node:["success":message]) 
     } 
 }//end of class




    // request body
{
  "to" : "cQDtm_someDeviceTokenReceivedFromClient",
  "priority":"high",

 "notification": {
     "title":"Booking Rescheduled",
      "body": "Cancelled Booking 7830593, for Mon, 12 March",
      "sound":"default",
     "badge": "100"
  }
}