Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Com o Firebase Admin SDK
é possível executar tarefas básicas
de gerenciamento de tópicos do lado do servidor. Com os tokens de
registro, é possível fazer e cancelar a inscrição de instâncias do app clienteem massa usando
a lógica do servidor.
É possível inscrever instâncias de apps cliente em qualquer tópico ou
criar um novo tópico. Se você usar a API para fazer a inscrição de um app cliente
em um novo tópico que ainda não existe no seu projeto do Firebase,
um novo tópico com esse nome será criado no FCM e qualquer cliente poderá
se inscrever nele depois.
É possível transferir uma lista dos tokens de registro ao método Firebase Admin SDK
para inscrever os dispositivos correspondentes em um tópico:
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);});
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.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");
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')
Go
// 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")
C#
// 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");
A API Admin do FCM também permite cancelar a inscrição de dispositivos em um tópico
passando tokens de registro para o método
adequado:
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);});
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.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");
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')
Go
// 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")
C#
// 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");
Os métodos subscribeToTopic() e unsubscribeFromTopic() retornam um objeto
que contém a resposta do FCM. O tipo de retorno tem o mesmo
formato, independentemente do número de tokens de registro especificados na
solicitação.
Em caso de erro (falhas de autenticação, token ou tópico inválido etc.),
esses métodos resultam em um erro.
Para ver uma lista completa de códigos de erros, incluindo descrições
e etapas de solução de problemas, consulte
Erros da API Admin FCM.
[null,null,["Última atualização 2025-08-16 UTC."],[],[],null,["\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\nNode.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\nJava \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\nPython \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\nGo \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\nC# \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\nNode.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\nJava \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\nPython \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\nGo \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\nC# \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)."]]