สร้างคำขอเซิร์ฟเวอร์แอป

การใช้ Firebase Admin SDK หรือโปรโตคอลเซิร์ฟเวอร์แอป FCM ช่วยให้คุณสร้างคำขอข้อความและส่งไปยังเป้าหมายประเภทต่อไปนี้ได้

  • ชื่อหัวข้อ
  • เงื่อนไข
  • โทเค็นการลงทะเบียนอุปกรณ์
  • ชื่อกลุ่มอุปกรณ์ (โปรโตคอลเท่านั้น)

คุณสามารถส่งข้อความด้วยเพย์โหลดการแจ้งเตือนซึ่งประกอบด้วยช่องที่กำหนดไว้ล่วงหน้า เพย์โหลดข้อมูลของช่องที่กำหนดโดยผู้ใช้ หรือข้อความที่มีเพย์โหลดทั้ง 2 ประเภท ดูข้อมูลเพิ่มเติมใน ประเภทข้อความ

ตัวอย่างในหน้านี้แสดงวิธีส่งข้อความการแจ้งเตือนโดยใช้ Firebase Admin SDK (ซึ่งรองรับ Node, Java, Python, C# และ Go) และโปรโตคอล HTTP v1 นอกจากนี้ยังมีคำแนะนำในการส่งข้อความผ่านโปรโตคอล HTTP และ XMPP เดิมที่เลิกใช้งานแล้วด้วย

ส่งข้อความไปยังอุปกรณ์เฉพาะ

หากต้องการส่งไปยังอุปกรณ์เครื่องเดียวโดยเฉพาะ ให้ส่งโทเค็นการลงทะเบียนของอุปกรณ์ตามที่ปรากฏ ดูข้อมูลการตั้งค่าไคลเอ็นต์สำหรับแพลตฟอร์มของคุณเพื่อดูข้อมูลเพิ่มเติมเกี่ยวกับโทเค็นการลงทะเบียน

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"
      }
   }
}

คำสั่ง 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 จะแสดงผลสตริงรหัสในรูปแบบ projects/{project_id}/messages/{message_id} การตอบกลับโปรโตคอล HTTP คือคีย์ JSON รายการเดียว:

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

ส่งข้อความไปยังอุปกรณ์หลายเครื่อง

Admin FCM API จะช่วยให้คุณแคสต์ข้อความไปยังรายการโทเค็นการลงทะเบียนอุปกรณ์ได้หลายรายการ คุณระบุโทเค็นการลงทะเบียนอุปกรณ์ได้สูงสุด 500 โทเค็นต่อการเรียกใช้

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.SendEachForMulticastAsync(message);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

ค่าที่ส่งกลับคือรายการโทเค็นที่สอดคล้องกับลำดับของโทเค็นอินพุต วิธีนี้มีประโยชน์เมื่อคุณต้องการตรวจสอบว่าโทเค็นใดส่งผลให้เกิดข้อผิดพลาด

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.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 สำหรับ ข้อมูลเบื้องต้นที่สำคัญและการตั้งค่า

ในตรรกะการส่งบนแบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการดังที่แสดงไว้

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"
      }
   }
}

คำสั่ง 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

หากต้องการส่งข้อความไปยังชุดค่าผสมของหัวข้อ ให้ระบุ condition ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย เช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครใช้บริการ TopicA และ TopicB หรือ TopicC

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

FCM จะประเมินเงื่อนไขในวงเล็บก่อน จากนั้นประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข้อมูล หัวข้อใดหัวข้อหนึ่งจะไม่ได้รับข้อความ และผู้ใช้ที่ไม่ได้สมัครรับ TopicA ก็จะไม่ได้รับข้อความนี้เช่นกัน ชุดค่าผสมต่อไปนี้ จะรับคำขอดังกล่าว

  • TopicA และ TopicB
  • TopicA และ TopicC

คุณสามารถใส่หัวข้อในนิพจน์แบบมีเงื่อนไขได้สูงสุด 5 หัวข้อ

วิธีส่งไปยังเงื่อนไข

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",
    }
  }
}

คำสั่ง 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 เป็นคีย์การแจ้งเตือนกลุ่ม

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":"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

ส่งข้อความเป็นกลุ่ม

SDK ของผู้ดูแลระบบรองรับการส่งข้อความแบบเป็นกลุ่ม คุณจะจัดกลุ่มข้อความได้สูงสุด 500 ข้อความเป็นกลุ่มเดียว และส่งทั้งหมดในการเรียก API เดียว พร้อมปรับปรุงประสิทธิภาพได้อย่างมากมากกว่าการส่งคำขอ HTTP แยกกันสำหรับแต่ละข้อความ

