เมื่อใช้โปรโตคอลเซิร์ฟเวอร์ Firebase Admin SDK หรือ FCM คุณสามารถสร้างคำขอข้อความและส่งไปยังเป้าหมายประเภทเหล่านี้ได้
- ชื่อหัวข้อ
- เงื่อนไข
- โทเค็นการลงทะเบียนอุปกรณ์
- ชื่อกลุ่มอุปกรณ์ (โปรโตคอลเท่านั้น)
คุณสามารถส่งข้อความพร้อมเพย์โหลดการแจ้งเตือนที่ประกอบด้วยฟิลด์ที่กำหนดไว้ล่วงหน้า เพย์โหลดข้อมูลของฟิลด์ที่ผู้ใช้กำหนดเอง หรือข้อความที่มีเพย์โหลดทั้งสองประเภท ดู ประเภทข้อความ สำหรับข้อมูลเพิ่มเติม
ตัวอย่างในหน้านี้แสดงวิธีส่งข้อความแจ้งเตือนโดยใช้ Firebase Admin SDK (ซึ่งรองรับ Node , Java , Python , C# และ Go ) และ โปรโตคอล HTTP v1 นอกจากนี้ยังมีคำแนะนำในการส่งข้อความผ่าน โปรโตคอล HTTP และ XMPP เดิมที่เลิกใช้งานแล้ว
ส่งข้อความไปยังอุปกรณ์เฉพาะ
หากต้องการส่งไปยังอุปกรณ์เฉพาะเครื่องเดียว ให้ส่งโทเค็นการลงทะเบียนของอุปกรณ์ตามที่แสดง ดูข้อมูลการตั้งค่าไคลเอ็นต์สำหรับแพลตฟอร์มของคุณเพื่อเรียนรู้เพิ่มเติมเกี่ยวกับโทเค็นการลงทะเบียน
โหนด 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);
});
ชวา
// 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);
หลาม
# 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)
ไป
// 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)
ค#
// 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);
พักผ่อน
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"
}
}
}
คำสั่ง 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
เมื่อสำเร็จ แต่ละวิธีการส่งจะส่งกลับรหัสข้อความ Firebase Admin SDK ส่งคืนสตริง ID ในรูปแบบ projects/{project_id}/messages/{message_id}
การตอบสนองของโปรโตคอล HTTP เป็นคีย์ JSON เดียว:
{
"name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
}
ส่งข้อความไปยังอุปกรณ์หลายเครื่อง
Admin FCM API ช่วยให้คุณสามารถมัลติแคสต์ข้อความไปยังรายการโทเค็นการลงทะเบียนอุปกรณ์ได้ คุณสามารถระบุโทเค็นการลงทะเบียนอุปกรณ์ได้สูงสุด 500 รายการต่อการเรียกใช้
โหนด 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');
});
ชวา
// 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");
หลาม
# 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))
ไป
// 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)
ค#
// 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.SendEachForMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
ค่าที่ส่งคืนคือรายการโทเค็นที่สอดคล้องกับลำดับของโทเค็นอินพุต สิ่งนี้มีประโยชน์เมื่อคุณต้องการตรวจสอบว่าโทเค็นใดที่ทำให้เกิดข้อผิดพลาด
โหนด 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);
}
});
ชวา
// 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);
}
หลาม
# 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))
ไป
// 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)
}
ค#
// 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.SendEachForMulticastAsync(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}");
}
ส่งข้อความไปยังหัวข้อ
หลังจากที่คุณสร้างหัวข้อแล้ว โดยการสมัครอินสแตนซ์แอปไคลเอ็นต์กับหัวข้อในฝั่งไคลเอ็นต์หรือผ่าน เซิร์ฟเวอร์ API คุณสามารถส่งข้อความไปยังหัวข้อได้ หากนี่เป็นครั้งแรกที่คุณสร้างส่งคำขอสำหรับ FCM โปรดดูคำแนะนำเกี่ยวกับ สภาพแวดล้อมเซิร์ฟเวอร์ของคุณและ FCM สำหรับข้อมูลพื้นหลังและการตั้งค่าที่สำคัญ
ในตรรกะการส่งของคุณบนแบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการตามที่แสดง:
โหนด 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);
});
ชวา
// 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);
หลาม
# 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)
ไป
// 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)
ค#
// 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);
พักผ่อน
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"
}
}
}
คำสั่ง 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
หากต้องการส่งข้อความไปยังหัวข้อต่างๆ รวมกัน ให้ระบุ เงื่อนไข ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครรับ TopicA
และ TopicB
หรือ TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข้อมูลหัวข้อใดหัวข้อหนึ่งจะไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครสมาชิก TopicA
จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้ได้รับ:
-
TopicA
และTopicB
-
TopicA
และTopicC
คุณสามารถรวมหัวข้อได้สูงสุดห้าหัวข้อในนิพจน์แบบมีเงื่อนไขของคุณ
หากต้องการส่งตามเงื่อนไข:
โหนด 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);
});
ชวา
// 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);
หลาม
# 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)
ไป
// 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)
ค#
// 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);
พักผ่อน
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",
}
}
}
คำสั่ง 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
ส่งข้อความไปยังกลุ่มอุปกรณ์
หากต้องการส่งข้อความไปยังกลุ่มอุปกรณ์ ให้ใช้ HTTP v1 API หากคุณกำลังส่งไปยังกลุ่มอุปกรณ์โดยใช้ API การส่งแบบเดิมที่เลิกใช้งานแล้วสำหรับ HTTP หรือ XMPP หรือ Firebase Admin SDK เวอร์ชันเก่าสำหรับ Node.js ที่อิงตามโปรโตคอลเดิม เราขอแนะนำอย่างยิ่งให้คุณ ย้ายข้อมูลไปยัง HTTP v1 API ในโอกาสแรกสุด API การส่งแบบเดิมจะถูกปิดใช้และนำออกในเดือนมิถุนายน 2024
การส่งข้อความไปยังกลุ่มอุปกรณ์จะคล้ายกับการส่งข้อความไปยังอุปกรณ์แต่ละเครื่องมาก โดยใช้วิธีเดียวกันในการ อนุญาตการส่งคำขอ ตั้งค่า token
เค็นเป็นคีย์การแจ้งเตือนกลุ่ม:
พักผ่อน
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":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ",
"data":{
"hello": "This is a Firebase Cloud Messaging device group message!"
}
}
}
คำสั่ง cURL
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
"data":{
"hello": "This is a Firebase Cloud Messaging device group message!"
},
"token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ"
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
ส่งข้อความเป็นชุด
Admin SDK รองรับการส่งข้อความเป็นกลุ่ม คุณสามารถจัดกลุ่มข้อความได้มากถึง 500 ข้อความเป็นชุดเดียวและส่งทั้งหมดในการเรียก API เดียว พร้อมการปรับปรุงประสิทธิภาพที่เหนือกว่าการส่งคำขอ HTTP แยกกันสำหรับแต่ละข้อความ
คุณสมบัตินี้สามารถใช้เพื่อสร้างชุดข้อความที่กำหนดเองและส่งไปยังผู้รับที่แตกต่างกัน รวมถึงหัวข้อหรือโทเค็นการลงทะเบียนอุปกรณ์เฉพาะ ใช้ฟีเจอร์นี้เมื่อคุณต้องการส่งข้อความไปยังผู้ชมที่แตกต่างกันไปพร้อมกันโดยมีรายละเอียดที่แตกต่างกันเล็กน้อยในเนื้อหาข้อความ เป็นต้น
โหนด 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');
});
ชวา
// 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");
หลาม
# 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))
ไป
// 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)
ค#
// 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.SendEachAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
ส่งข้อความที่เปิดใช้งานการบูตโดยตรง (Android เท่านั้น)
คุณสามารถส่งข้อความไปยังอุปกรณ์ในโหมดไดเร็กบูตได้โดยใช้ HTTP v1 หรือ HTTP API เดิม ก่อนที่จะส่งไปยังอุปกรณ์ในโหมดบูตโดยตรง ตรวจสอบให้แน่ใจว่าคุณได้ทำตามขั้นตอนเพื่อให้อุปกรณ์ไคลเอ็นต์ รับข้อความ FCM ในโหมดบูตโดยตรงแล้ว
ส่งโดยใช้ FCM v1 HTTP API
คำขอข้อความต้องมีคีย์ "direct_boot_ok" : true
ในตัวเลือก AndroidConfig
ของเนื้อหาคำขอ ตัวอย่างเช่น:
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,
},
}
ส่งโดยใช้ HTTP API เดิมของ FCM
คำขอข้อความต้องมีคีย์ "direct_boot_ok" : true
ที่ระดับบนสุดของเนื้อหาคำขอ ตัวอย่างเช่น:
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
}
ข้อความที่ส่งด้วยคีย์นี้ในเนื้อหาคำขอสามารถจัดการได้โดยแอปบนอุปกรณ์ที่อยู่ในโหมดบูตโดยตรง (และเมื่อไม่อยู่ในโหมดนั้นด้วย)
ปรับแต่งข้อความข้ามแพลตฟอร์ม
Firebase Admin SDK และโปรโตคอล FCM v1 HTTP อนุญาตให้คำขอข้อความของคุณตั้งค่าช่องทั้งหมดที่มีอยู่ในออบเจ็กต์ message
ซึ่งรวมถึง:
- ชุดฟิลด์ทั่วไปที่อินสแตนซ์แอป ทั้งหมด ได้รับข้อความจะตีความ
- ชุดฟิลด์เฉพาะแพลตฟอร์ม เช่น
AndroidConfig
และWebpushConfig
ตีความโดยอินสแตนซ์ของแอปที่ทำงานบนแพลตฟอร์มที่ระบุเท่านั้น
การบล็อกเฉพาะแพลตฟอร์มทำให้คุณมีความยืดหยุ่นในการปรับแต่งข้อความสำหรับแพลตฟอร์มต่างๆ เพื่อให้แน่ใจว่าได้รับการจัดการอย่างถูกต้องเมื่อได้รับ แบ็กเอนด์ FCM จะนำพารามิเตอร์ที่ระบุทั้งหมดมาพิจารณาและปรับแต่งข้อความสำหรับแต่ละแพลตฟอร์ม
เมื่อใดจึงควรใช้ฟิลด์ทั่วไป
ใช้ฟิลด์ทั่วไปเมื่อคุณ:
- การกำหนดเป้าหมายอินสแตนซ์ของแอปใน ทุก แพลตฟอร์ม — Apple, Android และเว็บ
- การส่งข้อความไปยังหัวข้อ
อินสแตนซ์ของแอปทั้งหมด โดยไม่คำนึงถึงแพลตฟอร์ม สามารถตีความฟิลด์ทั่วไปต่อไปนี้:
เมื่อใดควรใช้ฟิลด์เฉพาะแพลตฟอร์ม
ใช้ฟิลด์เฉพาะแพลตฟอร์มเมื่อคุณต้องการ:
- ส่งฟิลด์ไปยังแพลตฟอร์มเฉพาะเท่านั้น
- ส่งฟิลด์เฉพาะแพลตฟอร์ม นอกเหนือจาก ฟิลด์ทั่วไป
เมื่อใดก็ตามที่คุณต้องการส่งค่าไปยังแพลตฟอร์มใดแพลตฟอร์มหนึ่งเท่านั้น อย่า ใช้ฟิลด์ทั่วไป ใช้ฟิลด์เฉพาะแพลตฟอร์ม ตัวอย่างเช่น หากต้องการส่งการแจ้งเตือนไปยังแพลตฟอร์มและเว็บของ Apple เท่านั้น แต่ไม่ส่งไปยัง Android คุณต้องใช้ชุดฟิลด์สองชุดแยกกัน ชุดหนึ่งสำหรับ Apple และอีกชุดสำหรับเว็บ
เมื่อคุณส่งข้อความด้วย ตัวเลือกการจัดส่ง เฉพาะ ให้ใช้ช่องเฉพาะแพลตฟอร์มเพื่อตั้งค่า คุณสามารถระบุค่าที่แตกต่างกันในแต่ละแพลตฟอร์มได้หากต้องการ อย่างไรก็ตาม แม้ว่าคุณจะต้องการตั้งค่าเดียวกันในทุกแพลตฟอร์ม คุณต้องใช้ช่องเฉพาะแพลตฟอร์ม เนื่องจากแต่ละแพลตฟอร์มอาจตีความค่าแตกต่างกันเล็กน้อย เช่น time-to-live ตั้งค่าบน Android เป็นเวลาหมดอายุเป็นวินาที ในขณะที่ Apple ตั้งค่าเป็น วัน หมดอายุ
ตัวอย่าง: ข้อความแจ้งเตือนพร้อมตัวเลือกสีและไอคอน
ตัวอย่างการส่งคำขอนี้จะส่งชื่อและเนื้อหาการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ยังส่งการลบล้างเฉพาะแพลตฟอร์มบางส่วนไปยังอุปกรณ์ Android ด้วย
สำหรับ Android คำขอจะตั้งค่าไอคอนและสีพิเศษเพื่อแสดงบนอุปกรณ์ Android ตามที่ระบุไว้ในข้อมูลอ้างอิงสำหรับ AndroidNotification สีจะถูกระบุในรูปแบบ #rrggbb และรูปภาพจะต้องเป็นทรัพยากรไอคอนที่วาดได้ภายในแอป Android
ต่อไปนี้เป็นค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:
โหนด 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);
});
ชวา
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();
หลาม
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',
)
ไป
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",
}
ค#
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",
};
พักผ่อน
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"
}
}
}
}
ดู เอกสารอ้างอิง HTTP v1 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ
ตัวอย่าง: ข้อความแจ้งเตือนพร้อมรูปภาพที่กำหนดเอง
ตัวอย่างต่อไปนี้ส่งคำขอส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ยังส่งรูปภาพด้วย ต่อไปนี้เป็นค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:
โหนด 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);
});
พักผ่อน
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"
}
}
}
}
ดู เอกสารอ้างอิง HTTP v1 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ
ตัวอย่าง: ข้อความแจ้งเตือนที่มีการคลิกที่เกี่ยวข้อง
ตัวอย่างการส่งคำขอต่อไปนี้จะส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ยังส่งการดำเนินการเพื่อให้แอปดำเนินการเพื่อตอบสนองผู้ใช้ที่โต้ตอบกับการแจ้งเตือนด้วย ต่อไปนี้เป็นค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:
โหนด 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);
});
พักผ่อน
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"
}
}
}
}
ดู เอกสารอ้างอิง HTTP v1 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ
ตัวอย่าง: ข้อความแจ้งเตือนพร้อมตัวเลือกการแปล
ตัวอย่างต่อไปนี้ส่งคำขอส่งตัวเลือกการแปลสำหรับไคลเอนต์เพื่อแสดงข้อความที่แปลแล้ว ต่อไปนี้เป็นค่าประมาณของเอฟเฟ็กต์ภาพบนอุปกรณ์ของผู้ใช้:
โหนด 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);
});
พักผ่อน
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"],
},
},
},
},
},
}'
ดู เอกสารอ้างอิง HTTP v1 สำหรับรายละเอียดทั้งหมดเกี่ยวกับคีย์ที่มีอยู่ในบล็อกเฉพาะแพลตฟอร์มในเนื้อหาข้อความ
รหัสข้อผิดพลาดของผู้ดูแลระบบ
ตารางต่อไปนี้แสดงรายการรหัสข้อผิดพลาด Firebase Admin FCM API และคำอธิบาย รวมถึงขั้นตอนการแก้ปัญหาที่แนะนำ
รหัสข้อผิดพลาด | คำอธิบายและขั้นตอนการแก้ปัญหา |
---|---|
messaging/invalid-argument | มีการจัดเตรียมอาร์กิวเมนต์ที่ไม่ถูกต้องให้กับวิธี FCM ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม |
messaging/invalid-recipient | ผู้รับข้อความที่ต้องการไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม |
messaging/invalid-payload | มีการจัดเตรียมออบเจ็กต์เพย์โหลดข้อความที่ไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม |
messaging/invalid-data-payload-key | เพย์โหลดข้อความข้อมูลมีคีย์ที่ไม่ถูกต้อง ดูเอกสารอ้างอิงสำหรับ DataMessagePayload สำหรับคีย์ที่ถูกจำกัด |
messaging/payload-size-limit-exceeded | เพย์โหลดข้อความที่ให้มาเกินขีดจำกัดขนาด FCM ขีดจำกัดคือ 4096 ไบต์สำหรับข้อความส่วนใหญ่ สำหรับข้อความที่ส่งถึงหัวข้อ ขีดจำกัดคือ 2,048 ไบต์ ขนาดเพย์โหลดทั้งหมดมีทั้งคีย์และค่า |
messaging/invalid-options | มีการจัดเตรียมออบเจ็กต์ตัวเลือกข้อความที่ไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม |
messaging/invalid-registration-token | โทเค็นการลงทะเบียนที่ระบุไม่ถูกต้อง ตรวจสอบให้แน่ใจว่าตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนกับ FCM อย่าตัดทอนหรือเพิ่มอักขระเพิ่มเติม |
messaging/registration-token-not-registered | โทเค็นการลงทะเบียนที่ให้มาไม่ได้ลงทะเบียน โทเค็นการลงทะเบียนที่ถูกต้องก่อนหน้านี้สามารถยกเลิกการลงทะเบียนได้ด้วยเหตุผลหลายประการ รวมถึง:
|
messaging/invalid-package-name | ข้อความถูกส่งไปยังโทเค็นการลงทะเบียนที่มีชื่อแพ็คเกจไม่ตรงกับตัวเลือก restrictedPackageName ที่ให้ไว้ |
messaging/message-rate-exceeded | อัตราข้อความไปยังเป้าหมายเฉพาะสูงเกินไป ลดจำนวนข้อความที่ส่งไปยังอุปกรณ์หรือหัวข้อนี้ และอย่าลองส่งไปยังเป้าหมายนี้อีกครั้งในทันที |
messaging/device-message-rate-exceeded | อัตราข้อความไปยังอุปกรณ์เฉพาะสูงเกินไป ลดจำนวนข้อความที่ส่งไปยังอุปกรณ์นี้ และอย่าลองส่งไปยังอุปกรณ์นี้อีกครั้งในทันที |
messaging/topics-message-rate-exceeded | อัตราข้อความถึงสมาชิกในหัวข้อใดหัวข้อหนึ่งสูงเกินไป ลดจำนวนข้อความที่ส่งสำหรับหัวข้อนี้ และอย่าลองส่งไปที่หัวข้อนี้อีกครั้งในทันที |
messaging/too-many-topics | โทเค็นการลงทะเบียนได้สมัครรับหัวข้อถึงจำนวนสูงสุดแล้ว และไม่สามารถสมัครรับข้อมูลอีกต่อไป |
messaging/invalid-apns-credentials | ไม่สามารถส่งข้อความที่กำหนดเป้าหมายไปยังอุปกรณ์ Apple ได้เนื่องจากไม่ได้อัปโหลดใบรับรอง APN SSL ที่จำเป็นหรือหมดอายุแล้ว ตรวจสอบความถูกต้องของใบรับรองการพัฒนาและการผลิตของคุณ |
messaging/mismatched-credential | ข้อมูลรับรองที่ใช้ในการตรวจสอบสิทธิ์ SDK นี้ไม่ได้รับอนุญาตให้ส่งข้อความไปยังอุปกรณ์ที่สอดคล้องกับโทเค็นการลงทะเบียนที่ให้ไว้ ตรวจสอบให้แน่ใจว่าข้อมูลรับรองและโทเค็นการลงทะเบียนเป็นของโปรเจ็กต์ Firebase เดียวกัน ดู เพิ่ม Firebase ลงในแอปของคุณ สำหรับเอกสารเกี่ยวกับวิธีการตรวจสอบสิทธิ์ Firebase Admin SDK |
messaging/authentication-error | SDK ไม่สามารถตรวจสอบสิทธิ์เซิร์ฟเวอร์ FCM ได้ ตรวจสอบให้แน่ใจว่าคุณตรวจสอบสิทธิ์ Firebase Admin SDK ด้วยข้อมูลรับรองที่มีสิทธิ์ที่เหมาะสมในการส่งข้อความ FCM ดู เพิ่ม Firebase ลงในแอปของคุณ สำหรับเอกสารเกี่ยวกับวิธีการตรวจสอบสิทธิ์ Firebase Admin SDK |
messaging/server-unavailable | เซิร์ฟเวอร์ FCM ไม่สามารถประมวลผลคำขอได้ทันเวลา คุณควรลองคำขอเดิมอีกครั้ง แต่คุณต้อง:
|
messaging/internal-error | เซิร์ฟเวอร์ FCM พบข้อผิดพลาดขณะพยายามประมวลผลคำขอ คุณสามารถลองคำขอเดิมอีกครั้งได้ตามความต้องการที่ระบุไว้ในแถว messaging/server-unavailable ด้านบน หากข้อผิดพลาดยังคงอยู่ โปรดรายงานปัญหาไปยังช่องทางสนับสนุน รายงานข้อผิดพลาด ของเรา |
messaging/unknown-error | ข้อผิดพลาดเซิร์ฟเวอร์ที่ไม่รู้จักถูกส่งคืน ดูการตอบสนองของเซิร์ฟเวอร์ Raw ในข้อความแสดงข้อผิดพลาดเพื่อดูรายละเอียดเพิ่มเติม หากคุณได้รับข้อผิดพลาดนี้ โปรดรายงานข้อความแสดงข้อผิดพลาดทั้งหมดไปยังช่องทางสนับสนุน รายงานข้อบกพร่อง ของเรา |
ส่งข้อความโดยใช้โปรโตคอลเซิร์ฟเวอร์แอปเดิม
หากคุณกำลังใช้โปรโตคอลเดิม ให้สร้างคำขอข้อความตามที่แสดงในส่วนนี้ โปรดทราบว่าหากคุณส่งไปยังหลายแพลตฟอร์มผ่าน HTTP โปรโตคอล v1 จะทำให้คำขอข้อความของคุณง่ายขึ้นอย่างมาก
ส่งข้อความไปยังอุปกรณ์เฉพาะ
หากต้องการส่งข้อความไปยังอุปกรณ์เฉพาะ ให้ตั้งค่าคีย์ to
โทเค็นการลงทะเบียนสำหรับอินสแตนซ์แอปเฉพาะ ดูข้อมูลการตั้งค่าไคลเอ็นต์สำหรับแพลตฟอร์มของคุณเพื่อเรียนรู้เพิ่มเติมเกี่ยวกับโทเค็นการลงทะเบียน
คำขอ HTTP POST
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..."
}
การตอบสนองของ HTTP
{ "multicast_id": 108, "success": 1, "failure": 0, "results": [ { "message_id": "1:08" } ] }
ข้อความ XMPP
<message id="">
<gcm xmlns="google:mobile:data">
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
</gcm>
</message>
การตอบสนอง XMPP
<message id=""> <gcm xmlns="google:mobile:data"> { "from":"REGID", "message_id":"m-1366082849205" "message_type":"ack" } </gcm> </message>
เซิร์ฟเวอร์การเชื่อมต่อ XMPP มีตัวเลือกอื่นสำหรับการตอบกลับ ดู รูปแบบการตอบกลับของเซิร์ฟเวอร์
สำหรับรายการตัวเลือกข้อความทั้งหมดที่พร้อมใช้งานเมื่อส่งข้อความดาวน์สตรีมไปยังแอปไคลเอนต์ โปรดดูข้อมูลอ้างอิงสำหรับโปรโตคอลเซิร์ฟเวอร์การเชื่อมต่อที่คุณเลือก HTTP หรือ XMPP
ส่งข้อความไปยังหัวข้อ
การส่งข้อความไปยังหัวข้อ Firebase Cloud Messaging นั้นคล้ายคลึงกับการส่งข้อความไปยังอุปกรณ์แต่ละเครื่องหรือกลุ่มผู้ใช้มาก เซิร์ฟเวอร์แอปจะตั้งค่า to
เป็น /topics/yourTopic
นักพัฒนาสามารถเลือกชื่อหัวข้อที่ตรงกับนิพจน์ทั่วไป: "/topics/[a-zA-Z0-9-_.~%]+"
หากต้องการส่งไปยังหลายหัวข้อรวมกัน เซิร์ฟเวอร์แอปจะต้องตั้งค่าคีย์ condition
(แทนคีย์ to
) เป็นเงื่อนไขบูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น หากต้องการส่งข้อความไปยังอุปกรณ์ที่สมัครรับ TopicA
และ TopicB
หรือ TopicC
:
'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)
FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข้อมูลหัวข้อใดหัวข้อหนึ่งจะไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครสมาชิก TopicA จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้ได้รับ:
- หัวข้อ A และหัวข้อ B
- TopicA และ TopicC
คุณสามารถรวมหัวข้อได้สูงสุดห้าหัวข้อในนิพจน์ตามเงื่อนไขของคุณ และรองรับวงเล็บด้วย โอเปอเรเตอร์ที่รองรับ: &&
, ||
.
คำขอ HTTP POST ของหัวข้อ
ส่งไปที่หัวข้อเดียว:
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
ส่งไปยังอุปกรณ์ที่สมัครรับหัวข้อ "สุนัข" หรือ "แมว":
https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
การตอบสนองของหัวข้อ HTTP
//Success example: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
หัวข้อข้อความ XMPP
ส่งไปที่หัวข้อเดียว:
<message id="">
<gcm xmlns="google:mobile:data">
</gcm>
</message>
ส่งไปยังอุปกรณ์ที่สมัครรับหัวข้อ "สุนัข" หรือ "แมว":
<message id=""> <gcm xmlns="google:mobile:data"> </gcm> </message>
หัวข้อการตอบสนอง XMPP
//Success example: { "message_id": "1023456" } //failure example: { "error": "TopicsMessageRateExceeded" }
คาดว่าจะเกิดความล่าช้าสูงสุด 30 วินาทีก่อนที่เซิร์ฟเวอร์ FCM จะตอบกลับคำขอส่งหัวข้อสำเร็จหรือล้มเหลว ตรวจสอบให้แน่ใจว่าได้ตั้งค่าการหมดเวลาของเซิร์ฟเวอร์แอปในคำขอตามนั้น
ส่งข้อความไปยังกลุ่มอุปกรณ์
การส่งข้อความไปยังกลุ่มอุปกรณ์โดยใช้ API เดิมที่เลิกใช้แล้วจะคล้ายกับการส่งข้อความไปยังอุปกรณ์แต่ละเครื่องมาก ตั้ง to
พารามิเตอร์เป็นคีย์การแจ้งเตือนเฉพาะสำหรับกลุ่มอุปกรณ์ ตัวอย่างในส่วนนี้แสดงวิธีการส่งข้อความข้อมูลไปยังกลุ่มอุปกรณ์ในโปรโตคอล HTTP และ XMPP ดั้งเดิม
คำขอ HTTP POST ของกลุ่มอุปกรณ์
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!", } }
การตอบสนอง HTTP ของกลุ่มอุปกรณ์
นี่คือตัวอย่างของ "ความสำเร็จ"— notification_key
มีโทเค็นการลงทะเบียน 2 อันเชื่อมโยงอยู่ และส่งข้อความถึงทั้งสองรายการได้สำเร็จ:
{ "success": 2, "failure": 0 }
นี่คือตัวอย่างของ "ความสำเร็จบางส่วน" — notification_key
มีโทเค็นการลงทะเบียน 3 รายการที่เกี่ยวข้องกัน ข้อความถูกส่งไปยังโทเค็นการลงทะเบียนสำเร็จแล้ว 1 รายการเท่านั้น ข้อความตอบกลับจะแสดงรายการโทเค็นการลงทะเบียน ( registration_ids
) ที่ไม่ได้รับข้อความ:
{ "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
เมื่อข้อความล้มเหลวในการส่งข้อความไปยังโทเค็นการลงทะเบียนอย่างน้อยหนึ่งรายการที่เกี่ยวข้องกับ notification_key
เซิร์ฟเวอร์แอปควรลองอีกครั้งโดยมีแบ็คออฟระหว่างการลองใหม่
หากเซิร์ฟเวอร์พยายามส่งข้อความไปยังกลุ่มอุปกรณ์ที่ไม่มีสมาชิก การตอบสนองจะมีลักษณะดังนี้ โดยถือว่าสำเร็จ 0 ครั้งและล้มเหลว 0 ครั้ง:
{ "success": 0, "failure": 0 }
ข้อความ XMPP ของกลุ่มอุปกรณ์
<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>
การตอบสนอง XMPP ของกลุ่มอุปกรณ์
เมื่อข้อความถูกส่งไปยังอุปกรณ์ใด ๆ ในกลุ่มสำเร็จ เซิร์ฟเวอร์การเชื่อมต่อ XMPP จะตอบกลับด้วย ACK หากข้อความทั้งหมดที่ส่งไปยังอุปกรณ์ทั้งหมดในกลุ่มล้มเหลว เซิร์ฟเวอร์การเชื่อมต่อ XMPP จะตอบกลับด้วย NACK
นี่คือตัวอย่างของ "ความสำเร็จ" — notification_key
มีโทเค็นการลงทะเบียน 3 รายการที่เกี่ยวข้องกัน และข้อความถูกส่งไปยังโทเค็นทั้งหมดสำเร็จแล้ว:
{ "from": "aUniqueKey", "message_type": "ack", "success": 3, "failure": 0, "message_id": "m-1366082849205" }
นี่คือตัวอย่างของ "ความสำเร็จบางส่วน" — notification_key
มีโทเค็นการลงทะเบียน 3 รายการที่เกี่ยวข้องกัน ข้อความถูกส่งไปยังโทเค็นการลงทะเบียนสำเร็จแล้ว 1 รายการเท่านั้น ข้อความตอบกลับจะแสดงรายการโทเค็นการลงทะเบียนที่ไม่ได้รับข้อความ:
{ "from": "aUniqueKey", "message_type": "ack", "success":1, "failure":2, "failed_registration_ids":[ "regId1", "regId2" ] }
เมื่อเซิร์ฟเวอร์การเชื่อมต่อ FCM ไม่สามารถส่งไปยังอุปกรณ์ทั้งหมดในกลุ่มได้ เซิร์ฟเวอร์แอปจะได้รับการตอบกลับแบบไม่มีข้อมูล
สำหรับรายการตัวเลือกข้อความทั้งหมด โปรดดูข้อมูลอ้างอิงสำหรับโปรโตคอลเซิร์ฟเวอร์การเชื่อมต่อที่คุณเลือก HTTP หรือ XMPP
วิธีการส่งแบบดั้งเดิมของ Firebase Admin SDK
Firebase Admin Node.js SDK รองรับวิธีการส่งข้อความ (FCM) โดยอิงตาม Legacy FCM server API วิธีการเหล่านี้ยอมรับข้อโต้แย้งที่แตกต่างกันเมื่อเทียบกับวิธี send()
คุณควรใช้เมธอด send()
ทุกครั้งที่เป็นไปได้ และใช้เฉพาะวิธีที่อธิบายไว้ในหน้านี้เมื่อส่งข้อความไปยังอุปกรณ์แต่ละเครื่องหรือกลุ่มอุปกรณ์
ส่งไปยังอุปกรณ์แต่ละเครื่อง
คุณสามารถส่งโทเค็นการลงทะเบียนไปยังเมธอด sendToDevice()
เพื่อส่งข้อความไปยังอุปกรณ์นั้นได้:
โหนด 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);
});
เมธอด sendToDevice()
ยังสามารถส่งข้อความ มัลติคาสต์ (นั่นคือ ข้อความไปยังอุปกรณ์หลายเครื่อง) โดยการส่งอาร์เรย์ของโทเค็นการลงทะเบียน แทนที่จะส่งโทเค็นการลงทะเบียนเพียงอันเดียว:
โหนด 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);
});
เมธอด sendToDevice()
ส่งคืนสัญญาที่ได้รับการแก้ไขด้วยวัตถุ MessagingDevicesResponse
ที่มีการตอบกลับจาก FCM ประเภทการส่งคืนมีรูปแบบเดียวกันเมื่อส่งโทเค็นการลงทะเบียนเดียวหรืออาร์เรย์ของโทเค็นการลงทะเบียน
บางกรณี เช่น ข้อผิดพลาดในการรับรองความถูกต้องหรือการจำกัดอัตราทำให้ข้อความทั้งหมดล้มเหลวในการประมวลผล ในกรณีเหล่านี้ คำสัญญาที่ส่งกลับโดย sendToDevice()
จะถูกปฏิเสธโดยมีข้อผิดพลาด หากต้องการดูรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ไข โปรดดู ข้อผิดพลาด Admin FCM API
ส่งไปยังกลุ่มอุปกรณ์
เมธอด sendToDeviceGroup()
ช่วยให้คุณสามารถส่งข้อความไปยังกลุ่มอุปกรณ์โดยการระบุคีย์การแจ้งเตือนสำหรับกลุ่มอุปกรณ์นั้น:
โหนด 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);
});
เมธอด sendToDeviceGroup()
ส่งคืนสัญญาที่ได้รับการแก้ไขด้วยวัตถุ MessagingDevicesResponse
ที่มีการตอบกลับจาก FCM
บางกรณี เช่น ข้อผิดพลาดในการรับรองความถูกต้องหรือการจำกัดอัตราทำให้ข้อความทั้งหมดล้มเหลวในการประมวลผล ในกรณีเหล่านี้ คำสัญญาที่ส่งกลับโดย sendToDeviceGroup()
จะถูกปฏิเสธโดยมีข้อผิดพลาด หากต้องการดูรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ไข โปรดดู ข้อผิดพลาด Admin FCM API
การกำหนดเพย์โหลดข้อความ
วิธีการข้างต้นที่ใช้โปรโตคอลดั้งเดิมของ FCM ยอมรับเพย์โหลดข้อความเป็นอาร์กิวเมนต์ที่สอง และรองรับทั้ง ข้อความแจ้งเตือนและข้อความข้อมูล คุณสามารถระบุประเภทข้อความหนึ่งหรือทั้งสองประเภทได้โดยการสร้างออบเจ็กต์ที่มีคีย์ data
และ/หรือ notification
ตัวอย่างเช่น ต่อไปนี้เป็นวิธีกำหนดเพย์โหลดข้อความประเภทต่างๆ:
ข้อความแจ้งเตือน
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.'
}
};
ข้อความข้อมูล
const payload = {
data: {
score: '850',
time: '2:45'
}
};
ข้อความรวม
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'
}
};
เพย์โหลดข้อความแจ้งเตือนมีชุดย่อยของคุณสมบัติที่ถูกต้องที่กำหนดไว้ล่วงหน้า และแตกต่างกันเล็กน้อยขึ้นอยู่กับระบบปฏิบัติการมือถือที่คุณกำหนดเป้าหมาย ดูเอกสารอ้างอิงสำหรับ NotificationMessagePayload
สำหรับรายการทั้งหมด
เพย์โหลดข้อความข้อมูลประกอบด้วยคู่คีย์-ค่าที่กำหนดเองโดยมีข้อจำกัดบางประการ รวมถึงข้อเท็จจริงที่ว่าค่าทั้งหมดต้องเป็นสตริง ดูเอกสารอ้างอิงสำหรับ DataMessagePayload
สำหรับรายการข้อจำกัดทั้งหมด
การกำหนดตัวเลือกข้อความ
วิธีการข้างต้นซึ่งใช้โปรโตคอลดั้งเดิมของ FCM ยอมรับอาร์กิวเมนต์ที่สามซึ่งเป็นทางเลือกซึ่งระบุตัวเลือกบางอย่างสำหรับข้อความ ตัวอย่างเช่น ตัวอย่างต่อไปนี้ส่งข้อความที่มีลำดับความสำคัญสูงไปยังอุปกรณ์ซึ่งจะหมดอายุหลังจาก 24 ชั่วโมง:
โหนด 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);
});
ดูเอกสารอ้างอิงสำหรับ MessagingOptions
สำหรับรายการตัวเลือกทั้งหมดที่มี