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

คุณใช้โปรโตคอลเซิร์ฟเวอร์แอป FCM และ 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

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

Admin 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 จะตั้งค่าเป็น date การหมดอายุ

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

ตัวอย่างนี้ส่งคำขอส่งชื่อการแจ้งเตือนและเนื้อหาทั่วไปไปยังทุกแพลตฟอร์ม แต่จะส่งการลบล้างเฉพาะแพลตฟอร์มบางอย่างไปยังอุปกรณ์ 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 สำหรับ HTTP v1 API

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

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

รหัสข้อผิดพลาด ขั้นตอนคำอธิบายและการแก้ปัญหา
UNSPECIFIED_ERROR ไม่มีข้อมูลเพิ่มเติมเกี่ยวกับข้อผิดพลาดนี้ ไม่มี
INVALID_ARGUMENT (รหัสข้อผิดพลาด HTTP = 400) พารามิเตอร์คำขอไม่ถูกต้อง ส่วนขยายประเภท google.rpc.BadRequest จะแสดงผลเพื่อระบุช่องที่ไม่ถูกต้อง สาเหตุที่เป็นไปได้ ได้แก่ การลงทะเบียนที่ไม่ถูกต้อง, ชื่อแพ็กเกจไม่ถูกต้อง, ข้อความใหญ่เกินไป, คีย์ข้อมูลไม่ถูกต้อง, TTL ไม่ถูกต้อง หรือพารามิเตอร์อื่นๆ ไม่ถูกต้อง
การลงทะเบียนไม่ถูกต้อง: ตรวจสอบรูปแบบของโทเค็นการลงทะเบียนที่คุณส่งไปยังเซิร์ฟเวอร์ ตรวจสอบว่าโทเค็นดังกล่าวตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนกับ FCM อย่าตัดโทเค็นหรือเพิ่มอักขระอื่น
ชื่อแพ็กเกจไม่ถูกต้อง: ตรวจสอบว่าส่งข้อความไปยังโทเค็นการลงทะเบียนที่มีชื่อแพ็กเกจตรงกับค่าที่ส่งไปในคำขอ
ข้อความใหญ่เกินไป: ตรวจสอบว่าขนาดข้อมูลเพย์โหลดทั้งหมดที่รวมอยู่ในข้อความมีขนาดไม่เกิน 4, 096 ไบต์สําหรับข้อความส่วนใหญ่ หรือ 2048 ไบต์ในกรณีที่ส่งข้อความไปยังหัวข้อ ซึ่งจะมีทั้งคีย์และค่า
คีย์ข้อมูลไม่ถูกต้อง: ตรวจสอบว่าข้อมูลเพย์โหลดไม่มีคีย์ (เช่น from หรือ gcm หรือค่าใดๆ ที่นำหน้าด้วย google) ที่ FCM ใช้ภายใน โปรดทราบว่า FCM มีการใช้คำบางคำ (เช่น collapse_key) ด้วยแต่อนุญาตให้ใช้ในเพย์โหลด ซึ่งในกรณีนี้ค่าเพย์โหลดจะถูกแทนที่โดยค่า FCM
TTL ไม่ถูกต้อง: ตรวจสอบว่าค่าที่ใช้ใน ttl เป็นจำนวนเต็มที่แสดงระยะเวลาเป็นวินาทีระหว่าง 0 ถึง 2,419,200 (4 สัปดาห์)
พารามิเตอร์ไม่ถูกต้อง: ตรวจสอบว่าพารามิเตอร์ที่ระบุมีชื่อและประเภทที่ถูกต้อง
UNREGISTERED (รหัสข้อผิดพลาด HTTP = 404) อินสแตนซ์ของแอปถูกยกเลิกการลงทะเบียนจาก FCM โดยปกติแล้วหมายความว่าโทเค็นที่ใช้จะใช้งานไม่ได้อีกต่อไปและจะต้องใช้โทเค็นใหม่ ข้อผิดพลาดนี้อาจเกิดจากโทเค็นการลงทะเบียนขาดหายไปหรือโทเค็นที่ไม่ได้ลงทะเบียน
ไม่มีการลงทะเบียน: หากเป้าหมายของข้อความคือค่า token ให้ตรวจสอบว่าคำขอมีโทเค็นการลงทะเบียน
ไม่ได้ลงทะเบียน: โทเค็นการลงทะเบียนที่มีอยู่อาจใช้ไม่ได้ในบางสถานการณ์ เช่น
- หากแอปไคลเอ็นต์ยกเลิกการลงทะเบียนกับ FCM
- ในกรณีที่แอปไคลเอ็นต์ยกเลิกการลงทะเบียนโดยอัตโนมัติ ซึ่งอาจเกิดขึ้นได้หากผู้ใช้ถอนการติดตั้งแอปพลิเคชัน เช่น ใน iOS หากบริการฟีดแบ็ก APN รายงานว่าโทเค็น APN ไม่ถูกต้อง
- หากโทเค็นการลงทะเบียนหมดอายุ (เช่น Google อาจตัดสินใจรีเฟรชโทเค็นการลงทะเบียน หรือโทเค็น APNs หมดอายุสําหรับอุปกรณ์ iOS)
- หากอัปเดตแอปไคลเอ็นต์แล้ว แต่ไม่ได้กำหนดค่าเวอร์ชันใหม่ให้รับข้อความ
สำหรับทุกกรณี ให้นำโทเค็นการลงทะเบียนนี้ออกจากเซิร์ฟเวอร์แอปและหยุดใช้ในการส่งข้อความ
SENDER_ID_MISMATCH (รหัสข้อผิดพลาด HTTP = 403) รหัสผู้ส่งที่ได้รับการตรวจสอบสิทธิ์จะแตกต่างจากรหัสผู้ส่งสำหรับโทเค็นการลงทะเบียน โทเค็นการลงทะเบียนจะผูกกับกลุ่มผู้ส่งบางกลุ่ม เมื่อแอปไคลเอ็นต์ลงทะเบียนสำหรับ FCM แอปต้องระบุผู้ส่งที่ได้รับอนุญาตให้ส่งข้อความ คุณควรใช้รหัสผู้ส่งรหัสใดรหัสหนึ่งดังกล่าวเมื่อส่งข้อความไปยังแอปไคลเอ็นต์ หากเปลี่ยนเป็นผู้ส่งรายอื่น โทเค็นการลงทะเบียนที่มีอยู่จะไม่ทำงาน
QUOTA_EXCEEDED (รหัสข้อผิดพลาด HTTP = 429) เกินขีดจำกัดการส่งสำหรับเป้าหมายข้อความ ส่วนขยายประเภท google.rpc.QuotaFailure จะแสดงผลเพื่อระบุโควต้าที่เกินโควต้า ข้อผิดพลาดนี้อาจเกิดจากการเกินโควต้าอัตราข้อความ เกินโควต้าอัตราข้อความในอุปกรณ์ หรือเกินโควต้าอัตราข้อความหัวข้อ
เกินอัตราการส่งข้อความ: อัตราการส่งข้อความสูงเกินไป คุณต้องลดอัตราโดยรวมของการส่งข้อความ ใช้ Exponential Backoff โดยมีความล่าช้าเริ่มต้นอย่างน้อย 1 นาทีเพื่อลองส่งข้อความที่ถูกปฏิเสธอีกครั้ง
เกินอัตราการส่งข้อความในอุปกรณ์: อัตราการส่งข้อความไปยังอุปกรณ์เครื่องใดเครื่องหนึ่งสูงเกินไป โปรดดูขีดจำกัดอัตราคำขอส่งข้อความสำหรับอุปกรณ์ 1 เครื่อง โปรดลดจำนวนข้อความที่ส่งไปยังอุปกรณ์นี้และใช้ Exponential Backoff เพื่อลองส่งอีกครั้ง
อัตราการส่งข้อความหัวข้อ: อัตราการส่งข้อความไปยังหัวข้อใดหัวข้อหนึ่งสูงเกินไป ลดจำนวนข้อความที่ส่งสำหรับหัวข้อนี้และใช้ Exponential Backoff โดยมีความล่าช้าเริ่มต้นอย่างน้อย 1 นาทีเพื่อลองส่งอีกครั้ง
UNAVAILABLE (รหัสข้อผิดพลาด HTTP = 503) เซิร์ฟเวอร์ทำงานหนักเกินไป เซิร์ฟเวอร์ประมวลผลคำขอได้ไม่ทันเวลา ลองส่งคำขอเดิมอีกครั้ง แต่คุณต้องดำเนินการต่อไปนี้
- ใช้ส่วนหัว Retry-After หากคำขอนั้นรวมอยู่ในการตอบกลับจากเซิร์ฟเวอร์การเชื่อมต่อ FCM
- ใช้ Exponential Backoff ในกลไกการลองใหม่ (เช่น หากคุณรอ 1 วินาทีก่อนลองอีกครั้งครั้งแรก ให้รออย่างน้อย 2 วินาทีก่อนเกมถัดไป จากนั้น 4 วินาที แล้วทำแบบนี้ไปเรื่อยๆ) หากคุณส่งหลายข้อความ ให้พิจารณาใช้การกระตุก โปรดดูข้อมูลเพิ่มเติมที่หัวข้อการจัดการการลองใหม่ ผู้ส่งที่ทำให้เกิดปัญหามีความเสี่ยงที่จะถูกปฏิเสธเป็นรายชื่อผู้ส่ง
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 ไบต์ ขีดจำกัดสำหรับข้อความที่ส่งไปยังหัวข้อ คือ 2,048 ไบต์ ขนาดเพย์โหลดทั้งหมดจะมีทั้งคีย์และค่า
messaging/invalid-options ระบุออบเจ็กต์ตัวเลือกข้อความที่ไม่ถูกต้อง ข้อความแสดงข้อผิดพลาดควรมีข้อมูลเพิ่มเติม
messaging/invalid-registration-token ระบุโทเค็นการลงทะเบียนไม่ถูกต้อง ตรวจสอบว่าโทเค็นดังกล่าวตรงกับโทเค็นการลงทะเบียนที่แอปไคลเอ็นต์ได้รับจากการลงทะเบียนกับ FCM อย่าตัดหรือเพิ่มอักขระอื่น
messaging/registration-token-not-registered โทเค็นการลงทะเบียนที่ระบุไม่ได้ลงทะเบียน โทเค็นการลงทะเบียนที่ถูกต้องก่อนหน้านี้อาจยกเลิกการลงทะเบียนได้ด้วยเหตุผลหลายประการ เช่น
  • แอปไคลเอ็นต์ยกเลิกการลงทะเบียนตัวเองจาก FCM
  • แอปไคลเอ็นต์ถูกยกเลิกการลงทะเบียนโดยอัตโนมัติ กรณีนี้อาจเกิดขึ้นหากผู้ใช้ถอนการติดตั้งแอปพลิเคชัน หรือในแพลตฟอร์มของ Apple หากบริการ APNs Feedback Service รายงานว่าโทเค็น APNs ไม่ถูกต้อง
  • โทเค็นการลงทะเบียนหมดอายุแล้ว เช่น 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 เดียวกัน โปรดดูเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Admin SDK ของ Firebase ที่เพิ่ม Firebase ลงในแอป
