Dựa trên mô hình xuất bản/đăng ký, tính năng nhắn tin theo chủ đề FCM cho phép bạn gửi một thông báo đến nhiều thiết bị đã chọn nhận 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à 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 thuỷ triều tại địa phương có thể chọn nhận thông báo về chủ đề "cảnh báo dòng thuỷ triều" và nhận thông báo về điều kiện đánh bắt cá nước mặn tối ưu ở những khu vực cụ thể. 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ủ đề:
- Nhắn tin 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.
- Thông báo theo chủ đề được tối ưu hoá cho thông lượng thay vì độ trễ. Để gửi nhanh chóng và an toàn đến các thiết bị riêng lẻ hoặc 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 những trường hợp sử dụng đó.
- Tính năng nhắn tin theo chủ đề hỗ trợ số lượng kênh đăng ký không giới hạn cho mỗi chủ đề. Tuy nhiên, FCM áp dụng giới hạn ở những khu vực sau:
- Một phiên bản ứng dụng có thể đăng ký tối đa 2.000 chủ đề.
- Nếu bạn đang sử dụng tính năng nhập hàng loạt để đăng ký các thực thể ứng dụng, thì mỗi yêu cầu sẽ bị giới hạn ở 1.000 thực thể ứng dụng.
- Tần suất đăng ký mới bị giới hạn theo tốc độ 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 một phản hồi
429 RESOURCE_EXHAUSTED
("vượt quá hạn mức"). Thử lại với thời gian đợi luỹ thừa.
Đăng ký ứng dụng khách vào một chủ đề
Bạn có thể truyền danh sách mã thông báo đăng ký đến phương thức đăng ký Firebase Admin SDK để đăng ký các thiết bị tương ứng vào 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')
Tìm
// 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')
Tìm
// 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()
và unsubscribeFromTopic()
tạo ra một đối tượng chứa phản hồi từ FCM. Kiểu 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 (lỗi xác thực, 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. Để 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 FCM quản trị.
Nhận và xử lý thông báo theo chủ đề
FCM gửi thông báo theo chủ đề theo cách tương tự như các thông báo khác ở hạ lưu. Cách xử lý thông báo trên ứng dụng sẽ phụ thuộc vào trạng thái nền trước/nền sau của trang web và các yếu tố khác được mô tả trong phần này.
Hành vi của thông báo sẽ khác nhau tuỳ thuộc vào việc trang ở nền trước (có tiêu điểm) hay ở nền sau, bị ẩn sau các thẻ khác hoặc hoàn toàn bị đóng. Trong mọi trường hợp, trang phải xử lý lệnh gọi lại onMessage
, nhưng trong các trường hợp ở chế độ nền, bạn cũng có thể cần xử lý onBackgroundMessage
hoặc định cấu hình thông báo hiển thị để cho phép người dùng đưa ứng dụng web của bạn vào nền trước.
Trạng thái ứng dụng | Thông báo | Dữ liệu | Cả hai |
---|---|---|---|
Màu nổi | onMessage |
onMessage |
onMessage |
Nền (trình chạy dịch vụ) | onBackgroundMessage (thông báo hiển thị tự động xuất hiện) |
onBackgroundMessage |
onBackgroundMessage (thông báo hiển thị tự động xuất hiện) |
Xử lý thông báo khi ứng dụng web của bạn đang chạy trên nền trước
Để nhận được sự kiện onMessage
, ứng dụng của bạn phải xác định trình chạy dịch vụ nhắn tin Firebase trong firebase-messaging-sw.js
.
Ngoài ra, bạn có thể cung cấp một worker dịch vụ hiện có cho SDK thông qua getToken(): Promise<string>
.
Web
import { initializeApp } from "firebase/app"; import { getMessaging } from "firebase/messaging/sw"; // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object const firebaseApp = initializeApp({ apiKey: 'api-key', authDomain: 'project-id.firebaseapp.com', databaseURL: 'https://project-id.firebaseio.com', projectId: 'project-id', storageBucket: 'project-id.appspot.com', messagingSenderId: 'sender-id', appId: 'app-id', measurementId: 'G-measurement-id', }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = getMessaging(firebaseApp);
Web
// Give the service worker access to Firebase Messaging. // Note that you can only use Firebase Messaging here. Other Firebase libraries // are not available in the service worker. // Replace 10.13.2 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js'); // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object firebase.initializeApp({ apiKey: 'api-key', authDomain: 'project-id.firebaseapp.com', databaseURL: 'https://project-id.firebaseio.com', projectId: 'project-id', storageBucket: 'project-id.appspot.com', messagingSenderId: 'sender-id', appId: 'app-id', measurementId: 'G-measurement-id', }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging();
Khi ứng dụng của bạn ở nền trước (người dùng hiện đang xem trang web của bạn), bạn có thể nhận dữ liệu và tải trọng thông báo trực tiếp trong trang.
Web
// Handle incoming messages. Called when: // - a message is received while the app has focus // - the user clicks on an app notification created by a service worker // `messaging.onBackgroundMessage` handler. import { getMessaging, onMessage } from "firebase/messaging"; const messaging = getMessaging(); onMessage(messaging, (payload) => { console.log('Message received. ', payload); // ... });
Web
// Handle incoming messages. Called when: // - a message is received while the app has focus // - the user clicks on an app notification created by a service worker // `messaging.onBackgroundMessage` handler. messaging.onMessage((payload) => { console.log('Message received. ', payload); // ... });
Xử lý tin nhắn khi ứng dụng web của bạn ở chế độ nền
Tất cả thông báo nhận được trong lúc ứng dụng đang chạy trong nền sẽ kích hoạt một thông báo hiển thị trong trình duyệt. Bạn có thể chỉ định các lựa chọn cho thông báo này, chẳng hạn như tiêu đề hoặc thao tác khi nhấp, trong yêu cầu gửi từ máy chủ ứng dụng hoặc bằng cách sử dụng logic của service worker trên máy khách.
Thiết lập các lựa chọn thông báo trong yêu cầu gửi
Đối với thông báo được gửi từ máy chủ ứng dụng, API JavaScript FCM hỗ trợ khoá fcm_options.link
. Thông thường, tham số này được đặt thành một trang trong ứng dụng web của bạn:
https://fcm.googleapis.com//v1/projects/<YOUR-PROJECT-ID>/messages:send
Content-Type: application/json
Authorization: bearer <YOUR-ACCESS-TOKEN>
{
"message": {
"topic": "matchday",
"notification": {
"title": "Background Message Title",
"body": "Background message body"
},
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
}
Nếu giá trị đường liên kết trỏ đến một trang đã mở trong thẻ trình duyệt, thì thao tác nhấp vào thông báo sẽ đưa thẻ đó lên nền trước. Nếu trang chưa mở, thao tác nhấp vào thông báo sẽ mở trang trong một thẻ mới.
Vì thông báo dữ liệu không hỗ trợ fcm_options.link
, bạn nên thêm tải trọng thông báo vào tất cả thông báo dữ liệu. Ngoài ra, bạn có thể xử lý thông báo bằng trình chạy dịch vụ.
Để biết nội dung giải thích về sự khác biệt giữa thông báo và thông báo dữ liệu, hãy xem phần Các loại thông báo.
Đặt các lựa chọn thông báo trong worker dịch vụ
Đối với thông báo dữ liệu, bạn có thể đặt các lựa chọn thông báo trong worker dịch vụ. Trước tiên, hãy khởi động ứng dụng của bạn trong worker dịch vụ:
Web
import { initializeApp } from "firebase/app"; import { getMessaging } from "firebase/messaging/sw"; // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object const firebaseApp = initializeApp({ apiKey: 'api-key', authDomain: 'project-id.firebaseapp.com', databaseURL: 'https://project-id.firebaseio.com', projectId: 'project-id', storageBucket: 'project-id.appspot.com', messagingSenderId: 'sender-id', appId: 'app-id', measurementId: 'G-measurement-id', }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = getMessaging(firebaseApp);
Web
// Give the service worker access to Firebase Messaging. // Note that you can only use Firebase Messaging here. Other Firebase libraries // are not available in the service worker. // Replace 10.13.2 with latest version of the Firebase JS SDK. importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js'); // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object firebase.initializeApp({ apiKey: 'api-key', authDomain: 'project-id.firebaseapp.com', databaseURL: 'https://project-id.firebaseio.com', projectId: 'project-id', storageBucket: 'project-id.appspot.com', messagingSenderId: 'sender-id', appId: 'app-id', measurementId: 'G-measurement-id', }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging();
Để đặt các lựa chọn, hãy gọi onBackgroundMessage
trong firebase-messaging-sw.js
.
Trong ví dụ này, chúng ta tạo một thông báo có các trường tiêu đề, nội dung và biểu tượng.
Web
import { getMessaging } from "firebase/messaging/sw"; import { onBackgroundMessage } from "firebase/messaging/sw"; const messaging = getMessaging(); onBackgroundMessage(messaging, (payload) => { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' }; self.registration.showNotification(notificationTitle, notificationOptions); });
Web
messaging.onBackgroundMessage((payload) => { console.log( '[firebase-messaging-sw.js] Received background message ', payload ); // Customize notification here const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' }; self.registration.showNotification(notificationTitle, notificationOptions); });
Tạo yêu cầu gửi
Sau khi tạo một chủ đề, bằng cách đăng ký các phiên bản ứng dụng khách vào chủ đề ở phía ứng dụng khách hoặc thông qua API máy chủ, bạn có thể gửi thông báo đến 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ủ và FCM để biết thông tin quan trọng về bối cảnh và cách thiết lập.
Trong logic gửi ở phần phụ trợ, hãy chỉ định tên chủ đề mong muốn như minh hoạ:
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)
Tìm
// 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 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 những thiết bị đã đăng ký TopicA
và TopicB
hoặc TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM trước tiên 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ý một chủ đề bất kỳ sẽ không nhận được thông báo. Tương tự, người dùng không đăng ký TopicA
sẽ không nhận được thông báo. Các tổ hợp này sẽ nhận được:
TopicA
vàTopicB
TopicA
vàTopicC
Bạn có thể thêm tối đa 5 chủ đề vào biểu thức có điều kiện.
Để 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)
Tìm
// 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
Các bước tiếp theo
- Tìm hiểu thêm về cách khác để gửi đến nhiều thiết bị – gửi tin nhắn cho nhóm thiết bị