Firebase Cloud Messaging function sendToDevice not working

走远了吗. 提交于 2021-02-08 05:24:42

问题


I'm using the following code to send a notification from one device to another using FCM. Everything works fine until before return admin.messaging().sendToDevice(...). The 'Token ID: ' log displays token ID of the receiver, but when I set the variable token_id to the sendToDevice function, the notification is not called, therefore the notification is not sent. Can someone tell me what's wrong?

'use strict'

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

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite(event => {

	const user_id = event.params.user_id;
	const notification_id = event.params.notification_id;

	console.log('We have a notification to send to ', user_id);

	if(!event.data.val()){

		return console.log('Notification has been deleted from the database: ', notification_id);

	}

	const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
	return fromUser.then(fromUserResult => {

		const from_user_id = fromUserResult.val().from;

		console.log('You have a new notification from ', from_user_id);

		const user_query = admin.database().ref(`/usuarios/${from_user_id}/nome`).once('value');
		return user_query.then(userResult => {

			const user_name = userResult.val();

			const device_token = admin.database().ref(`/usuarios/${user_id}/device_token`).once('value');
			return device_token.then(result => {
							
				const token_id = result.val();

				console.log('Token ID: ', token_id);

				const payload = {
					notification: {
						title: "New Request",
						body: `${user_name} has sent you a request.`,
						icon: "default",
					},
					data: {
						p_tab: "2"
					}
				};

				return admin.messaging().sendToDevice(token_id, payload).then(response =>{

					console.log('Notification sent to ', user_id);

				});

			});

		});

	});

});

EDIT Code I use to save Firebase Instance ID to the current user's database.

String deviceToken = FirebaseInstanceId.getInstance().getToken();

usersRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("device_token").setValue(deviceToken);

来源:https://stackoverflow.com/questions/45423966/firebase-cloud-messaging-function-sendtodevice-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!