如何使用 firebase admin 向设备发送通知

How to send a notification to device using firebase admin

我正在为应用程序添加通知支持。我正在为 React Native 客户端使用 React Native firebase,并且能够接收控制台发送的通知。

但是,当我使用 firebase 管理工具发送通知时,没有收到任何通知。

firebase admin 在服务器启动时初始化一次

    let admin = require('firebase-admin')

    let serviceAccount = require('../../appname-firebase-admin.json')

    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://appname-12e14.firebaseio.com',
    })
    console.log('initialise firebase admin')

然后我根据 firebase admin 做了这个测试函数 documentation

async function sendNotification() {
  let admin = require('firebase-admin')

  let registrationToken =
    'super-long-token-goes-here'

  let message = {
    notification: { title: 'Super title', body: 'this is a test' },
    token: registrationToken,
  }

  admin
    .messaging()
    .send(message)
    .then(response => {
      // Response is a message ID string.
      console.log('Successfully sent notification:', response)
      return { success: true }
    })
    .catch(error => {
      console.log('Error sending notification:', error)
    })

  return {
    success: true,
  }
}

这个结果

Successfully sent notification: projects/appname-12e14/messages/0:1574700947563522%48f1ba652348f1ba99

设备上没有通知。

编辑:我也尝试过使用 .sendToDevice()

React-native-firebase 确实会在打开的应用程序中显示通知,您可以创建自定义通知并使用您喜欢的组件在应用程序中显示它。或者,您可以使用像 Notify 这样的第三方服务,它有一个简单的 API 来管理它们。