Mem-build permintaan kirim server aplikasi

Dengan protokol server aplikasi FCM atau Firebase Admin SDK, Anda dapat membangun permintaan pesan dan mengirimkannya ke jenis target berikut:

  • Nama topik
  • Kondisi
  • Token pendaftaran perangkat
  • Nama grup perangkat (hanya untuk protokol lama dan Firebase Admin SDK untuk Node.js)

Anda dapat mengirim pesan dengan payload notifikasi yang terdiri atas kolom yang telah ditentukan, payload data untuk kolom yang ditentukan oleh pengguna, atau pesan yang berisi kedua jenis payload. Lihat Jenis pesan untuk mengetahui informasi selengkapnya.

Contoh di halaman ini menunjukkan cara mengirim pesan notifikasi menggunakan Firebase Admin SDK (yang memiliki dukungan untuk Node, Java, Python, C#, dan Go) dan protokol HTTP v1. Ada juga panduan untuk mengirim pesan melalui protokol HTTP dan XMPP versi lama.

Mengirim pesan ke perangkat tertentu

Untuk mengirim ke satu perangkat tertentu, teruskan token pendaftaran perangkat seperti yang ditunjukkan. Baca informasi penyiapan klien untuk platform Anda guna mempelajari token pendaftaran lebih lanjut.

Node.js

// This registration token comes from the client FCM SDKs.
const registrationToken = 'YOUR_REGISTRATION_TOKEN';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

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);

Python

# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    token=registration_token,
)

# Send 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)

Go

// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
	log.Fatalf("error getting Messaging client: %v\n", err)
}

// This registration token comes from the client FCM SDKs.
registrationToken := "YOUR_REGISTRATION_TOKEN"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Token: registrationToken,
}

// Send a message to the device corresponding to the provided
// registration token.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// This registration token comes from the client FCM SDKs.
var registrationToken = "YOUR_REGISTRATION_TOKEN";

// See documentation on defining a message 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.
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/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
   "message":{
      "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
      "notification":{
        "body":"This is an FCM notification message!",
        "title":"FCM Message"
      }
   }
}

Perintah cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
   "notification":{
     "title":"FCM Message",
     "body":"This is an FCM Message"
   },
   "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

Setelah berhasil, setiap metode pengiriman akan menampilkan ID pesan. Firebase Admin SDK menampilkan string ID dalam format projects/{project_id}/messages/{message_id}. Respons protokol HTTP adalah kunci JSON tunggal:

    {
      "name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
    }

Mengirim pesan ke beberapa perangkat

Dengan REST API dan Admin FCM API, Anda dapat mengirim pesan multicast ke beberapa token pendaftaran perangkat. Anda dapat menentukan hingga 500 token pendaftaran perangkat per pemanggilan.

Node.js

// Create a list 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 message = {
  data: {score: '850', time: '2:45'},
  tokens: registrationTokens,
};

getMessaging().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Java

// Create a list containing up to 500 registration tokens.
// These registration tokens come 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("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");

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': '2: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))

Go

// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Tokens: registrationTokens,
}

br, err := client.SendMulticast(context.Background(), message)
if err != nil {
	log.Fatalln(err)
}

// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)

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 Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
};

var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

REST

Buat permintaan batch HTTP:

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message!"
     }
  }
}

...

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message!"
     }
  }
}
--subrequest_boundary--

Simpan permintaan ke dalam file (dalam contoh ini batch_request.txt). Lalu gunakan perintah cURL:

curl --data-binary @batch_request.txt -H 'Content-Type: multipart/mixed; boundary="subrequest_boundary"' -H 'Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA' https://fcm.googleapis.com/batch

Pada prinsipnya, operasi ini menggunakan sendAll() API untuk Firebase Admin SDK, seperti yang ditunjukkan dalam contoh. Nilai yang ditampilkan adalah BatchResponse yang daftar responsnya sesuai dengan urutan token input. Hal ini berguna ketika Anda ingin memeriksa token mana yang menghasilkan error.

Node.js

// These registration tokens come from the client 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(registrationTokens[idx]);
        }
      });
      console.log('List of tokens that caused failures: ' + failedTokens);
    }
  });

Java

// These registration tokens come 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("time", "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.get(i).isSuccessful()) {
      // The order of responses corresponds to the order of the registration tokens.
      failedTokens.add(registrationTokens.get(i));
    }
  }

  System.out.println("List of tokens that caused failures: " + failedTokens);
}

Python

# 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': '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 caused failures: {0}'.format(failed_tokens))

Go

// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
	Data: map[string]string{
		"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 order of the registration tokens.
			failedTokens = append(failedTokens, registrationTokens[idx])
		}
	}

	fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}

