FCM 推送通知错误:消息必须是非空对象

问题描述 投票:0回答:1

我第一次尝试使用云函数在react.js应用程序中实现FCM推送通知,并陷入此错误:消息必须是非空对象。我读过一些有关该主题的答案,但没有一个对我有帮助。我不知道我的代码到底出了什么问题。 这是我的 index.js 在函数目录中

import functions from 'firebase-functions';
import admin from 'firebase-admin';

admin.initializeApp();

export const sendNotifications = functions.firestore.document('messages/{messageId}').onCreate(
    async (snapshot) => {
        const text = snapshot.data().text;
        const payload = {
            notification: {
                title: `${snapshot.data().username} sent ${text ? 'a new message' : 'a new attachment'}`,
                body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
                icon: snapshot.data().photoURL || '/images/profile_placeholder.png',
            }
        };
        console.log("Payload", payload)

        // Get the list of device tokens
        const allTokens = await admin.firestore().collection('fcmTokens').get();
        const tokens = [];
        allTokens.forEach((tokenDoc) => {
            tokens.push(tokenDoc.id);
        });

        console.log(tokens)

        // Send notification to all tokens.
        if (tokens.length > 0) {
            // Send notifications to all tokens.
            const response = await admin.messaging().send(tokens, payload);
            await cleanupTokens(response, tokens);
            functions.logger.log('Notifications have been sent and tokens cleaned up.');
        } else{
            console.log("Not tokens", tokens)
        }
    }
);


// Cleans up the tokens that are no longer valid.
function cleanupTokens(response, tokens) {
    // For each notification we check if there was an error.
    const tokensDelete = [];
    response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
            functions.logger.error('Failure sending notification to', tokens[index], error);
            // Cleanup the tokens that are not registered anymore.
            if (error.code === 'messaging/invalid-registration-token' ||
                error.code === 'messaging/registration-token-not-registered') {
                const deleteTask = admin.firestore().collection('fcmTokens').doc(tokens[index]).delete();
                tokensDelete.push(deleteTask);
            }
        }
    });
    return Promise.all(tokensDelete);
}

当我将有效负载记录到控制台时,它会显示通知对象及其中的所有数据,这让我感到困惑,因为它不为空,而是一个内部包含数据的对象。 下面是日志输出的屏幕截图。

javascript firebase google-cloud-functions firebase-cloud-messaging firebase-admin
1个回答
0
投票

您没有正确使用 Fireabse Admin API。它不接受您正在传递的论点。请再次查看 API 文档示例 以了解其工作原理。

如果您想向多个设备发送消息,您应该使用 sendMulticast()sendEachForMulticast() 而不是 send()。它接受一个 MulticastMessage 对象,其中包含要发送到的令牌。 文档中有一个示例:

// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // …
  'YOUR_REGISTRATION_TOKEN_N',
];

const message = {
  data: {score: '850', time: '2:45'},
  tokens: registrationTokens,
};

getMessaging().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

© www.soinside.com 2019 - 2024. All rights reserved.