คุณสามารถใช้ฟีเจอร์นี้เพื่อสร้างชุดข้อความที่กำหนดเองและส่งไปยังผู้รับต่างๆ รวมถึงหัวข้อหรือโทเค็นการลงทะเบียนอุปกรณ์ที่เจาะจง ใช้ฟีเจอร์นี้เมื่อต้องส่งข้อความถึงกลุ่มเป้าหมายต่างๆ พร้อมกัน โดยมีรายละเอียดที่แตกต่างกันเล็กน้อยในเนื้อหาข้อความ

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.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 และโปรโตคอล HTTP FCM v1 จะอนุญาตให้ส่งคำขอข้อความเพื่อตั้งค่าช่องทั้งหมดที่มีอยู่ในออบเจ็กต์ message ข้อมูลส่วนตัวดังกล่าวรวมถึงสิ่งต่อไปนี้

  • ชุดของช่องทั่วไปที่จะตีความโดยอินสแตนซ์แอปทั้งหมดที่ได้รับข้อความ
  • ชุดของช่องเฉพาะแพลตฟอร์ม เช่น AndroidConfig และ WebpushConfig จะตีความโดยอินสแตนซ์แอปที่ทำงานในแพลตฟอร์มที่ระบุเท่านั้น

การบล็อกเฉพาะแพลตฟอร์มช่วยให้คุณปรับแต่งข้อความสำหรับแพลตฟอร์มต่างๆ ได้อย่างยืดหยุ่น เพื่อดูแลให้มีการจัดการอย่างถูกต้องเมื่อได้รับ แบ็กเอนด์ของ FCM จะนำพารามิเตอร์ที่ระบุทั้งหมดมาพิจารณาและปรับแต่งข้อความสำหรับแต่ละแพลตฟอร์ม

กรณีที่ควรใช้ช่องทั่วไป

ใช้ช่องทั่วไปเมื่อคุณทำสิ่งต่อไปนี้

  • การกำหนดเป้าหมายอินสแตนซ์ของแอปบนแพลตฟอร์มทั้งหมด ได้แก่ Apple, Android และเว็บ
  • การส่งข้อความไปยังหัวข้อ

อินสแตนซ์แอปทั้งหมด ไม่ว่าจะแพลตฟอร์มใดก็ตาม จะตีความช่องทั่วไปต่อไปนี้ได้

กรณีที่ควรใช้ช่องเฉพาะแพลตฟอร์ม

ใช้ช่องเฉพาะแพลตฟอร์มเมื่อต้องการทําสิ่งต่อไปนี้

  • ส่งช่องไปยังบางแพลตฟอร์มเท่านั้น
  • ส่งช่องเฉพาะแพลตฟอร์มเพิ่มเติมจากช่องทั่วไป

เมื่อต้องการส่งค่าไปยังแพลตฟอร์มที่เฉพาะเจาะจงเท่านั้น อย่าใช้ช่องทั่วไป แต่ให้ใช้ช่องเฉพาะแพลตฟอร์ม เช่น หากต้องการส่งการแจ้งเตือนไปยังแพลตฟอร์มและเว็บของ Apple เท่านั้น แต่ส่งไปยัง Android คุณต้องใช้ช่อง 2 ชุดแยกกัน โดยชุดหนึ่งสำหรับ Apple และอีกชุดสำหรับเว็บ

เมื่อคุณส่งข้อความที่มีตัวเลือกการส่งที่เจาะจง ให้ใช้ช่องเฉพาะแพลตฟอร์มเพื่อตั้งค่า คุณสามารถระบุค่าที่แตกต่างกันในแต่ละแพลตฟอร์มได้ หากต้องการ อย่างไรก็ตาม แม้จะต้องการกำหนดค่าเดียวกันในแพลตฟอร์มต่างๆ คุณก็ต้องใช้ช่องเฉพาะแพลตฟอร์ม ทั้งนี้เนื่องจากแต่ละแพลตฟอร์มอาจตีความค่าแตกต่างกันเล็กน้อย เช่น มีการตั้งค่า Time to Live บน Android เป็นเวลาหมดอายุเป็นวินาที ขณะที่ใน Apple จะตั้งค่าเป็นวันที่หมดอายุ

ตัวอย่าง: ข้อความแจ้งเตือนที่มีตัวเลือกสีและไอคอน

ตัวอย่างนี้จะส่งชื่อการแจ้งเตือนและเนื้อหาทั่วไปไปยังทุกแพลตฟอร์ม แต่จะส่งการลบล้างเฉพาะแพลตฟอร์มบางส่วนไปยังอุปกรณ์ Android ด้วย