C#

// 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 Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
};

var response = await 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 order of the registration tokens.
            failedTokens.Add(registrationTokens[i]);
        }
    }

    Console.WriteLine($"List of tokens that caused failures: {failedTokens}");
}

REST

Setiap subpengiriman pengiriman menampilkan respons. Respons dipisahkan dengan string batas respons yang dimulai dengan --batch_.

--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q
Content-Type: application/http
Content-ID: response-

HTTP/1.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-Type: application/http
Content-ID: response-

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Vary: Origin
Vary: X-Origin
Vary: Referer

{
  "name": "projects/35006771263/messages/0:1570471792141696%43c11b7043c11b70"
}

--batch_nDhMX4IzFTDLsCJ3kHH7v_44ua-aJT6q--

Mengirim pesan ke topik

Setelah membuat topik, baik dengan membuat instance aplikasi klien berlangganan topik di sisi klien maupun melalui API server, Anda dapat mengirim pesan ke topik tersebut. Jika ini adalah pertama kalinya Anda membangun permintaan kirim untuk FCM, baca panduan lingkungan server dan FCM guna mengetahui informasi penting tentang penyiapan dan latar belakang.

Dalam logika pengiriman Anda di backend, tentukan nama topik yang diinginkan seperti yang ditunjukkan di bawah:

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send 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((error) => {
    console.log('Error sending message:', error);
  });

Java

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// The topic name 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":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// The topic name 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", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
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/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

Perintah cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Untuk mengirim pesan ke kombinasi topik, tentukan kondisi, yang merupakan ekspresi boolean yang menentukan topik target. Misalnya, kondisi berikut akan mengirim pesan ke perangkat yang berlangganan TopicA dan juga TopicB atau TopicC:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM mengevaluasi terlebih dahulu setiap kondisi di dalam tanda kurung, lalu mengevaluasi ekspresi dari kiri ke kanan. Pada ekspresi di atas, pengguna yang hanya berlangganan satu topik apa pun tidak akan menerima pesan. Demikian pula, pengguna yang tidak berlangganan TopicA tidak akan menerima pesan. Namun, pengguna dengan kombinasi berikut akan menerimanya:

  • TopicA dan TopicB
  • TopicA dan TopicC

Anda dapat menyertakan hingga lima topik dalam ekspresi kondisional.

Untuk mengirim ke sebuah kondisi:

Node.js

// Define a condition which will send 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';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close 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.
getMessaging().send(message)
  .then((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.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 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 message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# Define a condition 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(
    notification=messaging.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.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// Define a condition 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{
	Data: map[string]string{
		"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, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new 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.",
    },
    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/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

Perintah cURL:

curl -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!",
  },
  "condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Mengirim pesan dalam batch

REST API dan Admin SDK mendukung pengiriman pesan dalam batch. Anda dapat mengelompokkan hingga 500 pesan ke dalam satu batch dan mengirim semuanya dalam satu panggilan API. Dengan demikian, akan terjadi peningkatan performa yang signifikan dibandingkan dengan pengiriman permintaan HTTP yang terpisah untuk setiap pesan.

Fitur ini dapat digunakan untuk membangun satu set pesan yang disesuaikan dan mengirimkannya ke penerima yang berbeda, termasuk topik atau token pendaftaran perangkat tertentu. Gunakan fitur ini ketika, misalnya, Anda perlu mengirim pesan secara bersamaan ke audience yang berbeda dengan detail yang sedikit berbeda di isi pesan.

Node.js

// Create a list containing up to 500 messages.
const messages = [];
messages.push({
  notification: { title: 'Price drop', body: '5% off all electronics' },
  token: registrationToken,
});
messages.push({
  notification: { title: 'Price drop', body: '2% off all books' },
  topic: 'readers-club',
});

getMessaging().sendAll(messages)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Java

// Create a list containing up to 500 messages.
List<Message> messages = Arrays.asList(
    Message.builder()
        .setNotification(Notification.builder()
            .setTitle("Price drop")
            .setBody("5% off all electronics")
            .build())
        .setToken(registrationToken)
        .build(),
    // ...
    Message.builder()
        .setNotification(Notification.builder()
            .setTitle("Price drop")
            .setBody("2% off all books")
            .build())
        .setTopic("readers-club")
        .build()
);

BatchResponse response = FirebaseMessaging.getInstance().sendAll(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");

Python

# Create a list containing up to 500 messages.
messages = [
    messaging.Message(
        notification=messaging.Notification('Price drop', '5% off all electronics'),
        token=registration_token,
    ),
    # ...
    messaging.Message(
        notification=messaging.Notification('Price drop', '2% off all books'),
        topic='readers-club',
    ),
]

response = messaging.send_all(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

Go

// Create a list containing up to 500 messages.
messages := []*messaging.Message{
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "5% off all electronics",
		},
		Token: registrationToken,
	},
	{
		Notification: &messaging.Notification{
			Title: "Price drop",
			Body:  "2% off all books",
		},
		Topic: "readers-club",
	},
}

br, err := client.SendAll(context.Background(), messages)
if err != nil {
	log.Fatalln(err)
}

// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)

C#

// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
    new Message()
    {
        Notification = new Notification()
        {
            Title = "Price drop",
            Body = "5% off all electronics",
        },
        Token = registrationToken,
    },
    new Message()
    {
        Notification = new Notification()
        {
            Title = "Price drop",
            Body = "2% off all books",
        },
        Topic = "readers-club",
    },
};

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");

