Gửi thông báo đến các chủ đề trên Unity

Dựa trên mô hình phát hành/đăng ký, tính năng nhắn tin theo chủ đề FCM cho phép bạn gửi tin nhắn đến nhiều thiết bị đã chọn sử dụng một chủ đề cụ thể. Bạn soạn tin nhắn theo chủ đề khi cần và FCM sẽ xử lý việc định tuyến và phân phối tin nhắn một cách đáng tin cậy đến các thiết bị phù hợp.

Ví dụ: người dùng thủy triều cục bộ ứng dụng dự báo có thể chọn nhận "cảnh báo dòng thuỷ triều" chủ đề và nhận thông báo về điều kiện tối ưu cho hoạt động đánh bắt cá biển ở những khu vực nhất định. Người dùng ứng dụng thể thao có thể đăng ký nhận thông tin cập nhật tự động về tỷ số trực tiếp của các đội mà họ yêu thích.

Một số điều cần lưu ý về chủ đề:

  • Thông báo theo chủ đề phù hợp nhất với nội dung như thời tiết hoặc thông tin công khai khác.
  • Tin nhắn theo chủ đề được tối ưu hoá cho băng thông thay vì độ trễ. Để phân phối nhanh chóng và an toàn đến một thiết bị hoặc một nhóm nhỏ thiết bị, hãy nhắm mục tiêu tin nhắn đến mã thông báo đăng ký, chứ không phải chủ đề.
  • Nếu bạn cần gửi thông báo đến nhiều thiết bị cho mỗi người dùng, hãy cân nhắc nhắn tin theo nhóm thiết bị cho các trường hợp sử dụng đó.
  • Tính năng nhắn tin theo chủ đề hỗ trợ số lượng đăng ký không giới hạn cho mỗi chủ đề. Tuy nhiên, FCM thực thi các giới hạn trong những khu vực sau:
    • Một thực thể ứng dụng có thể đăng ký theo dõi không quá 2.000 chủ đề.
    • Nếu bạn đang sử dụng nhập hàng loạt đăng ký phiên bản ứng dụng, mỗi yêu cầu chỉ được có 1.000 phiên bản ứng dụng.
    • Tần suất của các gói thuê bao mới bị giới hạn tốc độ trên mỗi dự án. Nếu bạn gửi quá nhiều các yêu cầu đăng ký trong một khoảng thời gian ngắn, máy chủ FCM sẽ phản hồi bằng một Phản hồi 429 RESOURCE_EXHAUSTED ("vượt quá hạn mức"). Thử lại bằng thời gian đợi luỹ thừa.

Đăng ký ứng dụng khách cho một chủ đề

Để đăng ký một chủ đề, hãy gọi Firebase.Messaging.FirebaseMessaging.Subscribe từ ứng dụng của bạn. Thao tác này sẽ tạo một yêu cầu không đồng bộ đến FCM phụ trợ và đăng ký ứng dụng khách về chủ đề đã cho.

Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");

Nếu yêu cầu đăng ký ban đầu không thành công, FCM sẽ thử lại cho đến khi có thể đăng ký thành công chủ đề. Mỗi khi ứng dụng khởi động, FCM sẽ đảm bảo rằng tất cả các chủ đề được yêu cầu đều đã được đăng ký.

Để huỷ đăng ký, hãy gọi Firebase.Messaging.FirebaseMessaging.UnsubscribeFCM sẽ huỷ đăng ký chủ đề trong nền.

Quản lý gói thuê bao chủ đề trên máy chủ

Firebase Admin SDK cho phép bạn thực hiện các thao tác quản lý chủ đề cơ bản từ phía máy chủ. Sau khi đăng ký mã thông báo, bạn có thể đăng ký và huỷ đăng ký hàng loạt phiên bản ứng dụng khách bằng cách sử dụng logic máy chủ.

Bạn có thể đăng ký các phiên bản ứng dụng khách cho bất kỳ chủ đề hiện có nào, hoặc bạn có thể tạo một chủ đề mới. Khi bạn sử dụng API để đăng ký một ứng dụng khách cho một chủ đề mới (chưa có trong dự án Firebase của bạn), một chủ đề mới có tên đó sẽ được tạo trong FCM và sau đó, mọi ứng dụng khách đều có thể đăng ký chủ đề đó.