สำหรับ Android คำขอนี้จะตั้งค่าไอคอนและสีพิเศษให้แสดงในอุปกรณ์ Android ตามที่ระบุไว้ในข้อมูลอ้างอิงสำหรับ AndroidNotification สีดังกล่าวระบุในรูปแบบ #rrggbb และรูปภาพต้องเป็นทรัพยากรไอคอนที่ถอนออกได้ของแอป Android ในเครื่อง

ต่อไปนี้คือค่าประมาณของเอฟเฟกต์ภาพในอุปกรณ์ของผู้ใช้

ภาพวาดอุปกรณ์ 2 เครื่องแบบง่ายๆ โดยอุปกรณ์หนึ่งแสดงไอคอนและสีที่กำหนดเอง

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"
       }
     }
   }
 }

โปรดดูรายละเอียดทั้งหมดในเอกสารประกอบอ้างอิง HTTP v1 เกี่ยวกับคีย์ที่ใช้ได้ในบล็อกเฉพาะแพลตฟอร์มในส่วนเนื้อหาของข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนที่มีรูปภาพที่กำหนดเอง

ตัวอย่างการส่งคำขอต่อไปนี้จะส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ก็ส่งรูปภาพด้วย ต่อไปนี้คือค่าประมาณของผลกระทบด้านภาพ ในอุปกรณ์ของผู้ใช้

ภาพวาดง่ายๆ ในการแจ้งเตือนที่แสดง

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"
       }
     }
   }
 }

โปรดดูรายละเอียดทั้งหมดในเอกสารประกอบอ้างอิง HTTP v1 เกี่ยวกับคีย์ที่ใช้ได้ในบล็อกเฉพาะแพลตฟอร์มในส่วนเนื้อหาของข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนที่เชื่อมโยงกับการคลิก

ตัวอย่างการส่งคำขอจะส่งชื่อการแจ้งเตือนทั่วไปไปยังทุกแพลตฟอร์ม แต่ก็ส่งการดำเนินการของแอปเพื่อตอบสนองต่อผู้ใช้ที่โต้ตอบกับการแจ้งเตือนด้วย ต่อไปนี้คือค่าประมาณของเอฟเฟกต์ภาพในอุปกรณ์ของผู้ใช้

ภาพวาดง่ายๆ ที่แสดงผู้ใช้กำลังแตะเปิดหน้าเว็บ

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"
       }
     }
   }
 }

โปรดดูรายละเอียดทั้งหมดในเอกสารประกอบอ้างอิง HTTP v1 เกี่ยวกับคีย์ที่ใช้ได้ในบล็อกเฉพาะแพลตฟอร์มในส่วนเนื้อหาของข้อความ

ตัวอย่าง: ข้อความแจ้งเตือนที่มีตัวเลือกการแปลภาษา

ตัวอย่างต่อไปนี้จะส่งตัวเลือกการแปลเพื่อให้ไคลเอ็นต์แสดงข้อความที่แปลแล้ว ต่อไปนี้คือค่าประมาณของเอฟเฟกต์ภาพในอุปกรณ์ของผู้ใช้

ภาพวาดอุปกรณ์ 2 เครื่องแสดงข้อความเป็นภาษาอังกฤษและสเปนแบบเรียบง่าย

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"],
                    },
                 },
               },
             },
  },
}'

โปรดดูรายละเอียดทั้งหมดในเอกสารประกอบอ้างอิง HTTP v1 เกี่ยวกับคีย์ที่ใช้ได้ในบล็อกเฉพาะแพลตฟอร์มในส่วนเนื้อหาของข้อความ

รหัสข้อผิดพลาดของ REST สำหรับ API ของ HTTP v1

การตอบกลับข้อผิดพลาดของ HTTP สำหรับ HTTP v1 API จะมีรหัสข้อผิดพลาด ข้อความแสดงข้อผิดพลาด และสถานะข้อผิดพลาด และอาจมีอาร์เรย์ details ที่มีรายละเอียดเพิ่มเติมเกี่ยวกับข้อผิดพลาด

ต่อไปนี้เป็นตัวอย่างการตอบกลับข้อผิดพลาด 2 แบบ

ตัวอย่างที่ 1: การตอบกลับข้อผิดพลาดจากคำขอ HTTP v1 API ที่มีค่าไม่ถูกต้องในข้อความข้อมูล

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

ตัวอย่างที่ 2: การตอบกลับข้อผิดพลาดจากคำขอ HTTP v1 API ที่มีโทเค็นการลงทะเบียนที่ไม่ถูกต้อง

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

