Gửi tin nhắn đến các chủ đề trên nền tảng Apple

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

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

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

  • Nhắn tin theo chủ đề phù hợp nhất với những nội dung như thời tiết hoặc thông tin công khai khác.
  • Thông báo theo chủ đề được tối ưu hóa về thông lượng thay vì độ trễ . Để gửi nhanh chóng, an toàn tới các thiết bị riêng lẻ hoặc nhóm thiết bị nhỏ, 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 tin nhắn tới nhiều thiết bị cho mỗi người dùng , hãy xem xét nhắn tin theo nhóm thiết bị cho các trường hợp sử dụng đó.
  • Tin nhắn theo chủ đề hỗ trợ đăng ký không giới hạn cho từng chủ đề. Tuy nhiên, FCM thực thi các giới hạn trong các lĩnh vực sau:
    • Một phiên bản ứng dụng có thể được đăng ký không quá 2000 chủ đề.
    • Nếu bạn đang sử dụng tính năng nhập hàng loạt để đăng ký phiên bản ứng dụng thì mỗi yêu cầu được giới hạn ở 1000 phiên bản ứng dụng.
    • Tần suất đăng ký mới bị giới hạn tỷ lệ cho mỗi dự án. Nếu bạn gửi quá nhiều 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 phản hồi 429 RESOURCE_EXHAUSTED ("vượt quá hạn ngạch"). Thử lại với thời gian chờ theo cấp số nhân.

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

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

Để đăng ký một chủ đề, hãy gọi phương thức đăng ký từ luồng chính của ứng dụng của bạn (FCM không an toàn cho luồng). Nếu yêu cầu đăng ký ban đầu không thành công, FCM sẽ tự động thử lại. Đối với trường hợp không thể hoàn thành đăng ký, đăng ký sẽ đưa ra một lỗi mà bạn có thể gặp trong trình xử lý hoàn thành như được hiển thị:

Nhanh

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

Mục tiêu-C

[[FIRMessaging messaging] subscribeToTopic:@"weather"
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to weather topic");
}];

Cuộc gọi này thực hiện một yêu cầu không đồng bộ tới phần phụ trợ FCM và đăng ký khách hàng theo chủ đề đã cho. Trước khi gọi subscribeToTopic:topic , hãy đảm bảo rằng phiên bản ứng dụng khách đã nhận được mã thông báo đăng ký thông qua lệnh gọi lại didReceiveRegistrationToken .

Mỗi khi ứng dụng khởi động, FCM đảm bảo rằng tất cả các chủ đề được yêu cầu đều đã được đăng ký. Để hủy đăng ký, hãy gọi unsubscribeFromTopic:topic và FCM hủy đăng ký chủ đề ở chế độ nền.

Quản lý đăng ký chủ đề trên máy chủ

SDK quản trị Firebase cho phép bạn thực hiện các tác vụ quản lý chủ đề cơ bản từ phía máy chủ. Với (các) mã thông báo đăng ký của họ, bạn có thể đăng ký và hủy đăng ký hàng loạt phiên bản ứng dụng khách bằ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ý ứng dụng khách cho một chủ đề mới (chủ đề chưa tồn tại cho dự án Firebase của bạn), một chủ đề mới có tên đó sẽ được tạo trong FCM và sau đó bất kỳ khách hàng nào cũng có thể đăng ký chủ đề đó.

Bạn có thể chuyển danh sách mã thông báo đăng ký sang phương thức đăng ký SDK quản trị Firebase để đăng ký các thiết bị tương ứng theo 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')

Đi

// 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 quản trị cũng cho phép bạn hủy đăng ký thiết bị khỏi một chủ đề bằng cách chuyển mã thông báo đăng ký sang 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')

Đi

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

Các phương thức subscribeToTopic()unsubscribeFromTopic() dẫn đến một đối tượng chứa phản hồi từ FCM. Kiể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 có lỗi (xác thực không thành công, mã thông báo hoặc chủ đề không hợp lệ, v.v.), các phương thức này sẽ dẫn đến lỗi. Để biết danh sách đầy đủ các mã lỗi, bao gồm mô tả và các bước giải quyết, hãy xem Lỗi API FCM của quản trị viên .

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

FCM gửi các thông điệp chủ đề theo cách tương tự như các thông điệp xuôi dòng khác.

Triển khai application(_:didReceiveRemoteNotification:fetchCompletionHandler:) như được hiển thị:

Nhanh

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

Mục tiêu-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Xây dựng yêu cầu gửi

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

Trong logic gửi của bạn ở phần phụ trợ, hãy chỉ định tên chủ đề mong muốn như được hiển thị:

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)

Đi

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

NGHỈ NGƠI

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 tin nhắn đến một tổ hợp các chủ đề, hãy chỉ định một điều kiện , đây là biểu thức boolean chỉ định các chủ đề đích. Ví dụ: điều kiện sau sẽ gửi tin nhắn đế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 đánh giá mọi điều kiện trong 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ý vào bất kỳ chủ đề nào sẽ không nhận được tin nhắn. Tương tự, người dùng không đăng ký TopicA sẽ không nhận được tin nhắn. Những kết hợp này nhận được nó:

  • TopicATopicB
  • TopicATopicC

Bạn có thể bao gồm tối đa năm chủ đề trong biểu thức điều kiện của mình.

Để 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)

Đi

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

NGHỈ NGƠI

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

Bước tiếp theo