【问题标题】:How to implement a function that triggers an push notification when a new document is created on fcm?如何实现在 fcm 上创建新文档时触发推送通知的功能?
【发布时间】:2019-06-03 15:23:51
【问题描述】:

我有一个大学项目,我正在开发一个应用程序,当在 firebase 的集合“ocorrencia”上创建新文档时,该应用程序需要接收推送通知。

我试过做这个 firebase 云功能,但没有运气,它不起作用,我不知道如何从“管理员”集合中的每个用户读取属性令牌(我的应用程序发送实际的设备令牌)并将其添加到数组中,以便将其发送到具有此值的所有设备。

我也尝试过使用本教程,但也没有用: https://angularfirebase.com/lessons/ionic-native-with-firebase-fcm-push-notifications-ios-android/

这是我的 index.js 函数:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.notificacao = functions.firestore
    .document('ocorrencia/{ocorrenciaId}')
    .onCreate((snap,context) => {

        const data = snap.data();
        const idAdmin = data.idAdmin

        const payload = {
            notification: {
                title:'Nova Ocorrência',
                body:'Uma nova Ocorrência foi registrada'
            }
        }
        var pushToken = "";
        return functions
        .firestore
          .collection("admin/idAdmin")
          .get()
          .then((doc) => {
            pushToken = doc.data().token;
            return admin.messaging().sendTodevice(pushToken, payload)
          });
    })

这是我将令牌发送到服务器的应用程序功能(在用户登录后触发):

async getDeviceToken(){
    let token;
    token = await this.fcm.getToken();
    console.log(this.adminUid);
    return this.sendFirestoreToken(token);
  }

  getAdminUid(){
    this.afAuth.authState.subscribe(auth => {
      this.adminUid = auth.uid;
    })
  }

  sendFirestoreToken(token){
    const adminRef = this.afs.collection('admin')
    return adminRef.doc(this.adminUid).update({idAdmin: this.adminUid, token: token});
  }

这里还有我在 github 上的应用程序仓库: https://github.com/gianveloxbr/MacacoIrmaoADM/tree/master/macacoIrmao

每次将新注册表添加到“ocorrencia”时,该函数都需要触发,并且需要将其发送给“admin”集合中的每个用户,并带有属性令牌。

编辑: 我已经尝试过这段代码,但不知道如何通过他们的 id 恢复所有文档

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.notificacao = functions.firestore
    .document('ocorrencia/{ocorrenciaId}')
    .onCreate((snap,context) => {

        const data = snap.data();
        const idAdmin = data.context.idAdmin


          const db = admin.firestore()

          // send a notification to each device token

          return Promise.all([admin.database().ref('admin/${}/token').once('value')]).then(
           // Don't know how to get every document using ${}
   results => {
                  const token = results[1];
                  if(!token.hasChildren()) return null;
                  let payload = {
                    notification: {
                        title:'Nova Ocorrência',
                        body:'Uma nova Ocorrência foi registrada'
                    }
                }
                const tokens = Object.keys(token.val());
                return admin.messaging().sendToDevice(tokens,payload);
              }
          )
    })

【问题讨论】:

    标签: node.js google-cloud-firestore firebase-cloud-messaging google-cloud-functions ionic4


    【解决方案1】:

    通过从令牌更改为主题自己解决了问题:

    如果有人想实现,这里是代码:

    index.js

    exports.notificacao = functions.firestore
    .document('ocorrencia/{ocorrenciaId}')
    .onCreate((snap,context) => {
     let payload = {
          notification: {
              title: 'Nova ocorrência',
              body: 'Uma nova ocorrência foi registrada.',
              click_action: 'FCM_PLUGIN_ACTIVITY'
          }
      }
          return admin.messaging().sendToTopic("admin",payload).then(response => {
              console.log('Notificação enviada com sucesso.', response);
          }).catch(error => {
              console.log('Erro:', error);
          })
        }
    )
    

    对于在用户登录后订阅主题,您需要在 app.component.ts 中实现这一点

    import { FCM } from '@ionic-native/fcm/ngx';
    constructor(private fcm:FCM) { }
    this.fcm.subscribeToTopic('admin');
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2022-07-18
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2017-12-13
      • 2019-09-09
      • 2021-03-03
      • 2021-09-24
      相关资源
      最近更新 更多