โปรดทราบว่าข้อความทั้งสองจะมีรหัสและสถานะเดียวกัน แต่อาร์เรย์รายละเอียดจะมีค่าหลายประเภท ตัวอย่างแรกมีประเภท type.googleapis.com/google.rpc.BadRequest ที่ระบุข้อผิดพลาดในค่าคำขอ ตัวอย่างที่ 2 ประเภท type.googleapis.com/google.firebase.fcm.v1.FcmError มีข้อผิดพลาดเฉพาะ FCM สำหรับข้อผิดพลาดส่วนใหญ่ อาร์เรย์รายละเอียดจะมีข้อมูลที่ต้องใช้ในการแก้ไขข้อบกพร่องและวิธีแก้ไข

ตารางต่อไปนี้แสดงรหัสข้อผิดพลาด REST API ของ FCM v1 และคำอธิบาย

รหัสข้อผิดพลาด คำอธิบายและขั้นตอนการแก้ปัญหา
UNSPECIFIED_ERROR ไม่มีข้อมูลเพิ่มเติมเกี่ยวกับข้อผิดพลาดนี้ ไม่มี
INVALID_ARGUMENT (รหัสข้อผิดพลาด HTTP = 400) พารามิเตอร์คำขอไม่ถูกต้อง แสดงส่วนขยายประเภท google.rpc.BadRequest เพื่อระบุว่าช่องใดไม่ถูกต้อง สาเหตุที่เป็นไปได้รวมถึงการลงทะเบียนไม่ถูกต้อง, ชื่อแพ็กเกจไม่ถูกต้อง, ข้อความมีขนาดใหญ่เกินไป, คีย์ข้อมูลไม่ถูกต้อง, TTL ไม่ถูกต้อง หรือพารามิเตอร์อื่นๆ ที่ไม่ถูกต้อง
การลงทะเบียนไม่ถูกต้อง: ตรวจสอบรูปแบบของโทเค็นการลงทะเบียนที่คุณส่งไปยังเซิร์ฟเวอร์ ตรวจสอบว่าตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนด้วย FCM อย่าตัดโทเค็นหรือเพิ่มอักขระอีก
ชื่อแพ็กเกจไม่ถูกต้อง: ตรวจสอบว่าข้อความส่งไปยังโทเค็นการลงทะเบียนซึ่งมีชื่อแพ็กเกจตรงกับค่าที่ส่งในคำขอ
ข้อความมีขนาดใหญ่เกินไป: ตรวจสอบว่าขนาดรวมของข้อมูลเพย์โหลดที่รวมอยู่ในข้อความไม่เกินขีดจำกัดของ FCM ซึ่งได้แก่ 4096 ไบต์สำหรับข้อความส่วนใหญ่ หรือ 2048 ไบต์ในกรณีที่ส่งข้อความไปยังหัวข้อ ซึ่งรวมทั้งคีย์และค่า
คีย์ข้อมูลไม่ถูกต้อง: ตรวจสอบว่าข้อมูลเพย์โหลดไม่มีคีย์ (เช่น from, หรือ gcm หรือค่าใดๆ ที่นำหน้าโดย Google) ที่ใช้ภายในโดย FCM โปรดทราบว่า FCM จะใช้คำบางคำ (เช่น collapse_key) ด้วย แต่จะใช้ในเพย์โหลดได้ ซึ่งในกรณีนี้ ค่า FCM จะลบล้างค่าเพย์โหลด
TTL ไม่ถูกต้อง: ตรวจสอบว่าค่าที่ใช้ใน ttl เป็นจำนวนเต็มที่แสดงระยะเวลาเป็นวินาทีตั้งแต่ 0 ถึง 2,419,200 (4 สัปดาห์)
พารามิเตอร์ไม่ถูกต้อง: ตรวจสอบว่าพารามิเตอร์ที่ระบุมีชื่อและประเภทที่ถูกต้อง
UNREGISTERED (รหัสข้อผิดพลาด HTTP = 404) มีการลงทะเบียนอินสแตนซ์ของแอปจาก FCM แล้ว ซึ่งโดยปกติจะหมายความว่าโทเค็นที่ใช้ใช้ไม่ได้แล้วและต้องใช้โทเค็นใหม่ ข้อผิดพลาดนี้อาจเกิดจากไม่มีโทเค็นการลงทะเบียนหรือโทเค็นที่ไม่ได้ลงทะเบียน
ไม่มีการลงทะเบียน: หากเป้าหมายของข้อความเป็นค่า token ให้ตรวจสอบว่าคำขอมีโทเค็นการลงทะเบียน
ยังไม่ได้ลงทะเบียน: โทเค็นการลงทะเบียนที่มีอยู่อาจใช้งานไม่ได้ในบางสถานการณ์ เช่น
- หากแอปไคลเอ็นต์ยกเลิกการลงทะเบียนกับ FCM
- หากแอปไคลเอ็นต์ถูกยกเลิกการลงทะเบียนโดยอัตโนมัติ ซึ่งอาจเกิดขึ้นได้หากผู้ใช้ถอนการติดตั้งแอปไคลเอ็นต์ ตัวอย่างเช่น ใน iOS หากบริการความคิดเห็น APNs รายงานว่าโทเค็น APN ไม่ถูกต้อง
- หากโทเค็นการลงทะเบียนหมดอายุ (เช่น Google อาจตัดสินใจรีเฟรชโทเค็นการลงทะเบียน หรือโทเค็น APN สําหรับอุปกรณ์ iOS หมดอายุแล้ว)
- หากมีการอัปเดตแอปไคลเอ็นต์ แต่ไม่ได้กำหนดค่าเวอร์ชันใหม่ให้รับข้อความ
สำหรับกรณีเหล่านี้ทั้งหมด ให้นำโทเค็นการลงทะเบียนนี้ออกจากเซิร์ฟเวอร์ของแอปและหยุดใช้โทเค็นเพื่อส่งข้อความ
SENDER_ID_MISMATCH (รหัสข้อผิดพลาด HTTP = 403) รหัสผู้ส่งที่ผ่านการตรวจสอบสิทธิ์แล้วแตกต่างจากรหัสผู้ส่งสำหรับโทเค็นการลงทะเบียน โทเค็นการลงทะเบียนจะเชื่อมโยงกับกลุ่มผู้ส่งบางกลุ่ม เมื่อแอปไคลเอ็นต์ลงทะเบียนสำหรับ FCM แอปต้องระบุผู้ส่งที่ได้รับอนุญาตให้ส่งข้อความ คุณควรใช้รหัสผู้ส่งรหัสใดรหัสหนึ่งเมื่อส่งข้อความไปยังแอปไคลเอ็นต์ หากเปลี่ยนเป็นผู้ส่งรายอื่น โทเค็นการลงทะเบียนที่มีอยู่จะไม่ทำงาน
QUOTA_EXCEEDED (รหัสข้อผิดพลาด HTTP = 429) เกินขีดจำกัดการส่งสำหรับข้อความเป้าหมาย แสดงส่วนขยายประเภท google.rpc.QuotaFailure เพื่อระบุว่าเกินโควต้าใด ข้อผิดพลาดนี้อาจเกิดจากอัตราข้อความเกินโควต้า เกินโควต้าอัตราข้อความในอุปกรณ์ หรือเกินโควต้าอัตราข้อความของหัวข้อ
อัตราข้อความเกินขีดจำกัด: อัตราการส่งข้อความสูงเกินไป คุณต้องลดอัตราโดยรวมที่ส่งข้อความ ใช้ Exponential Backoff โดยหน่วงเวลาเริ่มต้นอย่างน้อย 1 นาทีเพื่อลองส่งข้อความที่ถูกปฏิเสธอีกครั้ง
เกินอัตราการส่งข้อความในอุปกรณ์: อัตราการรับส่งข้อความในอุปกรณ์ใดอุปกรณ์หนึ่งสูงเกินไป โปรดดูการจำกัดอัตราการส่งข้อความไว้ในอุปกรณ์เครื่องเดียว ลดจำนวนข้อความที่ส่งมายังอุปกรณ์นี้และใช้ Exponential Backoff เพื่อลองส่งอีกครั้ง
อัตราข้อความของหัวข้อเกินขีดจำกัด: อัตราการรับส่งข้อความของหัวข้อใดหัวข้อหนึ่งสูงเกินไป ลดจำนวนข้อความที่ส่งสำหรับหัวข้อนี้และใช้ Exponential Backoff โดยหน่วงเวลาเริ่มต้นอย่างน้อย 1 นาทีเพื่อเริ่มส่งอีกครั้ง
UNAVAILABLE (รหัสข้อผิดพลาด HTTP = 503) เซิร์ฟเวอร์ทำงานหนักเกินไป เซิร์ฟเวอร์ประมวลผลคำขอไม่ได้ทันเวลา ลองส่งคำขอเดิมอีกครั้ง แต่ต้องทำดังนี้
- ทำตามส่วนหัว Retry-After หากมีอยู่ในการตอบกลับจากเซิร์ฟเวอร์การเชื่อมต่อ FCM
- ใช้ Exponential Backoff ในกลไกการลองอีกครั้ง (เช่น หากคุณรอ 1 วินาทีก่อนลองอีกครั้งครั้งแรก ให้รออย่างน้อย 2 วินาทีก่อนถึงอีก 1 วินาที จากนั้นรอ 4 วินาที เป็นต้น) หากคุณส่งข้อความจำนวนมาก ให้พิจารณาใช้ Jitter โปรดดูข้อมูลเพิ่มเติมที่หัวข้อการจัดการการดำเนินการซ้ำ ผู้ส่งที่ทำให้เกิดปัญหามีความเสี่ยงที่จะถูกปฏิเสธ
INTERNAL (รหัสข้อผิดพลาด HTTP = 500) เกิดข้อผิดพลาดภายในที่ไม่ทราบสาเหตุ เซิร์ฟเวอร์พบข้อผิดพลาดขณะพยายามประมวลผลคำขอ คุณสามารถลองทำตามคำขอเดิมอีกครั้งโดยทำตามคำแนะนำในการจัดการการดำเนินการซ้ำ หากข้อผิดพลาดยังคงอยู่ โปรดติดต่อทีมสนับสนุนของ Firebase
THIRD_PARTY_AUTH_ERROR (รหัสข้อผิดพลาด HTTP = 401) ใบรับรอง APN หรือคีย์การตรวจสอบสิทธิ์พุชจากเว็บไม่ถูกต้องหรือขาดหายไป ไม่สามารถส่งข้อความที่กำหนดเป้าหมายไปยังอุปกรณ์ iOS หรือการลงทะเบียนพุชในเว็บ ตรวจสอบความถูกต้องของข้อมูลเข้าสู่ระบบสำหรับการพัฒนาและข้อมูลที่ใช้งานจริง