REST

Buat permintaan batch HTTP dengan menggabungkan daftar subpermintaan:

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message to device 0!"
     }
  }
}

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "topic":"readers-club",
     "notification":{
       "title":"Price drop",
       "body":"2% off all books"
     }
  }
}

...

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary

POST /v1/projects/myproject-b5ae1/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "token":"cR1rjyj4_Kc:APA91bGusqbypSuMdsh7jSNrW4nzsM...",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message to device N!"
     }
  }
}
--subrequest_boundary--

Anda dapat membuat kueri untuk BatchResponse yang ditampilkan guna memeriksa berapa banyak pesan yang telah berhasil diteruskan ke FCM. BatchResponse juga menampilkan daftar respons yang dapat digunakan untuk memeriksa status setiap pesan. Urutan respons sesuai dengan urutan pesan dalam daftar input.

Mengirim pesan dalam mode booting langsung (hanya Android)

Anda dapat mengirim pesan ke perangkat dalam mode booting langsung menggunakan HTTP v1 API atau HTTP API lama. Sebelum mengirim ke perangkat dalam mode booting langsung, pastikan Anda telah menyelesaikan langkah-langkah untuk memungkinkan perangkat klien menerima pesan FCM dalam mode booting langsung.

Mengirim menggunakan HTTP v1 API FCM

Permintaan pesan harus menyertakan kunci "direct_boot_ok" : true dalam opsi AndroidConfig dari isi permintaan. Contoh:

https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
Content-Type:application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
    "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "android": {
      "direct_boot_ok": true,
    },
}

Mengirim menggunakan HTTP API lama FCM

Permintaan pesan harus menyertakan kunci "direct_boot_ok" : true pada level teratas isi permintaan. Contoh:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  "direct_boot_ok" : true
}

Pesan yang dikirim dengan kunci ini dalam isi permintaan dapat ditangani oleh aplikasi di perangkat yang saat ini berada dalam mode booting langsung (dan juga saat tidak berada dalam mode tersebut).

Menyesuaikan pesan untuk berbagai platform

Melalui Firebase Admin SDK dan protokol HTTP v1 FCM, permintaan pesan Anda dapat menetapkan semua kolom yang tersedia di objek message. Hal ini mencakup:

  • sekumpulan kolom umum untuk ditafsirkan oleh semua instance aplikasi yang menerima pesan tersebut.
  • kumpulan kolom khusus platform, seperti AndroidConfig dan WebpushConfig, yang hanya ditafsirkan oleh instance aplikasi yang berjalan pada platform yang ditentukan.

Blok khusus platform memberi Anda fleksibilitas dalam menyesuaikan pesan untuk berbagai platform, guna memastikan pesan ditangani dengan benar saat diterima. Backend FCM akan mempertimbangkan semua parameter yang telah ditentukan dan menyesuaikan pesan untuk setiap platform.

Kapan kolom umum digunakan

Gunakan kolom umum saat Anda:

  • Menarget instance aplikasi di semua platform, baik Apple, Android, maupun web
  • Mengirim pesan ke topik

Semua instance aplikasi, dari platform apa saja, dapat menafsirkan kolom umum berikut:

Kapan kolom khusus platform digunakan

Gunakan kolom khusus platform ketika Anda ingin:

  • Mengirim kolom hanya ke platform tertentu
  • Mengirim kolom khusus platform bersama dengan kolom umum

Kapan pun Anda ingin mengirim nilai ke platform tertentu saja, jangan gunakan kolom umum; gunakan kolom khusus platform. Misalnya, untuk mengirim notifikasi ke platform Apple dan web saja, tetapi tidak ke Android, Anda harus menggunakan dua kumpulan kolom terpisah, yaitu satu untuk Apple dan satu lagi untuk web.

