ارسال موضوع در C++

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

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

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

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

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

برای اشتراک در یک موضوع، با ::firebase::messaging::Subscribe در برنامه خود تماس بگیرید. این یک درخواست ناهمزمان به باطن FCM می دهد و مشتری را در موضوع داده شده مشترک می کند.

::firebase::messaging::Subscribe("example");

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

برای لغو اشتراک، با ::firebase::messaging::Unsubscribe تماس بگیرید و FCM اشتراک موضوع را در پس‌زمینه لغو می‌کند.

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

Firebase Admin SDK به شما این امکان را می دهد که وظایف مدیریت موضوع اصلی را از سمت سرور انجام دهید. با توجه به نشانه(های) ثبت نام آنها، می توانید با استفاده از منطق سرور، نمونه های برنامه مشتری را به صورت انبوه مشترک و لغو اشتراک کنید.

می‌توانید نمونه‌های برنامه مشتری را در هر موضوع موجود مشترک کنید، یا می‌توانید موضوع جدیدی ایجاد کنید. هنگامی که از API برای اشتراک برنامه مشتری در یک موضوع جدید استفاده می کنید (موضوعی که قبلاً برای پروژه Firebase شما وجود ندارد)، موضوع جدیدی با آن نام در FCM ایجاد می شود و هر مشتری می تواند متعاقباً در آن مشترک شود.

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

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

جاوا

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

Admin FCM API همچنین به شما این امکان را می دهد که اشتراک دستگاه ها را از یک موضوع با ارسال نشانه های ثبت نام به روش مناسب لغو کنید:

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

جاوا

// 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 می شود. نوع بازگشت بدون در نظر گرفتن تعداد نشانه های ثبت نام مشخص شده در درخواست، قالب یکسانی دارد.

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

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

FCM پیام های موضوعی را به همان روشی که سایر پیام های پایین دستی ارائه می دهد.

با نادیده گرفتن روش ::firebase::messaging::Listener::OnMessage ، می توانید اقداماتی را بر اساس پیام دریافتی انجام دهید و داده پیام را دریافت کنید:

void OnMessage(const ::firebase::messaging::Message& message) {
  LogMessage(TAG, "From: %s", message.from.c_str());
  LogMessage(TAG, "Message ID: %s", message.message_id.c_str());
}

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

پس از ایجاد یک موضوع، یا با اشتراک نمونه‌های برنامه مشتری در موضوع سمت سرویس گیرنده یا از طریق 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);
  });

جاوا

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

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

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

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

جاوا

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