รหัสข้อผิดพลาดของผู้ดูแลระบบ

ตารางต่อไปนี้แสดงรหัสข้อผิดพลาด FCM API ของผู้ดูแลระบบ Firebase และคำอธิบาย รวมถึงขั้นตอนการแก้ปัญหาที่แนะนำ

รหัสข้อผิดพลาด คำอธิบายและขั้นตอนการแก้ปัญหา
messaging/invalid-argument มีการระบุอาร์กิวเมนต์ที่ไม่ถูกต้องในเมธอด FCM ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม
messaging/invalid-recipient ผู้รับข้อความที่ต้องการไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม
messaging/invalid-payload ระบุออบเจ็กต์เพย์โหลดข้อความที่ไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม
messaging/invalid-data-payload-key เพย์โหลดข้อความข้อมูลมีคีย์ที่ไม่ถูกต้อง ดูเอกสารอ้างอิงสำหรับ DataMessagePayload สำหรับคีย์ที่จำกัด
messaging/payload-size-limit-exceeded เพย์โหลดของข้อความที่ระบุเกินขีดจำกัดขนาด FCM ข้อความส่วนใหญ่มีขีดจำกัดอยู่ที่ 4,096 ไบต์ ขีดจำกัดสำหรับข้อความที่ส่งไปยังหัวข้อคือ 2048 ไบต์ ขนาดเพย์โหลดทั้งหมดจะรวมทั้งคีย์และค่า
messaging/invalid-options ระบุออบเจ็กต์ตัวเลือกข้อความที่ไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม
messaging/invalid-registration-token ระบุโทเค็นการลงทะเบียนไม่ถูกต้อง ตรวจสอบว่าตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนด้วย FCM อย่าตัดหรือเพิ่มอักขระอื่นๆ ลงในข้อความ
messaging/registration-token-not-registered โทเค็นการลงทะเบียนที่ระบุไม่ได้ลงทะเบียน โทเค็นการลงทะเบียนที่ถูกต้องก่อนหน้านี้อาจถูกยกเลิกการลงทะเบียนด้วยเหตุผลหลายประการ เช่น
  • แอปไคลเอ็นต์ยกเลิกการลงทะเบียนออกจาก FCM
  • แอปไคลเอ็นต์ถูกยกเลิกการลงทะเบียนโดยอัตโนมัติ เหตุการณ์นี้อาจเกิดขึ้นได้หากผู้ใช้ถอนการติดตั้งแอปพลิเคชัน หรือในกรณีที่บริการความคิดเห็น APNs รายงานว่าโทเค็น APN ไม่ถูกต้องในแพลตฟอร์มของ Apple
  • โทเค็นการลงทะเบียนหมดอายุแล้ว ตัวอย่างเช่น Google อาจตัดสินใจรีเฟรชโทเค็นการลงทะเบียน หรือโทเค็น APN อาจหมดอายุสำหรับอุปกรณ์ Apple
  • อัปเดตแอปไคลเอ็นต์แล้ว แต่ไม่ได้กำหนดค่าเวอร์ชันใหม่ให้รับข้อความ