Saat Anda mengirim pesan dengan opsi pengiriman tertentu, gunakan kolom khusus platform untuk menetapkannya. Anda dapat menentukan beragam nilai untuk setiap platform jika mau. Namun, meskipun Anda ingin menetapkan nilai yang sama pada platform yang berbeda, Anda harus menggunakan kolom khusus platform. Alasannya, setiap platform mungkin menafsirkan nilai dengan sedikit berbeda. Misalnya, waktu aktif ditetapkan di Android sebagai waktu habis masa berlaku dalam hitungan detik, sedangkan di Apple ditetapkan sebagai tanggal habis masa berlaku.

Contoh: pesan notifikasi dengan opsi warna dan ikon

Contoh permintaan kirim berikut mengirimkan judul dan isi notifikasi yang sama ke semua platform, tetapi juga mengirim beberapa penggantian khusus platform ke perangkat Android.

Untuk Android, permintaan menetapkan ikon dan warna khusus untuk ditampilkan di perangkat Android. Seperti tercantum dalam referensi untuk AndroidNotification, warna ditentukan dalam format #rrggbb, dan gambar harus merupakan resource ikon drawable yang tersedia secara lokal untuk aplikasi Android.

Berikut adalah perkiraan efek visual pada perangkat pengguna:

Gambar sederhana dua perangkat, yang satu menampilkan ikon dan warna khusus

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: '`$FooCorp` up 1.43% on the day',
    body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close 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.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

message = messaging.Message(
    notification=messaging.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.',
    ),
    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(badge=42),
        ),
    ),
    topic='industry-tech',
)

Go

oneHour := time.Duration(1) * time.Hour
badge := 42
message := &messaging.Message{
	Notification: &messaging.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.",
	},
	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",
}

C#

var message = new Message
{
    Notification = new 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.",
    },
    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",
};

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"`$FooCorp` up 1.43% on the day",
       "body":"FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

Baca dokumentasi referensi HTTP v1 untuk mengetahui detail lengkap tentang kunci yang tersedia di blok khusus platform dalam isi pesan.

Contoh: pesan notifikasi dengan gambar kustom

Contoh permintaan kirim berikut tidak hanya mengirimkan judul notifikasi yang sama ke semua platform, tetapi juga mengirimkan gambar. Berikut adalah perkiraan efek visual pada perangkat pengguna:

Ilustrasi sederhana dari gambar dalam notifikasi tampilan

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Sparky says hello!'
  },
  android: {
    notification: {
      imageUrl: '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'
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "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"
       }
     }
   }
 }

Baca dokumentasi referensi HTTP v1 untuk mengetahui detail lengkap tentang kunci yang tersedia di blok khusus platform dalam isi pesan.

Contoh: pesan notifikasi dengan tindakan klik terkait

Contoh permintaan kirim berikut mengirimkan judul notifikasi yang sama ke semua platform, tetapi juga mengirimkan tindakan untuk dilakukan aplikasi sebagai respons terhadap interaksi pengguna dengan notifikasi tersebut. Berikut adalah perkiraan efek visual pada perangkat pengguna:

Gambar sederhana yang menunjukkan pengguna mengetuk untuk membuka halaman web

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 string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: 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"
       }
     }
   }
 }

Baca dokumentasi referensi HTTP v1 untuk mengetahui detail lengkap tentang kunci yang tersedia di blok khusus platform dalam isi pesan.

Contoh: pesan notifikasi dengan opsi pelokalan

Contoh permintaan kirim berikut mengirimkan opsi pelokalan agar klien menampilkan pesan yang dilokalkan. Berikut adalah perkiraan efek visual pada perangkat pengguna:

Gambar sederhana dua perangkat yang menampilkan teks dalam bahasa Inggris dan Spanyol

Node.js

var topicName = 'industry-tech';

var message = {
  android: {
    ttl: 3600000,
    notification: {
      bodyLocKey: 'STOCK_NOTIFICATION_BODY',
      bodyLocArgs: ['FooCorp', '11.80', '835.67', '1.43']
    }
  },
  apns: {
    payload: {
      aps: {
        alert: {
          locKey: 'STOCK_NOTIFICATION_BODY',
          locArgs: ['FooCorp', '11.80', '835.67', '1.43']
        }
      }
    }
  },
  topic: topicName,
};

getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
             "topic":"Tech",
             "android":{
               "ttl":"3600s",
               "notification":{
                 "body_loc_key": "STOCK_NOTIFICATION_BODY",
                 "body_loc_args":  ["FooCorp", "11.80", "835.67", "1.43"],
               },
             },
             "apns":{
               "payload":{
                 "aps":{
                   "alert" : {
                     "loc-key": "STOCK_NOTIFICATION_BODY",
                     "loc-args":  ["FooCorp", "11.80", "835.67", "1.43"],
                    },
                 },
               },
             },
  },
}'

Baca dokumentasi referensi HTTP v1 untuk mengetahui detail lengkap tentang kunci yang tersedia di blok khusus platform dalam isi pesan.

Kode error admin

Tabel berikut berisi kode error Firebase Admin FCM API beserta deskripsinya, termasuk langkah-langkah penyelesaian yang direkomendasikan.

Kode Error Deskripsi dan Langkah Penyelesaian
messaging/invalid-argument Argumen yang tidak valid diberikan ke metode FCM. Di dalam pesan error akan ada informasi tambahan.
messaging/invalid-recipient Penerima pesan yang dimaksud tidak valid. Di dalam pesan error akan ada informasi tambahan.
messaging/invalid-payload Diberikan objek payload pesan yang tidak valid. Di dalam pesan error akan ada informasi tambahan.
messaging/invalid-data-payload-key Payload pesan data berisi kunci yang tidak valid. Baca dokumentasi referensi DataMessagePayload untuk kunci yang dibatasi.
messaging/payload-size-limit-exceeded Payload pesan yang diberikan melebihi batas ukuran FCM. Batasnya adalah 4.096 byte untuk kebanyakan pesan. Untuk pesan yang dikirim ke topik, batasnya adalah 2.048 byte. Ukuran total payload mencakup kunci sekaligus nilai.
messaging/invalid-options Diberikan objek opsi pesan yang tidak valid. Di dalam pesan error akan ada informasi tambahan.
messaging/invalid-registration-token Diberikan token pendaftaran yang tidak valid. Pastikan token tersebut sama dengan token pendaftaran yang diterima aplikasi klien ketika mendaftar ke FCM. Jangan memotong atau menambahkan karakter lain ke token.
messaging/registration-token-not-registered Token pendaftaran yang diberikan tidak terdaftar. Token pendaftaran yang sebelumnya valid dapat dibatalkan pendaftarannya karena berbagai alasan, termasuk:
  • Aplikasi klien membatalkan pendaftarannya sendiri dari FCM.
  • Aplikasi klien otomatis dibatalkan pendaftarannya. Ini dapat terjadi jika pengguna meng-uninstal aplikasi atau, di platform Apple, saat APNs Feedback Service melaporkan bahwa token APNs tidak valid.
  • Masa berlaku token pendaftaran habis. Misalnya, Google mungkin memutuskan untuk memperbarui token pendaftaran, atau token APNs untuk perangkat Apple mungkin telah habis masa berlakunya.
  • Aplikasi klien sudah diupdate, tetapi versi yang baru belum dikonfigurasi untuk menerima pesan.
Untuk semua kasus tersebut, hapus token pendaftaran ini dan jangan gunakan lagi untuk mengirim pesan.
messaging/invalid-package-name Pesan ditujukan ke token pendaftaran yang nama paketnya tidak cocok dengan opsi restrictedPackageName yang disediakan.
messaging/message-rate-exceeded Tingkat pengiriman pesan ke target tertentu terlalu tinggi. Kurangi jumlah pesan yang dikirim ke perangkat atau topik ini, dan jangan langsung mencoba mengirimkan pesan lagi ke target ini.
messaging/device-message-rate-exceeded Tingkat pengiriman pesan ke perangkat tertentu terlalu tinggi. Kurangi jumlah pesan yang dikirim ke perangkat ini dan jangan langsung mencoba mengirimkan pesan lagi ke perangkat ini.
messaging/topics-message-rate-exceeded Tingkat pengiriman pesan ke pelanggan topik tertentu terlalu tinggi. Kurangi jumlah pesan yang dikirim ke topik ini dan jangan langsung mencoba mengirimkan pesan lagi ke topik ini.
messaging/too-many-topics Token pendaftaran telah berlangganan jumlah maksimum topik sehingga tidak dapat lagi berlangganan topik lainnya.
messaging/invalid-apns-credentials Pesan yang ditargetkan ke perangkat Apple tidak bisa dikirim karena sertifikat SSL APNs yang diperlukan tidak diupload atau tidak berlaku lagi. Periksa validitas sertifikat pengembangan dan produksi Anda.
messaging/mismatched-credential Kredensial yang digunakan untuk mengautentikasi SDK ini tidak memiliki izin untuk mengirim pesan ke perangkat yang terkait dengan token pendaftaran yang diberikan. Pastikan kredensial dan token pendaftaran tercakup dalam project Firebase yang sama. Baca artikel Menambahkan Firebase ke aplikasi Anda untuk mempelajari dokumentasi mengenai cara mengautentikasi Firebase Admin SDK.
messaging/authentication-error SDK tidak dapat melakukan autentikasi ke server FCM. Pastikan Anda mengautentikasi Firebase Admin SDK dengan kredensial yang memiliki izin yang tepat untuk mengirim pesan FCM. Baca artikel Menambahkan Firebase ke aplikasi Anda untuk mempelajari dokumentasi mengenai cara mengautentikasi Firebase Admin SDK.
messaging/server-unavailable Server FCM tidak dapat memproses permintaan secara tepat waktu. Coba lagi permintaan yang sama, tetapi Anda harus:
  • Mematuhi header Retry-After jika dimasukkan dalam respons dari Server Koneksi FCM.
  • Menerapkan back-off eksponensial dalam mekanisme percobaan ulang. Misalnya, jika Anda menunggu satu detik sebelum percobaan ulang pertama, tunggulah minimal dua detik sebelum percobaan ulang berikutnya, lalu empat detik dan seterusnya. Jika Anda mengirim beberapa pesan, tunda setiap pesan secara independen dengan jumlah acak tambahan agar tidak mengeluarkan permintaan baru untuk semua pesan secara bersamaan.
