Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Firebase Admin SDK позволяет выполнять базовые задачи управления темами на стороне сервера. Используя регистрационные токены, вы можете массово подписывать и отменять подписку на экземпляры клиентских приложений, используя серверную логику.
Вы можете подписать экземпляры клиентского приложения на любую существующую тему или создать новую. Когда вы используете API для подписки клиентского приложения на новую тему (которой ещё нет в вашем проекте Firebase), в FCM создаётся новая тема с этим именем, и любой клиент может впоследствии подписаться на неё.
Вы можете передать список токенов регистрации в метод подписки Firebase Admin SDK , чтобы подписать соответствующие устройства на тему:
Node.js
// These registration tokens come from the client FCM SDKs.constregistrationTokens=['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.TopicManagementResponseresponse=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)iferr!=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.varregistrationTokens=newList<string>(){"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",};// Subscribe the devices corresponding to the registration tokens to the// topicvarresponse=awaitFirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens,topic);// See the TopicManagementResponse reference documentation// for the contents of response.Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
API Admin FCM также позволяет отписывать устройства от темы, передавая токены регистрации соответствующему методу:
Node.js
// These registration tokens come from the client FCM SDKs.constregistrationTokens=['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.TopicManagementResponseresponse=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)iferr!=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.varregistrationTokens=newList<string>(){"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",};// Unsubscribe the devices corresponding to the registration tokens from the// topicvarresponse=awaitFirebaseMessaging.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 Admin FCM .
[null,null,["Последнее обновление: 2025-08-15 UTC."],[],[],null,["# Manage topics from the server\n\n\u003cbr /\u003e\n\nThe [Firebase Admin SDK](/docs/admin/setup)\nallows you to perform basic\ntopic management tasks from the server side. Given their registration\ntoken(s), you can subscribe and unsubscribe client app instances in bulk using\nserver logic.\n\nYou can subscribe client app instances to any existing topic, or\nyou can create a new topic. When you use the API to subscribe a client app\nto a new topic (one that does not already exist for your Firebase project),\na new topic of that name is created in FCM and any client can subsequently\nsubscribe to it.\n\nYou can pass a list of registration tokens to the Firebase Admin SDK\nsubscription method to subscribe the corresponding devices to a topic: \n\n### Node.js\n\n // These registration tokens come from the client FCM SDKs.\n const registrationTokens = [\n 'YOUR_REGISTRATION_TOKEN_1',\n // ...\n 'YOUR_REGISTRATION_TOKEN_n'\n ];\n\n // Subscribe the devices corresponding to the registration tokens to the\n // topic.\n getMessaging().subscribeToTopic(registrationTokens, topic)\n .then((response) =\u003e {\n // See the MessagingTopicManagementResponse reference documentation\n // for the contents of response.\n console.log('Successfully subscribed to topic:', response);\n })\n .catch((error) =\u003e {\n console.log('Error subscribing to topic:', error);\n });\n\n### Java\n\n // These registration tokens come from the client FCM SDKs.\n List\u003cString\u003e registrationTokens = Arrays.asList(\n \"YOUR_REGISTRATION_TOKEN_1\",\n // ...\n \"YOUR_REGISTRATION_TOKEN_n\"\n );\n\n // Subscribe the devices corresponding to the registration tokens to the\n // topic.\n TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(\n registrationTokens, topic);\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n System.out.println(response.getSuccessCount() + \" tokens were subscribed successfully\");\n\n### Python\n\n # These registration tokens come from the client FCM SDKs.\n registration_tokens = [\n 'YOUR_REGISTRATION_TOKEN_1',\n # ...\n 'YOUR_REGISTRATION_TOKEN_n',\n ]\n\n # Subscribe the devices corresponding to the registration tokens to the\n # topic.\n response = messaging.subscribe_to_topic(registration_tokens, topic)\n # See the TopicManagementResponse reference documentation\n # for the contents of response.\n print(response.success_count, 'tokens were subscribed successfully')\n\n### Go\n\n // These registration tokens come from the client FCM SDKs.\n registrationTokens := []string{\n \t\"YOUR_REGISTRATION_TOKEN_1\",\n \t// ...\n \t\"YOUR_REGISTRATION_TOKEN_n\",\n }\n\n // Subscribe the devices corresponding to the registration tokens to the\n // topic.\n response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)\n if err != nil {\n \tlog.Fatalln(err)\n }\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n fmt.Println(response.SuccessCount, \"tokens were subscribed successfully\")\n\n### C#\n\n // These registration tokens come from the client FCM SDKs.\n var registrationTokens = new List\u003cstring\u003e()\n {\n \"YOUR_REGISTRATION_TOKEN_1\",\n // ...\n \"YOUR_REGISTRATION_TOKEN_n\",\n };\n\n // Subscribe the devices corresponding to the registration tokens to the\n // topic\n var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(\n registrationTokens, topic);\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n Console.WriteLine($\"{response.SuccessCount} tokens were subscribed successfully\"); \n https://github.com/firebase/firebase-admin-dotnet/blob/75f6b03eea42fbe84f57ee4b1177efdf916f4c58/FirebaseAdmin/FirebaseAdmin.Snippets/FirebaseMessagingSnippets.cs#L327-L341\n\n| **Important:** To use the Admin FCM API, you must first follow the steps in [Add the Firebase Admin SDK to your Server](/docs/admin/setup) to initialize the SDK.\n\nThe Admin FCM API also allows you to unsubscribe devices from a topic\nby passing registration tokens to the appropriate\nmethod: \n\n### Node.js\n\n // These registration tokens come from the client FCM SDKs.\n const registrationTokens = [\n 'YOUR_REGISTRATION_TOKEN_1',\n // ...\n 'YOUR_REGISTRATION_TOKEN_n'\n ];\n\n // Unsubscribe the devices corresponding to the registration tokens from\n // the topic.\n getMessaging().unsubscribeFromTopic(registrationTokens, topic)\n .then((response) =\u003e {\n // See the MessagingTopicManagementResponse reference documentation\n // for the contents of response.\n console.log('Successfully unsubscribed from topic:', response);\n })\n .catch((error) =\u003e {\n console.log('Error unsubscribing from topic:', error);\n });\n\n### Java\n\n // These registration tokens come from the client FCM SDKs.\n List\u003cString\u003e registrationTokens = Arrays.asList(\n \"YOUR_REGISTRATION_TOKEN_1\",\n // ...\n \"YOUR_REGISTRATION_TOKEN_n\"\n );\n\n // Unsubscribe the devices corresponding to the registration tokens from\n // the topic.\n TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(\n registrationTokens, topic);\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n System.out.println(response.getSuccessCount() + \" tokens were unsubscribed successfully\");\n\n### Python\n\n # These registration tokens come from the client FCM SDKs.\n registration_tokens = [\n 'YOUR_REGISTRATION_TOKEN_1',\n # ...\n 'YOUR_REGISTRATION_TOKEN_n',\n ]\n\n # Unubscribe the devices corresponding to the registration tokens from the\n # topic.\n response = messaging.unsubscribe_from_topic(registration_tokens, topic)\n # See the TopicManagementResponse reference documentation\n # for the contents of response.\n print(response.success_count, 'tokens were unsubscribed successfully')\n\n### Go\n\n // These registration tokens come from the client FCM SDKs.\n registrationTokens := []string{\n \t\"YOUR_REGISTRATION_TOKEN_1\",\n \t// ...\n \t\"YOUR_REGISTRATION_TOKEN_n\",\n }\n\n // Unsubscribe the devices corresponding to the registration tokens from\n // the topic.\n response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)\n if err != nil {\n \tlog.Fatalln(err)\n }\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n fmt.Println(response.SuccessCount, \"tokens were unsubscribed successfully\")\n\n### C#\n\n // These registration tokens come from the client FCM SDKs.\n var registrationTokens = new List\u003cstring\u003e()\n {\n \"YOUR_REGISTRATION_TOKEN_1\",\n // ...\n \"YOUR_REGISTRATION_TOKEN_n\",\n };\n\n // Unsubscribe the devices corresponding to the registration tokens from the\n // topic\n var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(\n registrationTokens, topic);\n // See the TopicManagementResponse reference documentation\n // for the contents of response.\n Console.WriteLine($\"{response.SuccessCount} tokens were unsubscribed successfully\"); \n https://github.com/firebase/firebase-admin-dotnet/blob/75f6b03eea42fbe84f57ee4b1177efdf916f4c58/FirebaseAdmin/FirebaseAdmin.Snippets/FirebaseMessagingSnippets.cs#L348-L362\n\n| **Note:** You can subscribe or unsubscribe up to 1,000 devices in a single request. If you provide an array with over 1,000 registration tokens, the request will fail with a `messaging/invalid-argument` error.\n\nThe `subscribeToTopic()` and `unsubscribeFromTopic()` methods results in an\nobject containing the response from FCM. The return type has the same\nformat regardless of the number of registration tokens specified in the\nrequest.\n\nIn case of an error (authentication failures, invalid token or topic etc.)\nthese methods result in an error.\nFor a full list of error codes, including descriptions\nand resolution steps, see\n[Admin FCM API Errors](/docs/cloud-messaging/send-message#admin_sdk_error_reference)."]]