我正在努力实现在更改Firebase Firestore文档时显示的推送通知。我正在使用react-native-firebase模块。我的Google Cloud函数侦听Firestore的更改,然后通过firebase-admin发送消息。
google的参考资料说,您可以指定一个设备通过以下方式发送消息:
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
在我的本机应用程序的客户端,我使用来获得令牌react-native-firebase
:
function getToken() {
let fcmToken = await AsyncStorage.getItem("fcmToken");
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
await AsyncStorage.setItem("fcmToken", fcmToken);
}
}
}
我是否需要在异步存储之外的其他地方存储Google云消息传递令牌,或者是否可以在Google Cloud函数内部按原样访问它?看来我应该将auth令牌存储在firestore中,并使用云函数访问firestore。这是最好的方法吗?
您不需要AsyncStorage
访问令牌,可以fcmToken = await firebase.messaging().getToken();
在代码中直接使用它。
从那里,您可以将其发送到回调Cloud Function,例如:
var sendMessage = firebase.functions().httpsCallable('sendMessage');
addMessage({ token: fcmToken }).then(function(result) {
// ...
});
这基于此处文档中的示例。然后,您可以通过Admin SDK调用FCM API,在Cloud Functions代码中使用此值来发送消息。
或将其存储在数据库(例如Cloud Firestore)中,如下所示:
db.collection("tokens").add(docData).then(function() {
console.log("Token successfully written to database!");
});
这基于此处文档中的示例。然后,您可以从Cloud Function中的数据库中读取该值,并通过Admin SDK调用FCM API,将其用于再次发送消息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句