Gestire le iscrizioni agli argomenti

Puoi iscrivere un'app client a un argomento dal server o dal client:

Gestisci le iscrizioni agli argomenti utilizzando l'API del server di iscrizione agli argomenti

Per iscrivere una registrazione FCM a un argomento, passa l'ID registrazione (ID installazione Firebase o token di registrazione FCM) all'API del server di iscrizione agli argomenti FCM come mostrato.

REST

POST https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions?topic_name=${TOPIC_NAME}

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{}

Comando curl:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{}'
https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions?topic_name=${TOPIC_NAME}

In caso di esito positivo, la risposta dell'API HTTP v1 è un oggetto JSON contenente il nome della risorsa, il nome dell'argomento e il timestamp.

    {
      "topic_name": "${TOPIC_NAME}",
      "create_time": "2026-01-15T01:30:15.01Z"
    }

L'API per le iscrizioni agli argomenti FCM V1 consente anche di annullare l'iscrizione di un token a un argomento tramite una richiesta DELETE:

REST

DELETE https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions/${TOPIC_NAME}

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{}

Comando curl:

curl -X DELETE -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{}'
https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions/${TOPIC_NAME}

Puoi anche elencare le iscrizioni agli argomenti di un ID di registrazione tramite una richiesta GET:

REST

GET https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

Comando curl:

curl -X GET -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json"
https://fcm.googleapis.com/v1/projects/${PROJECT_ID}/registrations/${REGISTRATION_ID}/topicSubscriptions

In caso di esito positivo, la risposta dell'API HTTP v1 è un oggetto JSON contenente un elenco di iscrizioni agli argomenti

    {
        "topic_subscriptions": [
          {
              "topic_name": "${TOPIC_NAME1}",
              "create_time": "2026-01-15T01:30:15.01Z"
          },
          {
              "topic_name": "${TOPIC_NAME2}",
              "create_time": "2026-01-16T02:40:17.01Z"
          },
        ...
        ]
    }

Gestisci le iscrizioni agli argomenti utilizzando l'SDK Admin

Firebase Admin SDK ti consente di eseguire attività di gestione di base degli argomenti dal lato server. In base ai token di registrazione, puoi iscrivere e annullare l'iscrizione collettivamente alle istanze dell'app client utilizzando la logica del server.

Puoi iscrivere le istanze dell'app client a qualsiasi argomento esistente o crearne uno nuovo. Quando utilizzi l'API per iscrivere un'app client a un nuovo argomento (uno che non esiste già per il tuo progetto Firebase), in FCM viene creato un nuovo argomento con quel nome e qualsiasi client può successivamente iscriversi.

Puoi passare un elenco di token di registrazione al metodo di iscrizione Firebase Admin SDK per iscrivere i dispositivi corrispondenti a un argomento:

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().subscribeToTopicAsync(
    registrationTokens, topic).get();
// 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')

Vai

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

Firebase Admin SDK consente anche di annullare l'iscrizione dei dispositivi a un argomento passando i token di registrazione al metodo appropriato:

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().unsubscribeFromTopicAsync(
    registrationTokens, topic).get();
// 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')

Vai

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

I metodi subscribeToTopic() e unsubscribeFromTopic() generano un oggetto contenente la risposta di FCM. Il tipo restituito ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.

In caso di errore (errori di autenticazione, token o argomento non valido e così via), questi metodi generano un errore. Per un elenco completo dei codici di errore, incluse le descrizioni e i passaggi per la risoluzione, consulta Errori di Firebase Admin SDK.

Gestisci le iscrizioni agli argomenti dalla tua app client

Le istanze delle app client possono anche essere iscritte o annullate l'iscrizione agli argomenti direttamente dalla tua app tramite gli SDK Firebase. Tieni presente che FCM riprova in caso di errori iniziali per garantire che l'iscrizione vada a buon fine.

Scegli la tua piattaforma:

Android

Le app client possono iscriversi a qualsiasi argomento esistente o crearne uno nuovo. Quando un'app client si iscrive a un nuovo nome di argomento (uno che non esiste già per il tuo progetto Firebase), viene creato un nuovo argomento con quel nome in FCM e qualsiasi client può iscriversi successivamente.

Per iscriversi a un argomento, l'app client chiama Firebase Cloud Messaging subscribeToTopic() con il nome dell'argomento FCM. Questo metodo restituisce un Task, che può essere utilizzato da un listener di completamento per determinare se l'iscrizione è andata a buon fine:

Kotlin

