ipegasus
ipegasus

Reputation: 15242

How to send a firebase cloud message in typescript?

I would like to know how to send a firebase cloud message, via my firebase functions backend. It looks like there is an issue with the payload. I would like to know how to solve the issue. Is an interface necessary for the payload? Thanks in advance!

Error

Error sending message: { Error: Invalid JSON payload received. Unknown name "message" at 'message': Cannot find field.  
at FirebaseMessagingError.FirebaseError [as constructor] (/home/ubuntu/environment/****/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)

Notification Function (Updated Working Code)

async function notification(
  notificationType: string,
  registrationToken: string,
  objectText: string
) {
  const matchesRef = db.collection("notifications");
  const notificationObject = await matchesRef.doc(notificationType).get();

  if (notificationObject.exists) {
    const tokenMessage: admin.messaging.Message = {
      token: registrationToken,
      notification: {
        title: notificationObject.data()!.title,
        body: notificationObject.data()!.body
      },
      data: {
        click_action: "FLUTTER_NOTIFICATION_CLICK",
        title: notificationObject.data()!.title,
        body: notificationObject.data()!.body
      },
      android: {
        priority: "high"
      },
      apns: {
        headers: {
          "apns-priority": "5"
        }
      }
    };
    admin
      .messaging()
      .send(tokenMessage)
      .then((response: string) => {
        // Response is a message ID string.
        logMe(`Successfully sent message: ${response}`);
        return response;
      })
      .catch((error: string) => {
        console.log("Error sending message:", error);
      });
  }
  return false;
}

Upvotes: 0

Views: 2572

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

If you are trying to use the TokenMessage structure, you can see from the linked API docs that it doesn't contain a message property. Remove the outer layer and the redundant token field at the top level:

    const message = {
        token: registrationToken,
        notification: {
          title: notificationObject.data()!.title,
          body: notificationObject.data()!.body
        },
        data: {
          click_action: "FLUTTER_NOTIFICATION_CLICK",
          title: notificationObject.data()!.title,
          body: notificationObject.data()!.body
        },
        android: {
          priority: "high"
        },
        apns: {
          headers: {
            "apns-priority": "5"
          }
        }
    };

Upvotes: 1

Related Questions