如何使用 Cloud Functions for Firebase 的批量通知 API?

How to use batch notifications API with Cloud Functions for Firebase?

我只是想让我的应用程序在有人喜欢那里的活动时向用户发送通知。

我试过这样做:

    exports.likeAddedNotification = functions.database.ref('/eventLikes/{eventID}/{userWhoLikedID}').onWrite(event => { 
    const userWhoLikedID = event.params.userWhoLikedID;
    console.log("User has liked a post " + userWhoLikedID);

    admin.database().ref('events/' + event.params.eventID).once('value').then(function(snapshot) {
    var usersID = snapshot.val().userId;
    console.log("The person who made the post is " + usersID);

    //Send notification to that user
    var payload = {
      "group_id": "batch_push_sender",
      "push_time": "now",
      "message": {
        "body": usersID + " liked your event"
        },
      "recipients": {
        "custom_ids": [usersID]
        },
      "sandbox": true, // Only for iOS
    };

    notificationRequest.write(JSON.stringify(payload));
    notificationRequest.end();

    console.log("Sent a notification to " + usersID);

    });
});

(很抱歉包含了这么多代码,但我觉得可能都是相关的) 如果我使用此代码并删除

var payload = ...

notificationRequest.write(JSON.stringify(payload));
notificationRequest.end();

它完全符合我的预期。它会写到控制台说哪个 post 被喜欢,谁喜欢那个 post。

我真的不确定这个问题是因为在闭包中做了太多事情,还是我只是做了一些明显错误的事情,或者是 Batch API 导致了错误。

如果您知道更好的推送通知站点允许使用 UDID 作为自定义标识符,这样我就不必手动处理每台设备的令牌,请告诉我!

首先,确保 return 您的 Promise,这是保证 Cloud Functions worker 继续运行的唯一方法。由于 Firebase 云通知是同步的,因此您的请求很可能被中止。

您还应该查看 Firebase Admin SDK 的消息传递组件。我们为 FCM 内置了一些不错的 API。 我们在 GitHub https://github.com/firebase/functions-samples/tree/master/fcm-notifications

上有一个关于如何在 Cloud Functions for Firebase 中使用这些的示例