且构网

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

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

更新时间:2022-11-27 18:45:18

  1. sendNotification(payload:)中,我有一个错字,我在输入键后错过了=.应该是"key=\(fcmLegacyServerKey)"
  2. sendNotification(payload:)中,不应调用payLoad.makeBody,我应该刚刚将JSON对象payLoad作为参数传递给.post请求.
  3. 通知的JSON对象从一开始就显然格式不正确.我想发送的消息类型是 notification ,但是我传入了一个名为aps的密钥.我应该已经通过了密钥notification,如下所示.
  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"
  }
}