首先,我生成了FCM令牌并将其存储在Firestore中。之后,我编写了一个云函数来基于FCM令牌发送通知。我部署了云功能,它说成功发送状态为ok的通知。但它不会显示在移动设备中。我的Index.js是
'use strict';
const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const admin = require('firebase-admin');
const firestore = new Firestore();
const db = admin.firestore();
admin.initializeApp(functions.config().firebase);
exports.hellouser = functions.firestore
.document('users/{token}')
.onWrite(event =>{
var document = event.data.data();
console.log("tokens",document);
var token = ['cdNN0AbYKU0:APA91bEyL0zo3zwHZD8H43Vp7bxAfYgehlVI8LrKktPO2eGuByVDdioysIGxHe5wocwq8ynxRToJPpOve_M59YY_MIRbWLnF9AIgoTwJORXZbw6VBw7']// this is my FCM token.
if(
const payload = {
notification: {
title: "Message",
body: "hi hello",
sound: "default"
}
};
return admin.messaging().sendToDevice(token, payload).then((response)=> {
console.info("Successfully sent notification")
}).catch(function(error) {
console.warn("Error sending notification " , error)
});
});
如何基于FCMtoken发送通知。
最佳答案
如果您使用的是正确的代码,请检查if(
附近的语法。这可能对您有帮助。接下来编写一些代码来遍历您的response
对象。 Firebase可能会获取您的令牌和有效负载,对其进行处理并返回200 OK响应,但是在响应中您将遇到错误。响应具有如下一般结构:{ results: [ { //stuff related to one token },{ //stuff related to one token } ], canonicalRegistrationTokenCount: 0, failureCount: 1, successCount: 0, multicastId: SOME_LONG_NUMBER }
请记住,response.results
数组具有发送到令牌的每条消息的状态,其顺序与token
数组中的令牌相同。您可以在Firebase Documentation中看到所有可能的错误。如果response.failureCount > 0
则没有消息发送,并且您应该在response.results
中得到相应的错误。还要了解options
变量。 options.priority
必须为'high'
,以确保快速传递消息。也许这会有所帮助。