ارسال پیام به موضوعات در وب/جاوا اسکریپت

بر اساس مدل انتشار/اشتراک، پیام‌رسانی موضوعی FCM به شما امکان می‌دهد پیامی را به چندین دستگاه که در یک موضوع خاص شرکت کرده‌اند، ارسال کنید. شما پیام‌های موضوعی را در صورت نیاز می‌نویسید و FCM مسیریابی و ارسال پیام را به طور قابل اعتماد به دستگاه‌های مناسب انجام می‌دهد.

برای مثال، کاربران یک اپلیکیشن پیش‌بینی جزر و مد محلی می‌توانند در بخش «هشدارهای جریان‌های جزر و مدی» ثبت‌نام کنند و از شرایط مطلوب ماهیگیری در آب‌های شور در مناطق مشخص‌شده، اعلان دریافت کنند. کاربران یک اپلیکیشن ورزشی می‌توانند در به‌روزرسانی‌های خودکار نتایج زنده بازی تیم‌های مورد علاقه‌شان مشترک شوند.

نکاتی که باید در مورد موضوعات در نظر داشته باشید:

  • پیام‌رسانی موضوعی برای محتوایی مانند آب و هوا یا سایر اطلاعات عمومی مناسب‌تر است.
  • پیام‌های تاپیک به جای تأخیر، برای افزایش سرعت بهینه شده‌اند . برای تحویل سریع و ایمن به دستگاه‌های منفرد یا گروه‌های کوچکی از دستگاه‌ها، پیام‌ها را به توکن‌های ثبت‌نام هدایت کنید ، نه به تاپیک‌ها.
  • اگر نیاز دارید که برای هر کاربر به چندین دستگاه پیام ارسال کنید، برای این موارد استفاده ، پیام‌رسانی گروهی دستگاه را در نظر بگیرید.
  • پیام‌رسانی موضوعی از اشتراک‌های نامحدود برای هر موضوع پشتیبانی می‌کند. با این حال، FCM محدودیت‌هایی را در این زمینه‌ها اعمال می‌کند:
    • یک نمونه برنامه می‌تواند در حداکثر ۲۰۰۰ موضوع مشترک شود.
    • اگر از وارد کردن دسته‌ای برای اشتراک در نمونه‌های برنامه استفاده می‌کنید، هر درخواست به ۱۰۰۰ نمونه برنامه محدود می‌شود.
    • تعداد دفعات اشتراک‌های جدید برای هر پروژه محدود است. اگر در مدت زمان کوتاهی درخواست‌های اشتراک زیادی ارسال کنید، سرورهای FCM با پاسخ 429 RESOURCE_EXHAUSTED ("سهمیه از حد مجاز فراتر رفته") پاسخ می‌دهند. با backoff نمایی دوباره امتحان کنید.

برنامه کلاینت را در یک موضوع مشترک کنید

می‌توانید فهرستی از توکن‌های ثبت‌نام را به متد اشتراک Firebase Admin SDK ارسال کنید تا دستگاه‌های مربوطه در یک تاپیک ثبت‌نام شوند:

نود جی اس

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

جاوا

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

پایتون

# 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')

برو

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

سی شارپ

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

رابط برنامه‌نویسی نرم‌افزار مدیریت FCM همچنین به شما امکان می‌دهد با ارسال توکن‌های ثبت‌نام به متد مربوطه، اشتراک دستگاه‌ها را از یک تاپیک لغو کنید:

نود جی اس

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

جاوا

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

پایتون

# 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')

برو

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

سی شارپ

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

متدهای subscribeToTopic() و unsubscribeFromTopic() منجر به ایجاد یک شیء حاوی پاسخ از FCM می‌شوند. نوع بازگشتی صرف نظر از تعداد توکن‌های ثبت مشخص شده در درخواست، فرمت یکسانی دارد.

در صورت بروز خطا (عدم احراز هویت، توکن یا موضوع نامعتبر و غیره) این روش‌ها منجر به خطا می‌شوند. برای مشاهده لیست کامل کدهای خطا، شامل توضیحات و مراحل حل آنها، به خطاهای API مدیریت FCM مراجعه کنید.

دریافت و مدیریت پیام‌های موضوعی

FCM پیام‌های موضوعی را مانند سایر پیام‌های پایین‌دستی ارسال می‌کند. نحوه مدیریت پیام‌ها در کلاینت به وضعیت پیش‌زمینه/پس‌زمینه صفحه وب و سایر عواملی که در این بخش توضیح داده شده است، بستگی دارد.

رفتار پیام‌ها بسته به اینکه صفحه در پیش‌زمینه (دارای فوکوس) باشد، یا در پس‌زمینه، پنهان در پشت تب‌های دیگر یا کاملاً بسته، متفاوت است. در همه موارد، صفحه باید فراخوانی onMessage مدیریت کند، اما در موارد پس‌زمینه، ممکن است لازم باشد onBackgroundMessage نیز مدیریت کنید یا اعلان نمایش را پیکربندی کنید تا به کاربر اجازه دهد برنامه وب شما را به پیش‌زمینه بیاورد.

