Gestire le iscrizioni agli argomenti

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

Gestire gli abbonamenti agli argomenti utilizzando l'API del server di abbonamento agli argomenti

Per iscrivere una registrazione FCM a un argomento, trasmetti 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 gli abbonamenti agli argomenti FCM V1 consente anche di annullare l'iscrizione di un token a un argomento tramite la 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 gli abbonamenti agli argomenti di un ID registrazione tramite la 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 abbonamenti 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"
          },
        ...
        ]
    }

Gestire gli abbonamenti agli argomenti utilizzando l'SDK Admin

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

Puoi iscrivere le istanze dell'app client a qualsiasi argomento esistente oppure puoi creare un nuovo argomento. 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 abbonamento Firebase Admin SDK per abbonare 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 la registrazione 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() restituiscono 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 (autenticazioni non riuscite, token o argomento non validi e così via), questi metodi generano un errore. Per un elenco completo dei codici di errore, incluse descrizioni e procedure di risoluzione, consulta Firebase Admin SDK Errori.

Gestire gli abbonamenti agli argomenti dall'app client

Le istanze dell'app client possono anche essere iscritte o annullate l'iscrizione agli argomenti direttamente dalla tua app tramite gli SDK Firebase. Tieni presente che FCM tentativi in caso di errori iniziali per garantire la riuscita dell'abbonamento.

Scegli la tua piattaforma:

Android

Le app client possono abbonarsi 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ò successivamente iscriversi.

Per sottoscrivere 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'abbonamento è andato 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 abbonarsi 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ò successivamente iscriversi.

Per abbonarti a un argomento, chiama il metodo di abbonamento dal thread principale della tua applicazione (FCM non è thread-safe). Se la richiesta di abbonamento non riesce inizialmente, FCM riprova automaticamente. Per i casi in cui l'abbonamento non può essere completato, l'abbonamento genera un errore che puoi rilevare in un gestore di completamento come mostrato di seguito:

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 tutti gli argomenti richiesti siano stati sottoscritti. Per annullare l'iscrizione, chiama il numero unsubscribeFromTopic:topic, e FCM annulla l'iscrizione all'argomento in background.

C++

Per abbonarti a un argomento, chiama ::firebase::messaging::Subscribe dalla tua applicazione. Invia una richiesta asincrona al backend FCM e sottoscrive il client all'argomento specificato.

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

Se inizialmente la richiesta di abbonamento non va a buon fine, FCM riprova finché non riesce ad abbonarsi all'argomento. Ogni volta che l'app viene avviata, FCM si assicura che tutti gli argomenti richiesti siano stati sottoscritti.

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

Unity

Per abbonarti a un argomento, chiama Firebase.Messaging.FirebaseMessaging.Subscribe dalla tua applicazione. Invia una richiesta asincrona al backend FCM e sottoscrive il client all'argomento specificato.

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

Se inizialmente la richiesta di abbonamento non va a buon fine, FCM riprova finché non riesce ad abbonarsi all'argomento. Ogni volta che l'app viene avviata, FCM si assicura che tutti gli argomenti richiesti siano stati sottoscritti.

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

Gestione degli argomenti lato server legacy (deprecato)

Per capire cosa sono gli ID istanza, visita la pagina ID istanza. Per informazioni dettagliate sugli endpoint ritirati, consulta i riferimenti API Instance ID.

Gestire gli abbonamenti agli argomenti in caso di modifica dell'ID federato o del token

Quando l'FID (Firebase Installation ID) 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 rinnovi del token. Il motivo più comune per la modifica di un token è l'eliminazione/rotazione dell'ID installazione Firebase, che può essere monitorata seguendo le istruzioni riportate in Monitorare il ciclo di vita dell'ID installazione Firebase.

Se vuoi mantenere gli abbonamenti agli argomenti in caso di modifiche all'ID istanza dell'app o al token, devi eseguire il backup dei dati di abbonamento agli argomenti sul client o sul backend e abbonare il nuovo identificatore agli argomenti a cui era abbonata in precedenza l'istanza dell'app. 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 backend.