if (hisFcmToken) {
// Send preload silent notification
const dataNotification= {
data: {
name: "Some name",
married : 'true'
},
token: hisFcmToken
};
try {
await admin.messaging().send(dataNotification);
console.log(`FCM data notification sent successfully to user ${document.id}`);
} catch (error) {
console.error(`Failed to send FCM data notification to user ${document.id}: ${error}`);
}
if (someCondition)) {
// Send user joined notification
const userJoinedNotification = {
notification: {
title: `${newUserName} just joined `,
image: someImageurl
},
data: {
newUserJoinNotification: 'true'
},
android: {
priority: "high"
},
apns: {
headers: {
'apns-priority': '10'
}
},
token: hisFcmToken
};
await admin.messaging().send(userJoinedNotification)
.then((response) => {
console.log('Successfully sent user join notification:', response);
})
.catch((error) => {
console.log('Error sending user join notification:', error);
if (error.code === 'messaging/registration-token-not-registered') {
// Remove the invalid token from your database
}
});
我对自己使用的是 Cloud Messaging API(旧版)还是 Firebase Cloud Messaging API (V1) 有点困惑,因为我必须在 2024 年 6 月 20 日之前迁移到 Firebase Cloud Messaging API (HTTP v1)。
文档说:
HTTP v1 发送请求需要 OAuth 2.0 访问令牌,而不是旧请求中使用的服务器密钥字符串。如果您使用 Admin SDK 发送消息,该库会为您处理令牌。
但我还是不确定。谢谢。
您正在使用适用于 Node.js 的 Firebase Admin SDK。只要您使用的是最新版本,就已经在使用最新的 API 端点。
例如,以下是大多数 Admin SDK 确定要调用的 API 的方式:https://github.com/firebase/firebase-admin-node/blob/67151e620fbb7bdfc2a017e9a35d51eca035d824/src/messaging/messaging.ts#L822
this.urlPath = `/v1/projects/${projectId}/messages:send`;