Firebase.messaging.subscribeToTopic("weather")
    .addOnCompleteListener { task ->
        var msg = "Subscribed"
        if (!task.isSuccessful) {
            msg = "Subscribe failed"
        }
        Log.d(TAG, msg)
        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
    }

Java

FirebaseMessaging.getInstance().subscribeToTopic("weather")
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                String msg = "Subscribed";
                if (!task.isSuccessful()) {
                    msg = "Subscribe failed";
                }
                Log.d(TAG, msg);
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

Per annullare l'iscrizione, l'app client chiama Firebase Cloud Messaging unsubscribeFromTopic() con il nome dell'argomento.

iOS

Le app client possono iscriversi a qualsiasi argomento esistente o crearne uno nuovo. Quando un'app client si iscrive a un nuovo nome di argomento (uno che non esiste già per il tuo progetto Firebase), viene creato un nuovo argomento con quel nome in FCM e qualsiasi client può iscriversi successivamente.

Per iscriverti a un argomento, chiama il metodo di iscrizione dal thread principale dell'applicazione (FCM non è thread-safe). Se la richiesta di iscrizione non va a buon fine inizialmente, FCM riprova automaticamente. Nei casi in cui l'abbonamento non può essere completato, viene generato un errore che puoi rilevare in un gestore di completamento, come mostrato:

Swift

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

Objective-C

[[FIRMessaging messaging] subscribeToTopic:@"weather"
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to weather topic");
}];

Questa chiamata effettua una richiesta asincrona al backend FCM e iscrive il client all'argomento specificato. Prima di chiamare subscribeToTopic:topic, assicurati che l'istanza dell'app client abbia già ricevuto un token di registrazione tramite il callback didReceiveRegistrationToken.

Ogni volta che l'app viene avviata, FCM si assicura che sia stata effettuata l'iscrizione a tutti gli argomenti richiesti. Per annullare l'iscrizione, chiama unsubscribeFromTopic:topic e FCM annulla l'iscrizione all'argomento in background.

C++

Per iscriverti a un argomento, chiama ::firebase::messaging::Subscribe dalla tua applicazione. In questo modo viene inviata una richiesta asincrona al backend FCM e il client viene iscritto all'argomento specificato.

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

Se la richiesta di sottoscrizione non va a buon fine inizialmente, FCM riprova finché non riesce a sottoscrivere l'argomento. Ogni volta che l'app viene avviata, FCM si assicura che sia stata effettuata l'iscrizione a tutti gli argomenti richiesti.

Per annullare l'iscrizione, chiama ::firebase::messaging::Unsubscribe e FCM annulla l'iscrizione all'argomento in background.

Unity

Per iscriverti a un argomento, chiama Firebase.Messaging.FirebaseMessaging.Subscribe dalla tua applicazione. In questo modo viene inviata una richiesta asincrona al backend FCM e il client viene iscritto all'argomento specificato.

Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");

Se la richiesta di sottoscrizione non va a buon fine inizialmente, FCM riprova finché non riesce a sottoscrivere l'argomento. Ogni volta che l'app viene avviata, FCM si assicura che sia stata effettuata l'iscrizione a tutti gli argomenti richiesti.

Per annullare l'iscrizione, chiama Firebase.Messaging.FirebaseMessaging.Unsubscribe, e FCM annulla l'iscrizione all'argomento in background.

Gestione degli argomenti lato server legacy (deprecata)

Per capire cosa sono gli ID istanza, consulta la pagina ID istanza. Per maggiori dettagli sugli endpoint ritirati, consulta i riferimenti API Instance ID.

Gestisci le iscrizioni agli argomenti in caso di modifica del FID o del token

Quando l'FID (ID installazione di Firebase) o il token FCM di un'app cambia, le iscrizioni agli argomenti associate al vecchio FID o token non vengono migrate e, di conseguenza, il nuovo identificatore non ha iscrizioni agli argomenti. In genere, un token non cambia durante gli aggiornamenti dell'app o i refresh dei token. Il motivo più comune per una modifica del token è l'eliminazione/rotazione del FID, che può essere monitorata seguendo Monitora il ciclo di vita dell'ID installazione di Firebase.

Se vuoi mantenere le iscrizioni agli argomenti in caso di modifiche al FID o al token, devi eseguire il backup dei dati di iscrizione agli argomenti sul client o sul backend e iscrivere il nuovo identificatore agli argomenti a cui era iscritta l'istanza dell'app in precedenza. Firebase non fornisce funzionalità automatiche per monitorare o eseguire la migrazione di questi abbonamenti. Si tratta di un'attività che devi implementare manualmente nella tua app e nel tuo backend.