حالت برنامه اعلان داده‌ها هر دو
پیش‌زمینه onMessage onMessage onMessage
پیشینه (کارگر خدماتی) onBackgroundMessage (نمایش خودکار اعلان‌ها) onBackgroundMessage onBackgroundMessage (نمایش خودکار اعلان‌ها)

مدیریت پیام‌ها زمانی که برنامه وب شما در پیش‌زمینه است

برای دریافت رویداد onMessage ، برنامه شما باید سرویس دهنده پیام رسانی Firebase را در firebase-messaging-sw.js تعریف کند. همچنین می‌توانید یک سرویس دهنده موجود را از طریق getToken(): Promise<string> به SDK ارائه دهید.

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

وقتی برنامه شما در پیش‌زمینه است (کاربر در حال مشاهده صفحه وب شماست)، می‌توانید داده‌ها و اعلان‌های مهم را مستقیماً در صفحه دریافت کنید.

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

مدیریت پیام‌ها وقتی برنامه وب شما در پس‌زمینه است

تمام پیام‌های دریافتی در حالی که برنامه در پس‌زمینه است، یک اعلان نمایش در مرورگر ایجاد می‌کنند. می‌توانید گزینه‌هایی برای این اعلان، مانند عنوان یا اقدام کلیک، یا در درخواست ارسال از سرور برنامه خود یا با استفاده از منطق سرویس‌دهنده در کلاینت، مشخص کنید.

تنظیم گزینه‌های اعلان در درخواست ارسال

برای پیام‌های اعلان ارسالی از سرور برنامه، API جاوا اسکریپت FCM از کلید fcm_options.link پشتیبانی می‌کند. معمولاً این کلید روی یک صفحه در برنامه وب شما تنظیم می‌شود:

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

اگر مقدار لینک به صفحه‌ای اشاره کند که از قبل در یک تب مرورگر باز است، کلیک روی اعلان، آن تب را به پیش‌زمینه می‌آورد. اگر صفحه از قبل باز نباشد، کلیک روی اعلان، صفحه را در یک تب جدید باز می‌کند.

از آنجا که پیام‌های داده از fcm_options.link پشتیبانی نمی‌کنند، توصیه می‌شود یک بار اعلان به همه پیام‌های داده اضافه کنید. به عنوان یک روش جایگزین، می‌توانید اعلان‌ها را با استفاده از service worker مدیریت کنید.

برای توضیح تفاوت بین پیام‌های اعلان و داده، به انواع پیام مراجعه کنید.

تنظیم گزینه‌های اعلان در سرویس ورکر

برای پیام‌های داده، می‌توانید گزینه‌های اعلان را در سرویس ورکر تنظیم کنید. ابتدا، برنامه خود را در سرویس ورکر راه‌اندازی کنید:

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

برای تنظیم گزینه‌ها، onBackgroundMessage در firebase-messaging-sw.js فراخوانی کنید. در این مثال، ما یک اعلان با فیلدهای عنوان، بدنه و آیکون ایجاد می‌کنیم.

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

ساخت درخواست‌های ارسال

پس از ایجاد یک موضوع، چه با عضویت نمونه‌های برنامه کلاینت در موضوع در سمت کلاینت و چه از طریق API سرور ، می‌توانید پیام‌هایی را به موضوع ارسال کنید. اگر این اولین بار است که درخواست‌های ارسال برای FCM را می‌سازید، برای اطلاعات مهم پیش‌زمینه و تنظیمات، به راهنمای محیط سرور و FCM خود مراجعه کنید.

در منطق ارسال خود در backend، نام موضوع مورد نظر را همانطور که نشان داده شده است، مشخص کنید:

نود جی اس

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

جاوا

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

پایتون

# 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)

برو

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

سی شارپ

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

استراحت

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

برای ارسال پیام به ترکیبی از موضوعات، یک شرط تعیین کنید، که یک عبارت بولی است که موضوعات هدف را مشخص می‌کند. برای مثال، شرط زیر پیام‌ها را به دستگاه‌هایی ارسال می‌کند که در TopicA و TopicB یا TopicC مشترک هستند:

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

FCM ابتدا هر شرط داخل پرانتز را ارزیابی می‌کند و سپس عبارت را از چپ به راست ارزیابی می‌کند. در عبارت بالا، کاربری که در هر موضوع واحدی مشترک شده باشد، پیام را دریافت نمی‌کند. به همین ترتیب، کاربری که در TopicA مشترک نشده باشد، پیام را دریافت نمی‌کند. این ترکیب‌ها آن را دریافت می‌کنند:

  • TopicA و TopicB
  • TopicA و TopicC

شما می‌توانید تا پنج موضوع را در عبارت شرطی خود بگنجانید.

برای ارسال به یک شرط:

نود جی اس

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

جاوا

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

پایتون

# 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)

برو

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

سی شارپ

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

استراحت

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

مراحل بعدی