How To Display Error Pop Up After Receive Data From Backend
Using the Firebase Admin SDK or FCM app server protocols, you can build bulletin requests and transport them to these types of targets:
- Topic proper noun
- Condition
- Device registration token
- Device group proper name (legacy protocols and Firebase Admin SDK for Node.js only)
You can transport messages with a notification payload made up of predefined fields, a data payload of your own user-defined fields, or a bulletin containing both types of payload. Meet Message types for more information.
Examples in this folio testify how to send notification messages using the Firebase Admin SDK (which has support for Node, Java, Python, C#, and Go) and the v1 HTTP protocol. There is also guidance for sending letters via the legacy HTTP and XMPP protocols.
Send letters to specific devices
To send to a single, specific device, pass the device's registration token every bit shown. See the client setup data for your platform to learn more about registration tokens.
Node.js
// This registration token comes from the client FCM SDKs. const registrationToken = 'YOUR_REGISTRATION_TOKEN'; const message = { data: { score: '850', fourth dimension: '2:45' }, token: registrationToken }; // Send a bulletin to the device corresponding to the provided // registration token. getMessaging().send(message) .and then((response) => { // Response is a bulletin ID string. panel.log('Successfully sent bulletin:', response); }) .take hold of((error) => { console.log('Error sending bulletin:', fault); });
Java
// This registration token comes from the client FCM SDKs. String registrationToken = "YOUR_REGISTRATION_TOKEN"; // See documentation on defining a message payload. Message message = Message.builder() .putData("score", "850") .putData("time", "2:45") .setToken(registrationToken) .build(); // Send a message to the device corresponding to the provided // registration token. String response = FirebaseMessaging.getInstance().send(message); // Response is a message ID string. System.out.println("Successfully sent message: " + response); FirebaseMessagingSnippets.java
Python
# This registration token comes from the customer FCM SDKs. registration_token = 'YOUR_REGISTRATION_TOKEN' # See documentation on defining a bulletin payload. message = messaging.Message( information={ 'score': '850', 'time': '2:45', }, token=registration_token, ) # Transport a message to the device corresponding to the provided # registration token. response = messaging.send(message) # Response is a message ID string. print('Successfully sent message:', response) cloud_messaging.py
Go
// Obtain a messaging.Client from the App. ctx := context.Groundwork() customer, err := app.Messaging(ctx) if err != nil { log.Fatalf("error getting Messaging customer: %v\northward", err) } // This registration token comes from the client FCM SDKs. registrationToken := "YOUR_REGISTRATION_TOKEN" // See documentation on defining a message payload. bulletin := &messaging.Bulletin{ Data: map[string]string{ "score": "850", "time": "two:45", }, Token: registrationToken, } // Send a message to the device corresponding to the provided // registration token. response, err := customer.Transport(ctx, message) if err != nil { log.Fatalln(err) } // Response is a message ID string. fmt.Println("Successfully sent message:", response) messaging.go
C#
// This registration token comes from the client FCM SDKs. var registrationToken = "YOUR_REGISTRATION_TOKEN"; // See documentation on defining a bulletin payload. var message = new Message() { Data = new Dictionary<string, string>() { { "score", "850" }, { "time", "2:45" }, }, Token = registrationToken, }; // Send a message to the device corresponding to the provided // registration token. cord response = await FirebaseMessaging.DefaultInstance.SendAsync(message); // Response is a message ID string. Panel.WriteLine("Successfully sent message: " + response);
REST
Mail service https://fcm.googleapis.com/v1/projects/myproject-b5ae1/letters:send HTTP/1.1 Content-Type: application/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "bulletin":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "torso":"This is an FCM notification message!", "championship":"FCM Bulletin" } } }
cURL command:
curl -X Mail service -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{ "message":{ "notification":{ "title":"FCM Message", "trunk":"This is an FCM Message" }, "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." }}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
On success, each send method returns a message ID. The Firebase Admin SDK returns the ID string in the format projects/{project_id}/letters/{message_id}
. The HTTP protocol response is a single JSON key:
{ "proper name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96" }
Ship messages to multiple devices
The REST API and the Admin FCM APIs permit you to multicast a bulletin to a listing of device registration tokens. You tin specify up to 500 device registration tokens per invocation.
Node.js
// Create a listing containing up to 500 registration tokens. // These registration tokens come from the client FCM SDKs. const registrationTokens = [ 'YOUR_REGISTRATION_TOKEN_1', // … 'YOUR_REGISTRATION_TOKEN_N', ]; const bulletin = { data: {score: '850', time: '2:45'}, tokens: registrationTokens, }; getMessaging().sendMulticast(message) .so((response) => { console.log(response.successCount + ' messages were sent successfully'); });
Java
// Create a listing containing upwardly to 500 registration tokens. // These registration tokens come from the client FCM SDKs. Listing<String> registrationTokens = Arrays.asList( "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n" ); MulticastMessage message = MulticastMessage.builder() .putData("score", "850") .putData("time", "2:45") .addAllTokens(registrationTokens) .build(); BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message); // See the BatchResponse reference documentation // for the contents of response. System.out.println(response.getSuccessCount() + " messages were sent successfully"); FirebaseMessagingSnippets.java
Python
# Create a list containing up to 500 registration tokens. # These registration tokens come from the client FCM SDKs. registration_tokens = [ 'YOUR_REGISTRATION_TOKEN_1', # ... 'YOUR_REGISTRATION_TOKEN_N', ] message = messaging.MulticastMessage( data={'score': '850', 'time': 'ii:45'}, tokens=registration_tokens, ) response = messaging.send_multicast(message) # See the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count)) cloud_messaging.py
Go
// Create a list containing upward to 500 registration tokens. // This registration tokens come from the client FCM SDKs. registrationTokens := []cord{ "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n", } bulletin := &messaging.MulticastMessage{ Data: map[string]string{ "score": "850", "fourth dimension": "2:45", }, Tokens: registrationTokens, } br, err := client.SendMulticast(context.Background(), message) if err != cipher { log.Fatalln(err) } // See the BatchResponse reference documentation // for the contents of response. fmt.Printf("%d letters were sent successfully\due north", br.SuccessCount) messaging.go
C#
// Create a list containing up to 500 registration tokens. // These registration tokens come from the client FCM SDKs. var registrationTokens = new List<string>() { "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n", }; var message = new MulticastMessage() { Tokens = registrationTokens, Data = new Lexicon<cord, cord>() { { "score", "850" }, { "time", "2:45" }, }, }; var response = wait FirebaseMessaging.DefaultInstance.SendMulticastAsync(message); // Encounter the BatchResponse reference documentation // for the contents of response. Console.WriteLine($"{response.SuccessCount} messages were sent successfully"); FirebaseMessagingSnippets.cs
Balance
Construct an HTTP batch request:
--subrequest_boundary Content-Blazon: application/http Content-Transfer-Encoding: binary Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA POST /v1/projects/myproject-b5ae1/messages:send Content-Type: awarding/json accept: application/json { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"FCM Bulletin", "body":"This is an FCM notification message!" } } } ... --subrequest_boundary Content-Type: application/http Content-Transfer-Encoding: binary Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA Post /v1/projects/myproject-b5ae1/messages:ship Content-Type: awarding/json take: application/json { "message":{ "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...", "notification":{ "title":"FCM Message", "trunk":"This is an FCM notification message!" } } } --subrequest_boundary--
Salve the request into a file (in this instance batch_request.txt). So apply the cURL command:
whorl --data-binary @batch_request.txt -H 'Content-Type: multipart/mixed; boundary="subrequest_boundary"' https://fcm.googleapis.com/batch
For Firebase Admin SDKs, this performance uses the sendAll()
API nether the hood, every bit shown in the examples. The return value is a BatchResponse
whose responses list corresponds to the order of the input tokens. This is useful when you want to cheque which tokens resulted in errors.
Node.js
// These registration tokens come from the customer FCM SDKs. const registrationTokens = [ 'YOUR_REGISTRATION_TOKEN_1', // … 'YOUR_REGISTRATION_TOKEN_N', ]; const message = { data: {score: '850', time: '2:45'}, tokens: registrationTokens, }; getMessaging().sendMulticast(message) .then((response) => { if (response.failureCount > 0) { const failedTokens = []; response.responses.forEach((resp, idx) => { if (!resp.success) { failedTokens.push button(registrationTokens[idx]); } }); console.log('Listing of tokens that caused failures: ' + failedTokens); } });
Java
// These registration tokens come up from the client FCM SDKs. List<String> registrationTokens = Arrays.asList( "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n" ); MulticastMessage message = MulticastMessage.builder() .putData("score", "850") .putData("fourth dimension", "2:45") .addAllTokens(registrationTokens) .build(); BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message); if (response.getFailureCount() > 0) { List<SendResponse> responses = response.getResponses(); List<String> failedTokens = new ArrayList<>(); for (int i = 0; i < responses.size(); i++) { if (!responses.become(i).isSuccessful()) { // The order of responses corresponds to the guild of the registration tokens. failedTokens.add(registrationTokens.get(i)); } } System.out.println("List of tokens that caused failures: " + failedTokens); } FirebaseMessagingSnippets.java
Python
# These registration tokens come up from the client FCM SDKs. registration_tokens = [ 'YOUR_REGISTRATION_TOKEN_1', # ... 'YOUR_REGISTRATION_TOKEN_N', ] bulletin = messaging.MulticastMessage( information={'score': '850', 'time': '2:45'}, tokens=registration_tokens, ) response = messaging.send_multicast(message) if response.failure_count > 0: responses = response.responses failed_tokens = [] for idx, resp in enumerate(responses): if not resp.success: # The order of responses corresponds to the order of the registration tokens. failed_tokens.append(registration_tokens[idx]) print('List of tokens that acquired failures: {0}'.format(failed_tokens)) cloud_messaging.py
Get
// Create a list containing up to 500 registration tokens. // This registration tokens come up from the customer FCM SDKs. registrationTokens := []string{ "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n", } bulletin := &messaging.MulticastMessage{ Data: map[string]cord{ "score": "850", "time": "2:45", }, Tokens: registrationTokens, } br, err := client.SendMulticast(context.Background(), message) if err != nil { log.Fatalln(err) } if br.FailureCount > 0 { var failedTokens []string for idx, resp := range br.Responses { if !resp.Success { // The order of responses corresponds to the club of the registration tokens. failedTokens = append(failedTokens, registrationTokens[idx]) } } fmt.Printf("List of tokens that caused failures: %v\northward", failedTokens) } messaging.go
C#
// These registration tokens come up from the client FCM SDKs. var registrationTokens = new Listing<string>() { "YOUR_REGISTRATION_TOKEN_1", // ... "YOUR_REGISTRATION_TOKEN_n", }; var bulletin = new MulticastMessage() { Tokens = registrationTokens, Data = new Lexicon<string, cord>() { { "score", "850" }, { "fourth dimension", "2:45" }, }, }; var response = wait FirebaseMessaging.DefaultInstance.SendMulticastAsync(message); if (response.FailureCount > 0) { var failedTokens = new List<string>(); for (var i = 0; i < response.Responses.Count; i++) { if (!response.Responses[i].IsSuccess) { // The order of responses corresponds to the social club of the registration tokens. failedTokens.Add(registrationTokens[i]); } } Panel.WriteLine($"List of tokens that caused failures: {failedTokens}"); } FirebaseMessagingSnippets.cs
REST
Each send sub-send returns a response. Responses are separated by a response boundary string starting with --batch_
.
--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q Content-Type: awarding/http Content-ID: response- HTTP/one.1 200 OK Content-Type: application/json; charset=UTF-8 Vary: Origin Vary: X-Origin Vary: Referer { "name": "projects/35006771263/messages/0:1570471792141125%43c11b7043c11b70" } ... --batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q Content-Blazon: awarding/http Content-ID: response- HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-viii Vary: Origin Vary: X-Origin Vary: Referer { "name": "projects/35006771263/messages/0:1570471792141696%43c11b7043c11b70" } --batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q--
Ship letters to topics
After you have created a topic, either by subscribing client app instances to the topic on the customer side or via the server API, yous can ship messages to the topic. If this is your commencement time building send requests for FCM, encounter the guide to your server environment and FCM for important background and setup information.
In your sending logic on the backend, specify the desired topic proper name as shown:
Node.js
// The topic proper name tin exist optionally prefixed with "/topics/". const topic = 'highScores'; const bulletin = { data: { score: '850', time: '2:45' }, topic: topic }; // Transport a message to devices subscribed to the provided topic. getMessaging().send(message) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); }) .catch((fault) => { console.log('Error sending message:', error); });
Java
// The topic name can be optionally prefixed with "/topics/". String topic = "highScores"; // See documentation on defining a bulletin payload. Message message = Message.builder() .putData("score", "850") .putData("time", "two:45") .setTopic(topic) .build(); // Transport a message to the devices subscribed to the provided topic. String response = FirebaseMessaging.getInstance().send(message); // Response is a message ID cord. System.out.println("Successfully sent bulletin: " + response); FirebaseMessagingSnippets.java
Python
# The topic proper name can be optionally prefixed with "/topics/". topic = 'highScores' # See documentation on defining a message payload. message = messaging.Bulletin( data={ 'score': '850', 'time': '2:45', }, topic=topic, ) # Send a bulletin to the devices subscribed to the provided topic. response = messaging.transport(message) # Response is a message ID string. print('Successfully sent bulletin:', response) cloud_messaging.py
Go
// The topic name tin can be optionally prefixed with "/topics/". topic := "highScores" // See documentation on defining a message payload. message := &messaging.Message{ Data: map[string]string{ "score": "850", "time": "ii:45", }, Topic: topic, } // Ship a message to the devices subscribed to the provided topic. response, err := client.Ship(ctx, message) if err != aught { log.Fatalln(err) } // Response is a bulletin ID string. fmt.Println("Successfully sent bulletin:", response) messaging.go
C#
// The topic proper noun can be optionally prefixed with "/topics/". var topic = "highScores"; // See documentation on defining a message payload. var message = new Message() { Data = new Dictionary<string, string>() { { "score", "850" }, { "time", "two:45" }, }, Topic = topic, }; // Send a bulletin to the devices subscribed to the provided topic. string response = wait FirebaseMessaging.DefaultInstance.SendAsync(message); // Response is a message ID cord. Console.WriteLine("Successfully sent message: " + response);
REST
Mail service https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:transport HTTP/1.1 Content-Type: application/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "message":{ "topic" : "foo-bar", "notification" : { "trunk" : "This is a Firebase Cloud Messaging Topic Message!", "title" : "FCM Message" } } }
cURL command:
ringlet -X Mail -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{ "message": { "topic" : "foo-bar", "notification": { "trunk": "This is a Firebase Cloud Messaging Topic Message!", "title": "FCM Bulletin" } } }' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/letters:ship HTTP/1.ane
To transport a message to a combination of topics, specify a status, which is a boolean expression that specifies the target topics. For example, the following status will ship messages to devices that are subscribed to TopicA
and either TopicB
or TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM get-go evaluates any atmospheric condition in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the bulletin. As well, a user who does non subscribe to TopicA
does not receive the message. These combinations do receive it:
-
TopicA
andTopicB
-
TopicA
andTopicC
Y'all tin include upward to five topics in your conditional expression.
To send to a condition:
Node.js
// Define a condition which volition ship to devices which are subscribed // to either the Google stock or the tech industry topics. const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics'; // Encounter documentation on defining a message payload. const message = { notification: { title: '$FooCorp up ane.43% on the day', body: '$FooCorp gained xi.80 points to close at 835.67, up i.43% on the day.' }, condition: condition }; // Ship a message to devices subscribed to the combination of topics // specified by the provided condition. getMessaging().send(message) .and so((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', error); });
Java
// Define a condition which will send to devices which are subscribed // to either the Google stock or the tech industry topics. Cord condition = "'stock-GOOG' in topics || 'industry-tech' in topics"; // See documentation on defining a bulletin payload. Bulletin message = Message.architect() .setNotification(Notification.builder() .setTitle("$GOOG upward 1.43% on the day") .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.") .build()) .setCondition(condition) .build(); // Send a bulletin to devices subscribed to the combination of topics // specified by the provided status. String response = FirebaseMessaging.getInstance().transport(message); // Response is a message ID string. System.out.println("Successfully sent message: " + response); FirebaseMessagingSnippets.java
Python
# Define a condition which volition send to devices which are subscribed # to either the Google stock or the tech manufacture topics. condition = "'stock-GOOG' in topics || 'industry-tech' in topics" # See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title='$GOOG up one.43% on the day', body='$GOOG gained eleven.eighty points to shut at 835.67, up i.43% on the day.', ), condition=condition, ) # Transport a message to devices subscribed to the combination of topics # specified by the provided condition. response = messaging.send(bulletin) # Response is a message ID cord. print('Successfully sent message:', response) cloud_messaging.py
Become
// Define a status which will send to devices which are subscribed // to either the Google stock or the tech industry topics. condition := "'stock-GOOG' in topics || 'industry-tech' in topics" // See documentation on defining a message payload. message := &messaging.Message{ Information: map[cord]cord{ "score": "850", "time": "2:45", }, Condition: condition, } // Send a message to devices subscribed to the combination of topics // specified by the provided condition. response, err := client.Send(ctx, bulletin) if err != nil { log.Fatalln(err) } // Response is a message ID string. fmt.Println("Successfully sent message:", response) messaging.go
C#
// Define a status which volition transport to devices which are subscribed // to either the Google stock or the tech manufacture topics. var condition = "'stock-GOOG' in topics || 'manufacture-tech' in topics"; // See documentation on defining a bulletin payload. var message = new Message() { Notification = new Notification() { Title = "$GOOG up 1.43% on the day", Body = "$GOOG gained 11.80 points to shut at 835.67, up 1.43% on the day.", }, Condition = condition, }; // Send a message to devices subscribed to the combination of topics // specified by the provided condition. string response = await FirebaseMessaging.DefaultInstance.SendAsync(message); // Response is a message ID string. Console.WriteLine("Successfully sent message: " + response);
REST
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/letters:transport HTTP/i.1 Content-Blazon: application/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "bulletin":{ "condition": "'dogs' in topics || 'cats' in topics", "notification" : { "body" : "This is a Firebase Cloud Messaging Topic Bulletin!", "championship" : "FCM Message", } } }
cURL command:
coil -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{ "notification": { "title": "FCM Message", "body": "This is a Firebase Cloud Messaging Topic Message!", }, "status": "'dogs' in topics || 'cats' in topics" }' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Transport a batch of messages
The Residual API and Admin SDKs support sending messages in batches. Yous can group up to 500 letters into a single batch and send them all in a single API call, with pregnant performance comeback over sending separate HTTP requests for each message.
This feature can be used to build a customized set up of messages and send them to dissimilar recipients, including topics or specific device registration tokens. Use this feature when, for case, you need to simultaneously transport messages to different audiences with slightly dissimilar details in the message body.
Node.js
// Create a list containing upward to 500 messages. const letters = []; letters.push({ notification: { title: 'Toll drop', body: '5% off all electronics' }, token: registrationToken, }); messages.push({ notification: { title: 'Price drop', trunk: '2% off all books' }, topic: 'readers-club', }); getMessaging().sendAll(messages) .so((response) => { console.log(response.successCount + ' letters were sent successfully'); });
Java
// Create a listing containing up to 500 messages. List<Message> letters = Arrays.asList( Message.builder() .setNotification(Notification.builder() .setTitle("Cost drop") .setBody("five% off all electronics") .build()) .setToken(registrationToken) .build(), // ... Message.architect() .setNotification(Notification.builder() .setTitle("Price drop") .setBody("2% off all books") .build()) .setTopic("readers-social club") .build() ); BatchResponse response = FirebaseMessaging.getInstance().sendAll(messages); // See the BatchResponse reference documentation // for the contents of response. Organisation.out.println(response.getSuccessCount() + " messages were sent successfully"); FirebaseMessagingSnippets.java
Python
# Create a list containing upwardly to 500 messages. messages = [ messaging.Message( notification=messaging.Notification('Price drib', 'v% off all electronics'), token=registration_token, ), # ... messaging.Message( notification=messaging.Notification('Price drop', '2% off all books'), topic='readers-guild', ), ] response = messaging.send_all(messages) # Run across the BatchResponse reference documentation # for the contents of response. print('{0} messages were sent successfully'.format(response.success_count)) cloud_messaging.py
Go
// Create a list containing up to 500 messages. letters := []*messaging.Message{ { Notification: &messaging.Notification{ Title: "Price drib", Body: "five% off all electronics", }, Token: registrationToken, }, { Notification: &messaging.Notification{ Title: "Price drop", Trunk: "two% off all books", }, Topic: "readers-club", }, } br, err := client.SendAll(context.Groundwork(), messages) if err != zero { log.Fatalln(err) } // Run into the BatchResponse reference documentation // for the contents of response. fmt.Printf("%d messages were sent successfully\due north", br.SuccessCount) messaging.go
C#
// Create a list containing up to 500 messages. var messages = new Listing<Message>() { new Message() { Notification = new Notification() { Title = "Price drop", Body = "v% off all electronics", }, Token = registrationToken, }, new Message() { Notification = new Notification() { Championship = "Toll drop", Body = "ii% off all books", }, Topic = "readers-society", }, }; var response = await FirebaseMessaging.DefaultInstance.SendAllAsync(messages); // See the BatchResponse reference documentation // for the contents of response. Console.WriteLine($"{response.SuccessCount} messages were sent successfully"); FirebaseMessagingSnippets.cs
REST
Construct an HTTP batch request by combining a list of sub requests:
--subrequest_boundary Content-Type: application/http Content-Transfer-Encoding: binary Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA POST /v1/projects/myproject-b5ae1/messages:send Content-Type: application/json have: awarding/json { "bulletin":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"FCM Bulletin", "body":"This is an FCM notification bulletin to device 0!" } } } --subrequest_boundary Content-Blazon: awarding/http Content-Transfer-Encoding: binary Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA POST /v1/projects/myproject-b5ae1/messages:send Content-Type: application/json accept: application/json { "message":{ "topic":"readers-social club", "notification":{ "title":"Price drop", "body":"ii% off all books" } } } ... --subrequest_boundary Content-Type: application/http Content-Transfer-Encoding: binary Potency: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA POST /v1/projects/myproject-b5ae1/messages:transport Content-Type: application/json take: awarding/json { "bulletin":{ "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...", "notification":{ "title":"FCM Message", "body":"This is an FCM notification message to device N!" } } } --subrequest_boundary--
You can query the returned BatchResponse
to check how many of the messages were handed off to FCM successfully. It also exposes a listing of responses that can exist used to check the state of individual messages. The order of the responses corresponds to the lodge of the messages in the input list.
Send straight boot-enabled messages (Android only)
You can ship messages to devices in direct boot manner using the HTTP v1 or legacy HTTP APIs. Before sending to devices in direct kick mode, make certain you accept completed the steps to enable client devices to receive FCM messages in direct boot mode.
Send using the FCM v1 HTTP API
The message request must include the key "direct_boot_ok" : true
in the AndroidConfig
options of the asking body. For example:
https://fcm.googleapis.com/v1/projects/myproject-b5ae1/letters:send Content-Type:application/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "Message":{ "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." "information": { "score": "5x1", "fourth dimension": "fifteen:10" }, "android": { "direct_boot_ok": true, }, }
Send using the FCM legacy HTTP API
The bulletin request must include the key "direct_boot_ok" : true
at the superlative level of the request body. For example:
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA { "data": { "score": "5x1", "time": "xv:ten" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." "direct_boot_ok" : true }
Letters sent with this key in the request torso can be handled past apps on devices currently in direct kicking mode (and likewise when not in that style).
Customize letters beyond platforms
The Firebase Admin SDK and the FCM v1 HTTP protocol both allow your message requests to prepare all fields available in the bulletin
object. This includes:
- a common set of fields to be interpreted by all app instances that receive the message.
- platform-specific sets of fields, such every bit
AndroidConfig
andWebpushConfig
, interpreted merely by app instances running on the specified platform.
Platform-specific blocks requite yous flexibility to customize messages for different platforms to ensure that they are handled correctly when received. The FCM backend will take all specified parameters into business relationship and customize the message for each platform.
When to use common fields
Employ common fields when you're:
- Targeting app instances on all platforms — Apple tree, Android, and web
- Sending messages to topics
All app instances, regardless of platform, can interpret the post-obit common fields:
-
message.notification.title
-
message.notification.body
-
message.information
When to utilize platform-specific fields
Utilize platform-specific fields when y'all want to:
- Send fields merely to item platforms
- Ship platform-specific fields in addition to the mutual fields
Whenever y'all want to send values just to particular platforms, don't use mutual fields; use platform-specific fields. For instance, to ship a notification only to Apple tree platforms and web but not to Android, yous must utilise two separate sets of fields, one for Apple tree and one for web.
When you lot are sending messages with specific delivery options, utilise platform-specific fields to set them. You lot can specify different values per platform if you want. However, fifty-fifty when you desire to set essentially the same value across platforms, you must use platform-specific fields. This is because each platform may interpret the value slightly differently—for example, fourth dimension-to-live is set on Android as an expiration time in seconds, while on Apple tree information technology is set every bit an expiration date.
Example: notification message with color and icon options
This instance send request sends a common notification title and content to all platforms, but it as well sends some platform-specific overrides to Android devices.
For Android, the request sets a special icon and color to display on Android devices. Every bit noted in the reference for AndroidNotification, the color is specified in #rrggbb format, and the image must be a drawable icon resources local to the Android app.
Hither's an approximation of the visual outcome on a user's device:
Node.js
const topicName = 'industry-tech'; const message = { notification: { championship: '`$FooCorp` up one.43% on the twenty-four hour period', body: 'FooCorp gained 11.80 points to shut at 835.67, up 1.43% on the day.' }, android: { notification: { icon: 'stock_ticker_update', color: '#7e55c3' } }, topic: topicName, }; getMessaging().send(bulletin) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); }) .catch((fault) => { console.log('Mistake sending message:', mistake); });
Java
Message message = Message.builder() .setNotification(Notification.builder() .setTitle("$GOOG upwards 1.43% on the mean solar day") .setBody("$GOOG gained 11.lxxx points to shut at 835.67, up 1.43% on the day.") .build()) .setAndroidConfig(AndroidConfig.builder() .setTtl(3600 * 1000) .setNotification(AndroidNotification.builder() .setIcon("stock_ticker_update") .setColor("#f45342") .build()) .build()) .setApnsConfig(ApnsConfig.builder() .setAps(Aps.architect() .setBadge(42) .build()) .build()) .setTopic("industry-tech") .build(); FirebaseMessagingSnippets.java
Python
message = messaging.Message( notification=messaging.Notification( championship='$GOOG upwardly 1.43% on the twenty-four hours', trunk='$GOOG gained 11.80 points to close at 835.67, upwards ane.43% on the day.', ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342' ), ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(bluecoat=42), ), ), topic='industry-tech', ) cloud_messaging.py
Go
oneHour := time.Elapsing(1) * time.Hour bluecoat := 42 message := &messaging.Bulletin{ Notification: &messaging.Notification{ Title: "$GOOG upward 1.43% on the day", Body: "$GOOG gained 11.80 points to close at 835.67, up ane.43% on the day.", }, Android: &messaging.AndroidConfig{ TTL: &oneHour, Notification: &messaging.AndroidNotification{ Icon: "stock_ticker_update", Color: "#f45342", }, }, APNS: &messaging.APNSConfig{ Payload: &messaging.APNSPayload{ Aps: &messaging.Aps{ Badge: &badge, }, }, }, Topic: "industry-tech", } messaging.go
C#
var message = new Bulletin { Notification = new Notification() { Title = "$GOOG upward 1.43% on the mean solar day", Body = "$GOOG gained 11.lxxx points to shut at 835.67, up 1.43% on the 24-hour interval.", }, Android = new AndroidConfig() { TimeToLive = TimeSpan.FromHours(1), Notification = new AndroidNotification() { Icon = "stock_ticker_update", Color = "#f45342", }, }, Apns = new ApnsConfig() { Aps = new Aps() { Badge = 42, }, }, Topic = "industry-tech", }; FirebaseMessagingSnippets.cs
Residuum
Mail https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:ship HTTP/i.1 Content-Blazon: awarding/json Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "message":{ "topic":"industry-tech", "notification":{ "title":"`$FooCorp` upwards 1.43% on the 24-hour interval", "body":"FooCorp gained eleven.80 points to shut at 835.67, up 1.43% on the day." }, "android":{ "notification":{ "icon":"stock_ticker_update", "color":"#7e55c3" } } } }
See the HTTP v1 reference documentation for complete item on the keys available in platform-specific blocks in the message trunk.
Example: notification message with a custom epitome
The post-obit example send asking sends a mutual notification title to all platforms, but it also sends an epitome. Here's an approximation of the visual event on a user's device:
Node.js
const topicName = 'industry-tech'; const message = { notification: { title: 'Sparky says hullo!' }, android: { notification: { imageUrl: 'https://foo.bar.pizza-monster.png' } }, apns: { payload: { aps: { 'mutable-content': one } }, fcm_options: { paradigm: 'https://foo.bar.pizza-monster.png' } }, webpush: { headers: { image: 'https://foo.bar.pizza-monster.png' } }, topic: topicName, }; getMessaging().send(message) .then((response) => { // Response is a message ID string. panel.log('Successfully sent bulletin:', response); }) .catch((error) => { console.log('Mistake sending message:', fault); });
REST
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/ane.1 Content-Type: application/json Authorisation: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "message":{ "topic":"industry-tech", "notification":{ "title":"Sparky says hi!", }, "android":{ "notification":{ "image":"https://foo.bar/pizza-monster.png" } }, "apns":{ "payload":{ "aps":{ "mutable-content":1 } }, "fcm_options": { "image":"https://foo.bar/pizza-monster.png" } }, "webpush":{ "headers":{ "image":"https://foo.bar/pizza-monster.png" } } } }
Meet the HTTP v1 reference documentation for complete detail on the keys bachelor in platform-specific blocks in the message body.
Example: notification bulletin with an associated click activity
The following example send asking sends a common notification title to all platforms, merely information technology besides sends an action for the app to perform in response to user interacting with the notification. Here's an approximation of the visual result on a user'southward device:
Node.js
const topicName = 'industry-tech'; const message = { notification: { title: 'Breaking News....' }, android: { notification: { clickAction: 'news_intent' } }, apns: { payload: { aps: { 'category': 'INVITE_CATEGORY' } } }, webpush: { fcmOptions: { link: 'breakingnews.html' } }, topic: topicName, }; getMessaging().send(message) .then((response) => { // Response is a message ID cord. console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', mistake); });
Residual
Postal service https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.i Content-Type: application/json Say-so: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "message":{ "topic":"industry-tech", "notification":{ "title":"Breaking News...", }, "android":{ "notification":{ "click_action":"news_intent" } }, "apns":{ "payload":{ "aps":{ "category" : "INVITE_CATEGORY" } }, }, "webpush":{ "fcm_options":{ "link":"breakingnews.html" } } } }
See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.
Example: notification bulletin with localization options
The post-obit instance send request sends localization options for the customer to display localized messages. Here'south an approximation of the visual effect on a user's device:
Node.js
var topicName = 'industry-tech'; var bulletin = { android: { ttl: 3600000, notification: { bodyLocKey: 'STOCK_NOTIFICATION_BODY', bodyLocArgs: ['FooCorp', '11.eighty', '835.67', 'one.43'] } }, apns: { payload: { aps: { alarm: { locKey: 'STOCK_NOTIFICATION_BODY', locArgs: ['FooCorp', '11.80', '835.67', '1.43'] } } } }, topic: topicName, }; getMessaging().transport(message) .then((response) => { // Response is a bulletin ID string. console.log('Successfully sent message:', response); }) .take hold of((error) => { console.log('Error sending message:', error); });
REST
Mail https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1 Content-Type: application/json Authority: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA { "message":{ "topic":"Tech", "android":{ "ttl":"3600s", "notification":{ "body_loc_key": "STOCK_NOTIFICATION_BODY", "body_loc_args": ["FooCorp", "eleven.80", "835.67", "ane.43"], }, }, "apns":{ "payload":{ "aps":{ "alert" : { "loc-key": "STOCK_NOTIFICATION_BODY", "loc-args": ["FooCorp", "11.80", "835.67", "i.43"], }, }, }, }, }, }'
See the HTTP v1 reference documentation for complete detail on the keys available in platform-specific blocks in the message body.
Admin error codes
The following table lists the Firebase Admin FCM API error codes and their descriptions, including recommended resolution steps.
Fault Code | Description and Resolution Steps |
---|---|
messaging/invalid-statement | An invalid argument was provided to an FCM method. The error message should contain additional data. |
messaging/invalid-recipient | The intended message recipient is invalid. The fault message should contain boosted data. |
messaging/invalid-payload | An invalid bulletin payload object was provided. The error message should contain additional data. |
messaging/invalid-data-payload-key | The data message payload contains an invalid central. See the reference documentation for DataMessagePayload for restricted keys. |
messaging/payload-size-limit-exceeded | The provided message payload exceeds the FCM size limits. The limit is 4096 bytes for most messages. For messages sent to topics, the limit is 2048 bytes. The total payload size includes both keys and values. |
messaging/invalid-options | An invalid message options object was provided. The error bulletin should contain additional information. |
messaging/invalid-registration-token | Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM. Do non truncate or add together additional characters to information technology. |
messaging/registration-token-not-registered | The provided registration token is not registered. A previously valid registration token tin be unregistered for a diverseness of reasons, including:
|
messaging/invalid-package-proper name | The message was addressed to a registration token whose packet proper noun does not lucifer the provided restrictedPackageName choice. |
messaging/message-rate-exceeded | The charge per unit of messages to a particular target is also high. Reduce the number of messages sent to this device or topic and do not immediately retry sending to this target. |
messaging/device-bulletin-rate-exceeded | The rate of messages to a particular device is too high. Reduce the number of letters sent to this device and practise not immediately retry sending to this device. |
messaging/topics-message-rate-exceeded | The rate of messages to subscribers to a item topic is too high. Reduce the number of letters sent for this topic, and do not immediately retry sending to this topic. |
messaging/also-many-topics | A registration token has been subscribed to the maximum number of topics and cannot exist subscribed to whatsoever more than. |
messaging/invalid-apns-credentials | A bulletin targeted to an Apple device could not be sent because the required APNs SSL document was not uploaded or has expired. Check the validity of your development and product certificates. |
messaging/mismatched-credential | The credential used to authenticate this SDK does not have permission to transport messages to the device respective to the provided registration token. Make sure the credential and registration token both belong to the same Firebase project. Meet Add Firebase to your app for documentation on how to authenticate the Firebase Admin SDKs. |
messaging/authentication-fault | The SDK could non authenticate to the FCM servers. Make sure you authenticate the Firebase Admin SDK with a credential which has the proper permissions to transport FCM letters. See Add together Firebase to your app for documentation on how to cosign the Firebase Admin SDKs. |
messaging/server-unavailable | The FCM server could not process the request in time. You should retry the same request, just you must:
|
messaging/internal-error | The FCM server encountered an error while trying to process the request. You could retry the aforementioned request following the requirements listed in the messaging/server-unavailable row above. If the mistake persists, delight study the trouble to our Issues Report support channel. |
messaging/unknown-error | An unknown server error was returned. Run into the raw server response in the mistake bulletin for more details. If you lot receive this error, please report the full error message to our Bug Study back up aqueduct. |
Send letters using the legacy app server protocols
If you prefer to use the legacy protocols, build bulletin requests as shown in this section. Keep in mind that, if you are sending to multiple platforms via HTTP, the v1 protocol tin can simplify your bulletin requests.
Ship messages to specific devices
To send messages to specific devices, set the to
key to the registration token for the specific app case. Run across the client setup information for your platform to learn more nigh registration tokens.
HTTP Mail service request
https://fcm.googleapis.com/fcm/send Content-Type:application/json Say-so:key=AIzaSyZ-1u...0GBYzPu7Udno5aA { "data": { "score": "5x1", "time": "xv:ten" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." }
HTTP response
{ "multicast_id": 108, "success": ane, "failure": 0, "results": [ { "message_id": "1:08" } ] }
XMPP message
<bulletin id=""> <gcm xmlns="google:mobile:data"> { "data": { "score": "5x1", "time": "fifteen:ten" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } </gcm> </message>
XMPP response
<bulletin id=""> <gcm xmlns="google:mobile:information"> { "from":"REGID", "message_id":"yard-1366082849205" "message_type":"ack" } </gcm> </message>
The XMPP connection server provides another options for responses. See Server response format.
For the full list of message options available when sending downstream letters to client apps, run into the reference information for your called connection server protocol, HTTP or XMPP.
Send letters to topics
Sending messages to a Firebase Cloud Messaging topic is very similar to sending letters to an individual device or to a user group. The app server sets the to
fundamental with a value like /topics/yourTopic
. Developers can choose any topic proper noun that matches the regular expression: "/topics/[a-zA-Z0-ix-_.~%]+"
.
To send to combinations of multiple topics, the app server must set the status
key (instead of the to
key) to a boolean condition that specifies the target topics. For case, to send messages to devices that subscribed to TopicA
and either TopicB
or TopicC
:
'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)
FCM starting time evaluates whatsoever weather in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does non receive the message. Likewise, a user who does not subscribe to TopicA does not receive the bulletin. These combinations do receive it:
- TopicA and TopicB
- TopicA and TopicC
You can include upwards to 5 topics in your conditional expression, and parentheses are supported. Supported operators: &&
, ||
.
Topic HTTP Post asking
Ship to a single topic:
https://fcm.googleapis.com/fcm/transport Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
Send to devices subscribed to topics "dogs" or "cats":
https://fcm.googleapis.com/fcm/send Content-Blazon:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
Topic HTTP response
//Success case: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
Topic XMPP message
Send to a single topic:
<bulletin id=""> <gcm xmlns="google:mobile:data"> </gcm> </message>
Send to devices subscribed to topics "dogs" or "cats":
<message id=""> <gcm xmlns="google:mobile:data"> </gcm> </bulletin>
Topic XMPP response
//Success instance: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
Expect upwards to 30 seconds of delay before the FCM Server returns a success or failure response to the topic send requests. Brand certain to prepare the app server's timeout value in the asking appropriately.
Transport messages to device groups
Sending messages to a device grouping is very similar to sending messages to an private device. Set the to
parameter to the unique notification key for the device group. See Message types for details on payload support. Examples in this folio evidence how to send data letters to device groups in the legacy HTTP and XMPP protocols.
Device Grouping HTTP Mail service Request
https://fcm.googleapis.com/fcm/ship Content-Type:application/json Potency:cardinal=AIzaSyZ-1u...0GBYzPu7Udno5aA { "to": "aUniqueKey", "data": { "hello": "This is a Firebase Deject Messaging Device Group Message!", } }
Device Group HTTP Response
Hither is an example of "success"— the notification_key
has 2 registration tokens associated with it, and the message was successfully sent to both of them:
{ "success": 2, "failure": 0 }
Hither is an instance of "fractional success" — the notification_key
has iii registration tokens associated with information technology. The message was successfully sent to 1 of the registration tokens simply. The response message lists the registration tokens (registration_ids
) that failed to receive the message:
{ "success":ane, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
When a message fails to be delivered to ane or more of the registration tokens associated with a notification_key
, the app server should retry with backoff between retries.
If the server attempts to transport a message to a device grouping that has no members, the response looks similar the following, with 0 success and 0 failure:
{ "success": 0, "failure": 0 }
Device Group XMPP Message
<message id=""> <gcm xmlns="google:mobile:information"> { "to": "aUniqueKey", "message_id": "m-1366082849205" , "data": { "hello":"This is a Firebase Deject Messaging Device Group Message!" } } </gcm> </bulletin>
Device Grouping XMPP Response
When the bulletin is sent to whatever one of the devices in the grouping successfully, the XMPP connection server responds with an ACK. If all messages sent to all devices in the group fail, XMPP connectedness server responds with a NACK.
Hither is an example of "success" — the notification_key
has 3 registration tokens associated with information technology, and the message was successfully sent to all of them:
{ "from": "aUniqueKey", "message_type": "ack", "success": 3, "failure": 0, "message_id": "m-1366082849205" }
Here is an example of "partial success" — the notification_key
has iii registration tokens associated with it. The message was successfully sent to 1 of the registration tokens merely. The response bulletin lists the registration tokens that failed to receive the message:
{ "from": "aUniqueKey", "message_type": "ack", "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
When FCM connexion server fails to deliver to all devices in the grouping. App server volition receive a nack response.
For the total listing of message options, see the reference information for your chosen connection server protocol, HTTP or XMPP.
Firebase Admin SDK legacy send methods
The Firebase Admin Node.js SDK supports methods for sending (FCM) messages based on the Legacy FCM server API. These methods take different arguments compared to the transport()
method. You should utilize the send()
method whenever possible, and only use the methods described in this folio when sending messages to individual devices or device groups.
Send to individual devices
You tin can pass a registration token to the sendToDevice()
method to send a message to that device:
Node.js
// This registration token comes from the customer FCM SDKs. const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'; // See the "Defining the message payload" section below for details // on how to define a message payload. const payload = { data: { score: '850', time: '2:45' } }; // Ship a message to the device corresponding to the provided // registration token. getMessaging().sendToDevice(registrationToken, payload) .so((response) => { // Run into the MessagingDevicesResponse reference documentation for // the contents of response. console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Mistake sending message:', error); });
The sendToDevice()
method tin can too send a multicast bulletin (that is, a message to multiple devices) by passing an array of registration tokens instead of simply a single registration token:
Node.js
// These registration tokens come from the client FCM SDKs. const registrationTokens = [ 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...', // ... 'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...' ]; // See the "Defining the bulletin payload" section below for details // on how to define a message payload. const payload = { data: { score: '850', time: '2:45' } }; // Send a bulletin to the devices corresponding to the provided // registration tokens. getMessaging().sendToDevice(registrationTokens, payload) .then((response) => { // See the MessagingDevicesResponse reference documentation for // the contents of response. panel.log('Successfully sent bulletin:', response); }) .grab((error) => { panel.log('Fault sending message:', mistake); });
The sendToDevice()
method returns a promise that is resolved with a MessagingDevicesResponse
object containing the response from FCM. The return blazon has the aforementioned format when passing a unmarried registration token or an array of registration tokens.
Some cases such as an authentication mistake 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 mistake. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.
Send to a device grouping
Device group messaging allows you to add together multiple devices to a single group. This is similar to topic messaging, merely includes authentication to ensure that group membership is managed only by your servers. For instance, if yous want to transport different letters to unlike phone models, your servers can add/remove registrations to the appropriate groups and send the appropriate message to each group. Device grouping messaging differs from topic messaging in that information technology involves managing device groups from your servers instead of directly within your application.
Y'all tin use device group messaging via the legacy XMPP or HTTP protocols on your app server. Older versions of the Firebase Admin SDK for Node.js are based on the legacy protocols and also provide device group messaging capabilities. The maximum number of members allowed for a notification key is 20.
You lot 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 grouping by specifying the notification key for that device grouping:
Node.js
// See the "Managing device groups" link above on how to generate a // notification key. const notificationKey = 'some-notification-key'; // See the "Defining the message payload" section beneath for details // on how to define a message payload. const payload = { data: { score: '850', time: '2:45' } }; // Transport a message to the device group corresponding to the provided // notification central. getMessaging().sendToDeviceGroup(notificationKey, payload) .and then((response) => { // See the MessagingDeviceGroupResponse reference documentation for // the contents of response. panel.log('Successfully sent bulletin:', response); }) .catch((fault) => { console.log('Error sending message:', error); });
The sendToDeviceGroup()
method returns a promise that is resolved with a MessagingDevicesResponse
object containing the response from FCM.
Some cases such as an hallmark fault 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 mistake. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.
Defining the message payload
The above methods based on the FCM legacy protocols take a bulletin payload as their 2d argument and support both notification and information messages. You tin specify one or both bulletin types past creating an object with the data
and / or notification
keys. For instance, here is how to define different types of bulletin payloads:
Notification message
const payload = { notification: { championship: '$FooCorp up 1.43% on the twenty-four hours', torso: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the mean solar day.' } };
Data message
const payload = { data: { score: '850', fourth dimension: 'ii:45' } };
Combined message
const payload = { notification: { championship: '$FooCorp upwardly 1.43% on the twenty-four hours', body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.' }, information: { 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 lot are targeting. Encounter 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. Come across the reference docs for DataMessagePayload
for a total list of restrictions.
Defining the message options
The above methods based on the FCM legacy protocols accept an optional tertiary argument specifying some options for the message. For example, the post-obit 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. const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'; // See the "Defining the message payload" section above for details // on how to define a message payload. const payload = { notification: { championship: 'Urgent action needed!', body: 'Urgent action is needed to forestall your account from being disabled!' } }; // Gear up the message as high priority and have information technology expire after 24 hours. const options = { priority: 'loftier', timeToLive: 60 * 60 * 24 }; // Ship a message to the device corresponding to the provided // registration token with the provided options. getMessaging().sendToDevice(registrationToken, payload, options) .then((response) => { console.log('Successfully sent bulletin:', response); }) .catch((error) => { panel.log('Fault sending message:', mistake); });
Run into the reference docs for MessagingOptions
for a total list of available options.
How To Display Error Pop Up After Receive Data From Backend,
Source: https://firebase.google.com/docs/cloud-messaging/send-message
Posted by: fettermanfatabimpar1961.blogspot.com
0 Response to "How To Display Error Pop Up After Receive Data From Backend"
Post a Comment