สำหรับทุกกรณีเหล่านี้ ให้นำโทเค็นการลงทะเบียนนี้ออกและหยุดใช้โทเค็นเพื่อส่งข้อความ
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 ไม่ได้เนื่องจากไม่ได้อัปโหลดใบรับรอง SSL ของ APN ที่จำเป็นหรือใบรับรองหมดอายุแล้ว ตรวจสอบความถูกต้องของใบรับรองการพัฒนาและใบรับรองเวอร์ชันที่ใช้งานจริง
messaging/mismatched-credential ข้อมูลเข้าสู่ระบบที่ใช้ตรวจสอบสิทธิ์ SDK นี้ไม่มีสิทธิ์ส่งข้อความไปยังอุปกรณ์ที่เกี่ยวข้องกับโทเค็นการลงทะเบียนที่ให้ไว้ ตรวจสอบว่าทั้งข้อมูลเข้าสู่ระบบและโทเค็นการลงทะเบียนเป็นของโปรเจ็กต์ Firebase เดียวกัน โปรดดูเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Firebase Admin SDK ที่เพิ่ม Firebase ลงในแอป
messaging/authentication-error SDK ตรวจสอบสิทธิ์เซิร์ฟเวอร์ FCM ไม่ได้ ตรวจสอบว่าคุณตรวจสอบสิทธิ์ Firebase Admin SDK ด้วยข้อมูลเข้าสู่ระบบซึ่งมีสิทธิ์ที่เหมาะสมในการส่งข้อความ FCM โปรดดูเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Firebase Admin SDK ที่เพิ่ม Firebase ลงในแอป
messaging/server-unavailable เซิร์ฟเวอร์ FCM ไม่สามารถประมวลผลคำขอได้ทันเวลา คุณควรลองส่งคำขอเดิมอีกครั้ง แต่ต้องทำดังนี้
  • ใช้ส่วนหัว Retry-After หากมีอยู่ในการตอบสนองจากเซิร์ฟเวอร์การเชื่อมต่อ FCM
  • ใช้ Exponential Backoff ในกลไกการลองอีกครั้ง เช่น หากคุณรอ 1 วินาทีก่อนลองอีกครั้งครั้งแรก ให้รออย่างน้อย 2 วินาทีก่อนครั้งต่อไป และ 4 วินาที และอื่นๆ หากคุณส่งข้อความหลายข้อความ ให้หน่วงเวลาแต่ละข้อความไว้อย่างอิสระด้วยจำนวนเงินเพิ่มเติมแบบสุ่ม เพื่อจะได้ไม่ต้องส่งคำขอใหม่สำหรับข้อความทั้งหมดพร้อมกัน