Bạn có thể chuyển danh sách mã thông báo đăng ký tới Firebase Admin SDK để đăng ký thiết bị tương ứng với một chủ đề:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Subscribe the devices corresponding to the registration tokens to the
// topic.
getMessaging().subscribeToTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully subscribed to topic:', response);
  })
  .catch((error) => {
    console.log('Error subscribing to topic:', error);
  });

Java

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Subscribe the devices corresponding to the registration tokens to the
// topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");

Python

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')

Tiến hành

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Subscribe the devices corresponding to the registration tokens to the
// topic.
response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were subscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Subscribe the devices corresponding to the registration tokens to the
// topic
var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");

API FCM dành cho quản trị viên cũng cho phép bạn huỷ đăng ký thiết bị khỏi một chủ đề bằng cách truyền mã thông báo đăng ký đến phương thức thích hợp:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
getMessaging().unsubscribeFromTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully unsubscribed from topic:', response);
  })
  .catch((error) => {
    console.log('Error unsubscribing from topic:', error);
  });

Java

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");

Python

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')

Tiến hành

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were unsubscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Unsubscribe the devices corresponding to the registration tokens from the
// topic
var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");

Phương thức subscribeToTopic()unsubscribeFromTopic() dẫn đến kết quả đối tượng chứa phản hồi từ FCM. Loại dữ liệu trả về có cùng định dạng bất kể số lượng mã thông báo đăng ký được chỉ định trong yêu cầu.

Trong trường hợp xảy ra lỗi (không xác thực được, mã thông báo hoặc chủ đề không hợp lệ, v.v.) thì các phương thức này dẫn đến lỗi. Để xem danh sách đầy đủ các mã lỗi, bao gồm cả nội dung mô tả và các bước giải quyết, hãy xem Lỗi API Quản trị FCM.

Nhận và xử lý tin nhắn theo chủ đề

FCM phân phối thông báo theo chủ đề giống như các thông báo hạ nguồn khác.

Bằng cách đăng ký sự kiện Firebase.Messaging.FirebaseMessaging.MessageReceived bạn có thể thực hiện hành động dựa trên tin nhắn đã nhận và xem dữ liệu tin nhắn.

Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;

...

public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e) {
  UnityEngine.Debug.Log("Received a new message");
  if (e.Message.From.Length > 0)
    UnityEngine.Debug.Log("from: " + e.Message.From);
  if (e.Message.Data.Count > 0) {
    UnityEngine.Debug.Log("data:");
    foreach (System.Collections.Generic.KeyValuePair iter in
             e.Message.Data) {
      UnityEngine.Debug.Log("  " + iter.Key + ": " + iter.Value);
    }
  }
}

Tạo yêu cầu gửi

Sau khi tạo một chủ đề, bạn có thể gửi thông báo đến chủ đề đó bằng cách đăng ký các thực thể ứng dụng khách cho chủ đề ở phía máy khách hoặc thông qua API máy chủ. Nếu đây là lần đầu tiên bạn tạo yêu cầu gửi cho FCM, hãy xem hướng dẫn về môi trường máy chủ của bạn và FCM cho thông tin quan trọng về nền tảng và chế độ thiết lập.

Trong logic gửi ở phần phụ trợ, hãy chỉ định tên chủ đề mong muốn như sau:

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)

Tiến hành

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

Kiến trúc chuyển trạng thái đại diện (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"
      }
   }
}

Lệnh 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

Để gửi thông báo đến một kết hợp các chủ đề, hãy chỉ định một điều kiện. Đây là một biểu thức boolean chỉ định các chủ đề mục tiêu. Ví dụ: điều kiện sau đây sẽ gửi thông báo đến các thiết bị đã đăng ký TopicATopicB hoặc TopicC:

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

Trước tiên, FCM sẽ đánh giá mọi điều kiện trong dấu ngoặc đơn, sau đó đánh giá biểu thức từ trái sang phải. Trong biểu thức trên, người dùng đã đăng ký bất kỳ chủ đề nào đều không nhận được thông báo. Tương tự, một người dùng không đăng ký TopicA không nhận được thông báo. Những cách kết hợp này nhận email:

  • TopicATopicB
  • TopicATopicC

Bạn có thể đưa tối đa 5 chủ đề vào biểu thức có điều kiện.

Cách gửi đến một điều kiện:

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)

Tiến hành

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

Kiến trúc chuyển trạng thái đại diện (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",
    }
  }
}

Lệnh 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