用户或企业的FCM主题消息传递

时间:2019-06-10 15:07:34

标签: firebase firebase-realtime-database notifications firebase-cloud-messaging google-cloud-functions

我的目标是允许用户“订阅”我的应用程序中的另一个用户/企业,以便他们的所有关注者可以在需要了解诸如新帖子之类的内容时收到通知。我正在使用Firebase Cloud Functions发送通知。

我正在尝试为此使用主题,但是它们似乎没有用...我可以成功订阅,但是尝试发送通知时却什么也没有得到...

注意:我已经设置了推送通知,并已成功将其发送给消息之类的消息。

//here i am subscribing to the user when they accept the request

  exports.friendRequestAccepted = functions.database.ref('/friends/{pendingFriend}/{requester}')
  .onUpdate((change, context) => {
    const pendingFriend = context.params.pendingFriend;
    const requester = context.params.requester;

    const ref = admin.database().ref(`users/${requester}/notificationTokens`);
    return ref.once("value", function(snapshot){
        const payload = {
              notification: {
                  title: 'You have a new Connection',
                  body: 'Somebody has accepted your connection request. Who could that be?'
              }
        };

        admin.messaging().sendToDevice(snapshot.val(), payload)
        // Subscribe the devices corresponding to the registration tokens to the
        // topic.
        admin.messaging().subscribeToTopic(pendingFriend)
          .then(function(response) {
            // See the MessagingTopicManagementResponse reference documentation
            // for the contents of response.
            console.log('Successfully subscribed to topic:', response);
          })
          .catch(function(error) {
            console.log('Error subscribing to topic:', error);
          });


    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    });
  })




//here i am trying to send the topic notification when a post is added...  

    exports.newPostNotification = functions.database.ref('/categories/{newPost}/')
        .onCreate((snapshot, context) => {
          // Grab the current value of what was written to the Realtime Database.
          const original = snapshot.val();
          console.log('informing for', context.params.newPost, original);
          // You must return a Promise when performing asynchronous tasks inside a Functions such as
          // writing to the Firebase Realtime Database.
          // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
          const payload = {
            notification: {
                title: 'New Post from user',
                body: 'blah blah blah',
            },
        };

          return admin.messaging().sendToTopic(original.userUid, payload)
            .then(function(response) {
              console.log("Successfully sent message:", response);
            })
            .catch(function(error) {
              console.log("Error sending message:", error);
            });    
          });

订阅时,我收到成功回调,但是当尝试将消息发送给订阅的用户时,我什么也没收到...我可以在下拉菜单的FCM控制台上看到主题,因此我知道他们在那儿。

我希望获得一些指导以帮助解决此问题,但我不知道我在做什么错。

干杯!

0 个答案:

没有答案