如何使用Google Apps脚本从Firebase发送推送通知?

TSR*_*TSR 5 android push-notification google-apps-script firebase firebase-cloud-messaging

我想写一个小脚本,告诉Firebase在满足某个条件时推送通知.如何使用Google Apps脚本从Firebase发送推送通知?

Fra*_*len 6

我以前从未尝试过这个,但它实际上非常简单.

你需要知道两件事:

  1. 如何向Firebase Cloud Messaging发送HTTP请求以传递消息
  2. 如何使用Apps脚本调用外部HTTP API

一旦您阅读了这两个文档,代码就相当简单:

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);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下:

  1. 脚本发送通知消息.这种消息:

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

    如果您想要完全控制消息到达设备时应用程序执行的操作,请发送数据消息

  2. 脚本将消息发送到特定设备,由设备中的设备令牌标识to.您也可以发送一个主题,例如/topics/user_TSR.有关此更广泛的示例,请参阅我的博客文章,了解如何在Android设备与Firebase数据库和云消息传递之间发送通知.

  3. keyAuthorization头将需要匹配一个为你的火力地堡项目.查看Firebase消息传递,获取服务器密钥的位置?