Pengirim yang menyebabkan masalah berisiko dimasukkan ke daftar hitam.
messaging/internal-error Server FCM mengalami error ketika mencoba memproses permintaan. Anda bisa mencoba lagi permintaan yang sama sesuai persyaratan yang tercantum pada baris messaging/server-unavailable di atas. Jika error tetap berlanjut, harap laporkan masalah ke saluran dukungan Laporan Bug kami.
messaging/unknown-error Ditampilkan error server yang tidak diketahui. Lihat respons server mentah pada pesan error untuk lebih jelasnya. Jika Anda menerima error ini, harap laporkan pesan error lengkap ke saluran dukungan Laporan Bug kami.

Mengirim pesan menggunakan protokol server aplikasi versi lama

Jika lebih suka menggunakan protokol lama, bangun permintaan pesan seperti ditunjukkan dalam bagian ini. Perlu diingat bahwa jika Anda mengirim ke beberapa platform melalui HTTP, protokol v1 dapat menyederhanakan permintaan pesan Anda.

Mengirim pesan ke perangkat tertentu

Untuk mengirim pesan ke perangkat tertentu, setel kunci to ke token pendaftaran untuk instance aplikasi tertentu. Baca informasi penyiapan klien untuk platform Anda guna mempelajari token pendaftaran lebih lanjut.

Permintaan POST HTTP

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

Respons HTTP

{ "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}

Pesan XMPP

<message id="">
  <gcm xmlns="google:mobile:data">
    { "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  }
  </gcm>
</message>

Respons XMPP

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "from":"REGID",
      "message_id":"m-1366082849205"
      "message_type":"ack"
  }
  </gcm>
</message>

Server koneksi XMPP menyediakan beberapa opsi lain untuk respons. Lihat Format respons server.

Untuk mengetahui daftar lengkap opsi pesan yang tersedia saat mengirim pesan downstream ke aplikasi klien, baca informasi referensi untuk protokol server koneksi pilihan Anda, HTTP atau XMPP.

Mengirim pesan ke topik

Mengirim pesan ke topik Firebase Cloud Messaging serupa dengan mengirim pesan ke satu perangkat atau ke grup pengguna. Server aplikasi menetapkan kunci to dengan nilai seperti /topics/yourTopic. Developer dapat memilih nama topik yang cocok dengan ekspresi reguler: "/topics/[a-zA-Z0-9-_.~%]+".

Untuk mengirim ke kombinasi beberapa topik, server aplikasi harus menyetel kunci condition (bukan kunci to) ke kondisi boolean yang menentukan topik target. Misalnya, untuk mengirim pesan ke perangkat yang berlangganan TopicA dan salah satu dari TopicB atau TopicC:

'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)

FCM mengevaluasi terlebih dahulu setiap kondisi di dalam tanda kurung, lalu mengevaluasi ekspresi dari kiri ke kanan. Pada ekspresi di atas, pengguna yang hanya berlangganan satu topik apa pun tidak akan menerima pesan. Demikian pula, pengguna yang tidak berlangganan TopicA tidak akan menerima pesan. Namun, pengguna dengan kombinasi berikut akan menerimanya:

  • TopicA dan TopicB
  • TopicA dan TopicC

Anda dapat menyertakan hingga lima topik dalam ekspresi kondisional. Penggunaan tanda kurung didukung. Operator yang didukung: &&, ||.

Permintaan POST HTTP topik

Mengirim ke satu topik:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

Mengirim ke perangkat yang berlangganan topik "dogs" atau "cats":

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

Respons HTTP topik

//Success example:
{
  "message_id": "1023456"
}

//failure example:
{
  "error": "TopicsMessageRateExceeded"
}

Pesan XMPP topik

Mengirim ke satu topik:

<message id="">
  <gcm xmlns="google:mobile:data">

  </gcm>
</message>

Mengirim ke perangkat yang berlangganan topik "dogs" atau "cats":

<message id="">
  <gcm xmlns="google:mobile:data">

  </gcm>
</message>

Respons XMPP topik

//Success example:
{
  "message_id": "1023456"
}

//failure example:
{
  "error": "TopicsMessageRateExceeded"
}

Perkirakan penundaan hingga 30 detik sebelum Server FCM menampilkan respons berhasil atau gagal untuk permintaan pengiriman topik. Karena itu, pastikan menyetel nilai waktu tunggu server aplikasi pada permintaan.

Mengirim pesan ke grup perangkat

Mengirim pesan ke grup perangkat sangat mirip dengan mengirim pesan ke satu perangkat. Setel parameter to ke kunci notifikasi unik untuk grup perangkat. Baca bagian Jenis pesan untuk mengetahui detail tentang dukungan payload. Contoh di halaman ini menunjukkan cara mengirimkan pesan data ke grup perangkat pada protokol HTTP dan XMPP lama.

Permintaan POST HTTP Grup Perangkat

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "aUniqueKey",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!",
   }
}