ผู้ส่งที่ทำให้เกิดปัญหามีความเสี่ยงที่จะถูกขึ้นบัญชีดำ
messaging/internal-error เซิร์ฟเวอร์ FCM พบข้อผิดพลาดขณะพยายามประมวลผลคำขอ คุณจะลองส่งคำขอเดียวกันอีกครั้งได้โดยทำตามข้อกำหนดที่แสดงในแถว messaging/server-unavailable ด้านบน หาก ข้อผิดพลาดยังคงอยู่ โปรดรายงานปัญหาไปยังช่องทางการสนับสนุนของ รายงานข้อบกพร่องของเรา
messaging/unknown-error แสดงผลข้อผิดพลาดที่ไม่รู้จักเกี่ยวกับเซิร์ฟเวอร์ ดูรายละเอียดเพิ่มเติมได้จากการตอบกลับของเซิร์ฟเวอร์ข้อมูลดิบในข้อความแสดงข้อผิดพลาด หากคุณได้รับข้อผิดพลาดนี้ โปรดรายงานข้อความแสดงข้อผิดพลาดแบบเต็มไปยังช่องทางการสนับสนุนรายงานข้อบกพร่องของเรา

ส่งข้อความโดยใช้โปรโตคอลเซิร์ฟเวอร์แอปเดิม

หากคุณใช้โปรโตคอลเดิมอยู่ ให้สร้างคำขอข้อความตามที่แสดงในส่วนนี้ โปรดทราบว่าหากคุณส่งไปยังหลายแพลตฟอร์มผ่าน 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

คุณสามารถใส่หัวข้อในนิพจน์ตามเงื่อนไขได้สูงสุด 5 หัวข้อ และใช้ได้ในวงเล็บ โอเปอเรเตอร์ที่รองรับ: &&, ||

คำขอ 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 รายการที่เชื่อมโยงอยู่ และส่งข้อความถึงทั้ง 2 โทเค็นได้สำเร็จ

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

นี่คือตัวอย่างของ "ความสำเร็จบางส่วน" notification_key มีโทเค็นการลงทะเบียน 3 รายการที่เชื่อมโยงอยู่ ข้อความส่งไปยังโทเค็นการลงทะเบียน 1 รายการเรียบร้อยแล้วเท่านั้น ข้อความตอบกลับจะแสดงโทเค็นการลงทะเบียน (registration_ids) ที่ไม่ได้รับข้อความ

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