messaging/authentication-error SDK ตรวจสอบสิทธิ์กับเซิร์ฟเวอร์ FCM ไม่ได้ ตรวจสอบว่าคุณตรวจสอบสิทธิ์ Firebase Admin SDK ด้วยข้อมูลเข้าสู่ระบบที่มีสิทธิ์ที่เหมาะสมในการส่งข้อความ FCM โปรดดูเอกสารเกี่ยวกับวิธีตรวจสอบสิทธิ์ Admin SDK ของ Firebase ที่เพิ่ม 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 จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจะประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข้อมูลในหัวข้อเดียวไม่ได้รับข้อความ และในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครรับข้อมูลหัวข้อ A ก็จะไม่ได้รับข้อความเช่นกัน ชุดค่าผสมเหล่านี้จะได้รับ:

  • หัวข้อ A และหัวข้อ B
  • หัวข้อ A และหัวข้อ C

คุณสามารถใส่หัวข้อได้สูงสุด 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 เดิม

คำขอ POST สำหรับ HTTP ของกลุ่มอุปกรณ์

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 ไม่สำเร็จ เซิร์ฟเวอร์ของแอปควรลองอีกครั้งโดยทำ Backoff ระหว่างการพยายามซ้ำ

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

Node.js SDK ของผู้ดูแลระบบ Firebase รองรับเมธอดสำหรับการส่งข้อความ (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