且构网

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

如何使用谷歌应用程序脚本从Firebase发送推送通知?

更新时间:2022-12-21 13:22:37

我以前从未尝试过,但实际上非常简单。



您需要知道以下两件事:


  1. 如何向Firebase Cloud Messaging发送HTTP请求以传递消息

  2. 如何调用外部HTTP来自Apps Script的API

阅读这两个文档后,代码非常简单: p>

 函数sendNotificationMessage(){
var response = UrlFetchApp.fetch('https://fcm.googleapis.com/fcm / send',{
方法:'POST',
contentType:'application / json ,
标题:{
授权:'key = AAAAIM ... WBRT'
},
有效载荷:JSON.stringify({
通知:{
标题:'Hello TSR!'
},
到:'cVR0 ... KhOYB'
})
});
Logger.log(response);

$ / code>

在这种情况下:


  1. 脚本发送通知消息。这种类型的消息:


    • 当应用程序未处于活动状态时,自动显示在系统托盘中

    • 在应用程序处于活动状态时不显示



    如果您希望完全控制消息到达设备时应用程序的功能, 数据消息


  2. 脚本将消息发送到特定设备,由其设备标记在属性中标识。您也可以发送到一个主题,例如 / topics / user_TSR 。有关更广泛的示例,请参阅我的博客文章,内容有关发送通知使用Firebase数据库和云消息传递的Android设备之间)。

  3. code> Authorization 标题需要与您的Firebase项目相匹配。请参阅 Firebase消息传递,从哪里获取服务器密钥?


I want to write a little script that tells Firebase to push notification if a certain condition is met. How to send push notification from Firebase using google apps script?

I'd never tried this before, but it's actually remarkably simple.

There are two things you need to know for this:

  1. How to send a HTTP request to Firebase Cloud Messaging to deliver a message
  2. How to call an external HTTP API from with Apps Script

Once you have read those two pieces of documentation, the code is fairly straightforward:

function sendNotificationMessage() {
  var response = UrlFetchApp.fetch('https://fcm.googleapis.com/fcm/send', {
    method: 'POST',
    contentType: 'application/json',
    headers: {
      Authorization: 'key=AAAAIM...WBRT'
    },
    payload: JSON.stringify({
      notification: {
        title: 'Hello TSR!'
      },
      to: 'cVR0...KhOYB'
    })
  });
  Logger.log(response);
}

In this case:

  1. the script sends a notification message. This type of message:

    • shows up automatically in the system tray when the app is not active
    • is not displayed when the app is active

    If you want full control over what the app does when the message reaches the device, send a data message

  2. the script send the message to a specific device, identified by its device token in the to property. You could also send to a topic, such as /topics/user_TSR. For a broader example of this, see my blog post on Sending notifications between Android devices with Firebase Database and Cloud Messaging.

  3. the key in the Authorization header will need to match the one for your Firebase project. See Firebase messaging, where to get Server Key?