当前位置: 首页 > 知识库问答 >
问题:

如何在Vapor中向Firebase云消息API发送POST请求

梁丘俊材
2023-03-14

我试图使用Vapor 1.5和Firebase遗留协议向Firebase Notifications API发出POST请求,但收到失败响应。

编辑通过邮递员发出请求失败,错误为“请求缺少身份验证密钥(FCM令牌)”

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个答案

江华容
2023-03-14
  1. 发送通知(有效负载:)中,我有一个输入错误,我错过了键后的=。它应该是“key=\(fcmLegacyServerKey)”

.

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"
  }
}
 类似资料:
  • 我刚开始使用Firebase云消息。我建了一个IOS应用来接收推送通知。应用程序运行良好。我从Firebase控制台发送消息,它们会正确显示。 我的问题是:我可以向所有设备发送一条消息吗(就像我可以在控制台中做的那样)?我是的,怎么会这样? 提前道谢!

  • 在我们的项目中,我们使用Firebase云消息传递来进行推送通知,我们遇到了消息重复的问题。我们过程如下所示: xamarin.firebase.ios.CloudMessaging 3.1.2 xamarin.firebase.ios.instanceID 3.2.1 xamarin.firebase.ios.core 5.1.3 订阅用户主题推荐 发送主题订阅者请求的通知 null 但是,当用

  • 有人知道一种从firebase控制台发送click_action的方法吗? 我只想发送click_action按钮来使用通知,即使应用程序关闭或在后台。

  • 我正在使用vapor为我的应用程序托管图像。我有以下代码来接收图像并打印它。 我怎么能发送一个多部分的请求,只是使用swft?。这是我正在使用的当前帖子请求代码。

  • 在搜索文档之后,我找不到任何关于如何在没有使用外部服务器的情况下使用FCM向设备发送消息的信息。 例如,如果我正在创建一个聊天应用程序,我将需要向用户发送关于未读消息的推送通知,因为他们不会一直在线,而且我不可能在后台有一个始终连接到实时数据库的持久服务,因为这会占用太多资源。 那么当某个用户“B”向他/她发送聊天消息时,我将如何向用户“a”发送推送通知呢?我需要一个外部服务器来完成这个任务吗?还

  • 我正在尝试为Web设置Firebase云消息传递。我成功地对其进行了正确初始化并获得了令牌: manifest.json与gcm_sender_id 我可以看到我在控制台中得到令牌,所以我试图验证它,并通过邮递员发送我的第一个通知-这里是留档。 发布网址:https://fcm.googleapis.com/v1/projects/PROJECTID/messages:发送授权:无授权 标题 Bo