Send to devices using the legacy API

The Firebase Admin Node.js SDK supports additional methods for sending Firebase Cloud Messaging (FCM) messages to end-user devices. They are based on the Legacy FCM server API, and therefore accept different arguments compared to the send() method. You should use the send() method whenever possible, and only use the methods described in this page when sending messages to individual devices or device groups.

Send to individual devices

You can pass a registration token to the sendToDevice() method to send a message to that device:

Node.js

// This registration token comes from the client FCM SDKs.
var registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().sendToDevice(registrationToken, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch(function(error) {
    console.log('Error sending message:', error);
  });

The sendToDevice() method can also send a multicast message (that is, a message to multiple devices) by passing an array of registration tokens instead of just a single registration token:

Node.js

// These registration tokens come from the client FCM SDKs.
var registrationTokens = [
  'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
  // ...
  'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...'
];

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the devices corresponding to the provided
// registration tokens.
admin.messaging().sendToDevice(registrationTokens, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch(function(error) {
    console.log('Error sending message:', error);
  });

The sendToDevice() method returns a promise that is resolved with a MessagingDevicesResponse object containing the response from FCM. The return type has the same format when passing a single registration token or an array of registration tokens.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToDevice() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Send to a device group

With device group messaging, you can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.

The maximum number of members allowed for a notification key is 20.

You can create device groups and generate notification keys via an app server or an Android client. See Managing device groups for details.

The sendToDeviceGroup() method allows you to send a message to a device group by specifying the notification key for that device group:

Node.js

// See the "Managing device groups" link above on how to generate a
// notification key.
var notificationKey = 'some-notification-key';

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device group corresponding to the provided
// notification key.
admin.messaging().sendToDeviceGroup(notificationKey, payload)
  .then(function(response) {
    // See the MessagingDeviceGroupResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch(function(error) {
    console.log('Error sending message:', error);
  });

The sendToDeviceGroup() method returns a promise that is resolved with a MessagingDeviceGroupResponse object containing the response from FCM.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToDeviceGroup() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Defining the message payload

The above methods accept a message payload as their second argument and support both notification and data messages. You can specify one or both message types by creating an object with the data and / or notification keys. For example, here is how to define different types of message payloads:

Notification message

var payload = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
};

Data message

var payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

Combined message

var payload = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  data: {
    stock: 'GOOG',
    open: '829.62',
    close: '635.67'
  }
};

Notification message payloads have a predefined subset of valid properties and differ slightly depending on which mobile operating system you are targeting. See the reference docs for NotificationMessagePayload for a full list.

Data message payloads are composed of custom key-value pairs with a few restrictions, including the fact that all values must be strings. See the reference docs for DataMessagePayload for a full list of restrictions.

Defining the message options

The above methods accept an optional third argument specifying some options for the message. For example, the following example sends a high priority message to a device which expires after 24 hours:

Node.js

// This registration token comes from the client FCM SDKs.
var registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';

// See the "Defining the message payload" section above for details
// on how to define a message payload.
var payload = {
  notification: {
    title: 'Urgent action needed!',
    body: 'Urgent action is needed to prevent your account from being disabled!'
  }
};

// Set the message as high priority and have it expire after 24 hours.
var options = {
  priority: 'high',
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
  .then(function(response) {
    console.log('Successfully sent message:', response);
  })
  .catch(function(error) {
    console.log('Error sending message:', error);
  });

See the reference docs for MessagingOptions for a full list of available options.

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.