Firebase云消息传递功能sendToDevice无法正常工作

时间:2017-07-31 19:35:14

标签: android firebase firebase-cloud-messaging google-cloud-functions firebase-admin

我正在使用以下代码使用FCM从一台设备向另一台设备发送通知。一切正常,直到return admin.messaging().sendToDevice(...)之前。 “令牌ID:”日志显示接收者的令牌ID,但是当我将变量token_id设置为sendToDevice函数时,不会调用通知,因此不会发送通知。 有人能告诉我什么是错的吗?

'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);

				});

			});

		});

	});

});

编辑我用于将Firebase实例ID保存到当前用户数据库的代码。

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

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

0 个答案:

没有答案