Respons HTTP Grup Perangkat

Berikut contoh "berhasil" — notification_key memiliki 2 token pendaftaran yang terkait dengannya dan pesan berhasil dikirim ke keduanya:

{
  "success": 2,
  "failure": 0
}

Berikut contoh "berhasil sebagian" — notification_key memiliki 3 token pendaftaran yang terkait dengannya. Pesan hanya berhasil dikirim ke 1 token pendaftaran. Pesan respons mencantumkan token pendaftaran (registration_ids) yang gagal menerima pesan:

{
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

Jika pesan gagal dikirim ke satu atau beberapa token pendaftaran yang terkait dengan notification_key, server aplikasi harus mencoba lagi dengan backoff di antara percobaan ulang.

Jika server mencoba mengirim pesan ke grup perangkat yang tidak memiliki anggota, responsnya akan terlihat seperti berikut, dengan 0 keberhasilan dan 0 kegagalan:

{
  "success": 0,
  "failure": 0
}

Pesan XMPP Grup Perangkat

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to": "aUniqueKey",
      "message_id": "m-1366082849205" ,
      "data": {
          "hello":"This is a Firebase Cloud Messaging Device Group Message!"
      }
  }
  </gcm>
</message>

Respons XMPP Grup Perangkat

Jika pesan berhasil dikirim ke salah satu perangkat dalam grup, server koneksi XMPP akan merespons dengan ACK. Jika semua pesan gagal dikirim ke semua perangkat dalam grup, server koneksi XMPP akan merespons dengan NACK.

Berikut contoh "berhasil" — notification_key memiliki 3 token pendaftaran yang terkait dengannya dan pesan berhasil dikirim ke ketiganya:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success": 3,
  "failure": 0,
  "message_id": "m-1366082849205"
}

Berikut contoh "berhasil sebagian" — notification_key memiliki 3 token pendaftaran yang terkait dengannya. Pesan hanya berhasil dikirim ke 1 token pendaftaran. Pesan respons mencantumkan token pendaftaran yang gagal menerima pesan:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

Jika server koneksi FCM gagal mengirim ke semua perangkat dalam grup, server aplikasi akan menerima respons NACK.

Untuk mengetahui daftar lengkap opsi pesan, lihat informasi referensi untuk protokol server koneksi pilihan Anda, HTTP atau XMPP.

Metode pengiriman lama Firebase Admin SDK

Firebase Admin Node.js SDK mendukung metode pengiriman pesan (FCM) berdasarkan API server FCM lama. Metode ini menerima argumen yang berbeda dibandingkan dengan metode send(). Anda harus menggunakan metode send() jika memungkinkan, dan hanya menggunakan metode yang dijelaskan di halaman ini saat mengirim pesan ke perangkat individual atau ke grup perangkat.

Mengirim ke perangkat individual

Anda dapat meneruskan token pendaftaran ke metode sendToDevice() untuk mengirim pesan ke perangkat tersebut:

Node.js

// This registration token comes from the client 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'
  }
};

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

Metode sendToDevice() juga dapat mengirim pesan multicast (yaitu, pesan ke beberapa perangkat) dengan meneruskan array token pendaftaran, bukan hanya satu token pendaftaran:

Node.js

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

// 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'
  }
};

// Send a message 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.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Metode sendToDevice() menampilkan promise yang diselesaikan dengan objek MessagingDevicesResponse yang berisi respons dari FCM. Jenis nilai yang ditampilkan memiliki format yang sama, baik ketika meneruskan satu token pendaftaran maupun array token pendaftaran.

Beberapa kasus, seperti error autentikasi atau pembatasan kapasitas, menyebabkan seluruh pesan gagal diproses. Dalam kasus ini, promise yang ditampilkan oleh sendToDevice() ditolak dengan error. Untuk mengetahui daftar lengkap kode error, termasuk deskripsi dan langkah-langkah penyelesaiannya, baca bagian Error pada Admin FCM API.

Mengirim ke grup perangkat

Dengan pengiriman pesan ke grup perangkat, Anda dapat menambahkan beberapa perangkat ke satu grup. Kemampuan ini mirip dengan pengiriman pesan menurut topik, tetapi yang ini mencakup autentikasi untuk memastikan bahwa keanggotaan grup hanya dikelola oleh server Anda. Misalnya, jika Anda ingin mengirim berbagai pesan ke model ponsel berbeda, server Anda dapat menambahkan/menghapus pendaftaran ke grup yang sesuai dan mengirim pesan yang sesuai ke setiap grup. Pengiriman pesan ke grup perangkat berbeda dengan pengiriman pesan menurut topik karena grup perangkat dikelola dari server Anda, bukan langsung di aplikasi.

Anda dapat menggunakan pengiriman pesan ke grup perangkat melalui protokol XMPP atau HTTP lama pada server aplikasi. Versi lama Firebase Admin SDK untuk Node.js didasarkan pada protokol lama. Versi ini juga dapat melakukan pengiriman pesan ke grup perangkat. Jumlah anggota maksimum yang diizinkan untuk kunci notifikasi adalah 20.

Anda dapat membuat grup perangkat dan membuat kunci notifikasi lewat server aplikasi atau klien Android. Baca bagian Mengelola grup perangkat untuk mengetahui detailnya.

Metode sendToDeviceGroup() memungkinkan Anda mengirim pesan ke grup perangkat dengan menentukan kunci notifikasi untuk grup perangkat tersebut:

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 below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

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

Metode sendToDeviceGroup() menampilkan promise yang diselesaikan dengan objek MessagingDevicesResponse yang berisi respons dari FCM.

Beberapa kasus, seperti error autentikasi atau pembatasan kapasitas, menyebabkan seluruh pesan gagal diproses. Dalam kasus ini, promise yang ditampilkan oleh sendToDeviceGroup() ditolak dengan error. Untuk mengetahui daftar lengkap kode error, termasuk deskripsi dan langkah-langkah penyelesaiannya, baca bagian Error pada Admin FCM API.

Menetapkan payload pesan

Metode berdasarkan protokol lama FCM di atas menerima payload pesan sebagai argumen kedua dan mendukung pesan notifikasi dan juga pesan data. Anda dapat menentukan salah satu atau kedua jenis pesan dengan membuat objek dengan kunci data dan/atau notification. Sebagai contoh, berikut adalah cara menetapkan berbagai jenis payload pesan:

Pesan notifikasi

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

Pesan data

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

Pesan gabungan

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

Payload pesan notifikasi memiliki subset properti valid yang telah ditentukan, dan sedikit berbeda tergantung sistem operasi seluler target Anda. Baca dokumen referensi NotificationMessagePayload untuk mengetahui daftar lengkapnya.

Payload pesan data terdiri dari key-value pair kustom dengan beberapa batasan, termasuk batasan bahwa semua nilai harus berupa string. Baca dokumen referensi DataMessagePayload untuk mengetahui daftar lengkap pembatasannya.

Menetapkan opsi pesan

Metode berdasarkan protokol lama FCM di atas menerima argumen ketiga opsional yang menentukan beberapa opsi untuk pesan tersebut. Misalnya, contoh berikut mengirim pesan berprioritas tinggi yang akan habis masa berlakunya setelah 24 jam ke perangkat:

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: {
    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.
const options = {
  priority: 'high',
  timeToLive: 60 * 60 * 24
};

// Send 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 message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Lihat dokumen referensi MessagingOptions untuk mengetahui daftar lengkap opsi yang tersedia.