เมื่อส่งข้อความไปยังโทเค็นการลงทะเบียนอย่างน้อย 1 รายการที่เชื่อมโยงกับ 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 ไปยังอุปกรณ์ทั้งหมดในกลุ่มไม่สำเร็จ เซิร์ฟเวอร์แอปจะได้รับการตอบสนองแบบ Nack

สำหรับรายการตัวเลือกข้อความทั้งหมด โปรดดูข้อมูลอ้างอิงสำหรับโปรโตคอลเซิร์ฟเวอร์การเชื่อมต่อที่คุณเลือก นั่นคือ HTTP หรือ XMPP

วิธีการส่งแบบเดิมของ Firebase Admin SDK

Firebase Admin Node.js SDK รองรับวิธีส่งข้อความ (FCM) ตาม API เซิร์ฟเวอร์ FCM เดิม เมธอดเหล่านี้ยอมรับอาร์กิวเมนต์ที่แตกต่างกัน ซึ่งต่างจากเมธอด send() คุณควรใช้เมธอด send() ทุกครั้งที่ทำได้ และใช้เฉพาะวิธีการที่อธิบายไว้ในหน้านี้เมื่อส่งข้อความไปยังอุปกรณ์แต่ละเครื่องหรือกลุ่มอุปกรณ์เท่านั้น

ส่งไปยังอุปกรณ์แต่ละเครื่อง

คุณส่งโทเค็นการลงทะเบียนไปยังเมธอด sendToDevice() เพื่อส่งข้อความไปยังอุปกรณ์นั้นได้โดยทำดังนี้

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

นอกจากนี้เมธอด sendToDevice() ยังส่งข้อความ multicast (ซึ่งก็คือข้อความไปยังอุปกรณ์หลายเครื่อง) ได้โดยการส่งอาร์เรย์ของโทเค็นการลงทะเบียนแทนที่จะส่งเพียงโทเค็นการลงทะเบียนรายการเดียว ดังนี้

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

เมธอด sendToDevice() จะแสดงผลสัญญาที่ได้รับการแก้ไขด้วยออบเจ็กต์ MessagingDevicesResponse ที่มีการตอบสนองจาก FCM ประเภทการแสดงผลจะมีรูปแบบเดียวกันเมื่อส่งโทเค็นการลงทะเบียนรายการเดียวหรืออาร์เรย์ของโทเค็นการลงทะเบียน

ในบางกรณี เช่น ข้อผิดพลาดในการตรวจสอบสิทธิ์หรือการจำกัดอัตรา อาจทำให้ระบบประมวลผลข้อความทั้งหมดไม่สำเร็จ ในกรณีเหล่านี้ คำสัญญาที่ sendToDevice() ส่งคืนจะถูกปฏิเสธโดยมีข้อผิดพลาด ดูรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ปัญหาได้ที่ข้อผิดพลาดของ Admin FCM API

ส่งไปยังกลุ่มอุปกรณ์

เมธอด sendToDeviceGroup() ช่วยให้คุณส่งข้อความไปยังกลุ่มอุปกรณ์ได้โดยการระบุคีย์การแจ้งเตือนสำหรับกลุ่มอุปกรณ์นั้น ดังนี้

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

เมธอด sendToDeviceGroup() จะแสดงผลสัญญาที่ได้รับการแก้ไขด้วยออบเจ็กต์ MessagingDevicesResponse ที่มีการตอบสนองจาก FCM

ในบางกรณี เช่น ข้อผิดพลาดในการตรวจสอบสิทธิ์หรือการจำกัดอัตรา อาจทำให้ระบบประมวลผลข้อความทั้งหมดไม่สำเร็จ ในกรณีเหล่านี้ คำสัญญาที่ sendToDeviceGroup() ส่งคืนจะถูกปฏิเสธโดยมีข้อผิดพลาด ดูรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ปัญหาได้ที่ข้อผิดพลาดของ Admin FCM API

การกำหนดเพย์โหลดของข้อความ

วิธีการข้างต้นที่อิงตามโปรโตคอลเดิมของ FCM ยอมรับเพย์โหลดข้อความเป็นอาร์กิวเมนต์ที่ 2 และรองรับทั้งข้อความการแจ้งเตือนและข้อความ คุณระบุประเภทข้อความประเภทใดประเภทหนึ่งหรือทั้ง 2 ประเภทได้โดยสร้างออบเจ็กต์ด้วยคีย์ 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 ชั่วโมง

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

ดูรายการตัวเลือกที่ใช้ได้ทั้งหมดในเอกสารอ้างอิงสำหรับ MessagingOptions