管理主題訂閱項目

您可以透過伺服器或用戶端,為用戶端應用程式訂閱主題:

使用主題訂閱伺服器 API 管理主題訂閱項目

如要將 FCM 註冊訂閱至主題,請將註冊 ID (Firebase 安裝 ID 或 FCM 註冊權杖) 傳遞至 FCM 主題訂閱伺服器 API,如下所示。

REST

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

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

{}

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?topicName=${TOPIC_NAME}

如果成功,HTTP v1 API 回應會是 JSON 物件,內含主題名稱和建立時間。

    {
      "topicName": "${TOPIC_NAME}",
      "createTime": "2026-01-15T01:30:15.01Z"
    }

FCM V1 主題訂閱 API 也可讓您透過 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

{}

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}

您也可以透過 GET 要求,列出註冊 ID 的主題訂閱項目:

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

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

如果成功,HTTP v1 API 回應會是包含主題訂閱清單的 JSON 物件。

    {
        "topicSubscriptions": [
          {
              "topicName": "${TOPIC_NAME1}",
              "createTime": "2026-01-15T01:30:15.01Z"
          },
          {
              "topicName": "${TOPIC_NAME2}",
              "createTime": "2026-01-16T02:40:17.01Z"
          },
        ...
        ]
    }

使用 Admin SDK 管理主題訂閱

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

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')

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)
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 也可將註冊權杖傳遞至適當的方法,取消裝置訂閱主題:

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')

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

subscribeToTopic() 和 unsubscribeFromTopic() 方法會產生包含 FCM 回應的物件。無論要求中指定的註冊權杖數量為何,傳回類型都採用相同格式。

如果發生錯誤 (驗證失敗、權杖或主題無效等),這些方法會導致錯誤。如需錯誤代碼的完整清單 (包括說明和解決步驟),請參閱「Firebase Admin SDK 錯誤」。

透過用戶端應用程式管理主題訂閱

用戶端應用程式執行個體也可以透過 Firebase SDK,直接從應用程式訂閱或取消訂閱主題。請注意,如果初始失敗,FCM 會重試,確保訂閱成功。

選擇平台:

Android

用戶端應用程式可以訂閱任何現有主題,也可以建立新主題。當用戶端應用程式訂閱新的主題名稱 (Firebase 專案中尚不存在的主題名稱) 時,系統會在 FCM 中建立該名稱的新主題,之後任何用戶端都可以訂閱該主題。

如要訂閱主題,用戶端應用程式會使用 FCM 主題名稱呼叫 Firebase Cloud Messaging subscribeToTopic()。這個方法會傳回 Task,完成事件監聽器可使用這個方法判斷訂閱是否成功:

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

如要取消訂閱,用戶端應用程式會呼叫 Firebase Cloud Messaging unsubscribeFromTopic(),並提供主題名稱。

iOS

用戶端應用程式可以訂閱任何現有主題,也可以建立新主題。當用戶端應用程式訂閱新的主題名稱 (Firebase 專案中尚不存在的主題名稱) 時,系統會在 FCM 中建立該名稱的新主題,之後任何用戶端都可以訂閱該主題。

如要訂閱主題,請從應用程式的主要執行緒呼叫訂閱方法 (FCM 不是執行緒安全)。如果訂閱要求一開始失敗,FCM 會自動重試。如果無法完成訂閱,訂閱作業會擲回錯誤,您可以在完成處理常式中擷取錯誤,如下所示:

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

這項呼叫會向 FCM 後端發出非同步要求,並為用戶端訂閱指定主題。呼叫 subscribeToTopic:topic 之前,請確認用戶端應用程式執行個體已透過回呼 didReceiveRegistrationToken 收到註冊權杖。

每次應用程式啟動時,FCM 都會確保所有要求的主題都已訂閱。如要取消訂閱,請呼叫 unsubscribeFromTopic:topic,FCM 會在背景取消訂閱主題。

C++

如要訂閱主題,請從應用程式呼叫 ::firebase::messaging::Subscribe。這會向 FCM 後端發出非同步要求,並為用戶端訂閱指定主題。

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

如果訂閱要求一開始失敗,FCM 會重試,直到成功訂閱主題為止。每次應用程式啟動時,FCM 都會確保所有要求的主題都已訂閱。

如要取消訂閱,請呼叫 ::firebase::messaging::Unsubscribe,FCM 就會在背景取消訂閱主題。

Unity

如要訂閱主題,請從應用程式呼叫 Firebase.Messaging.FirebaseMessaging.Subscribe。這會向 FCM 後端發出非同步要求,並為用戶端訂閱指定主題。

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

如果訂閱要求一開始失敗,FCM 會重試,直到成功訂閱主題為止。每次應用程式啟動時,FCM 都會確保所有要求的主題都已訂閱。

如要取消訂閱,請呼叫 Firebase.Messaging.FirebaseMessaging.Unsubscribe,FCM 就會在背景取消訂閱主題。

舊版伺服器端主題管理 (已淘汰)

如要瞭解執行個體 ID,請參閱執行個體 ID 頁面。如要進一步瞭解已淘汰的端點,請參閱執行個體 ID API 參考資料。

在 FID 或權杖變更時管理主題訂閱項目

當應用程式的 FID (Firebase 安裝 ID) 或 FCM 權杖變更時,與舊 FID 或權杖相關聯的主題訂閱項目不會遷移,因此新 ID 沒有主題訂閱項目。一般來說,權杖不會在應用程式更新或權杖重新整理期間變更。權杖變更最常見的原因是 FID 刪除/輪替,您可以按照「監控 Firebase 安裝 ID 生命週期」一文中的說明監控這類情況。

如要在 FID 或權杖變更時保留主題訂閱項目,請將每個應用程式執行個體的訂閱主題儲存在用戶端或後端。接著,當 FID 或權杖變更時,請為新的 ID 訂閱這些已儲存的主題。Firebase 不會自動追蹤或遷移主題訂閱項目,因此您必須在應用程式或後端中實作這項邏輯。

復原已刪除或遺失的主題訂閱項目

FCM 不會保留主題訂閱項目的記錄,因此無法自動還原因非預期 API 呼叫而移除的訂閱項目。復原方式取決於主題訂閱項目的管理位置:

  • 用戶端管理的訂閱項目:將使用者選取的主題儲存在應用程式中,例如 Android 上的 SharedPreferences 或 Apple 平台上的 UserDefaults。當使用者變更選項時,請只訂閱或取消訂閱變更的主題。註冊 ID 變更時,請再次為所有儲存的主題呼叫 subscribeToTopic。如要確認訂閱項目是否正確,請在使用者開啟應用程式時重新訂閱,但每月不超過一次。如果重新訂閱的頻率較高,專案的主題訂閱項目配額可能會很快用盡。主題訂閱項目很穩定,通常只有在註冊 ID 變更時才會失去同步。對已訂閱的主題呼叫 subscribeToTopic 是安全的。
  • 伺服器管理的訂閱項目:在後端記錄每個有效註冊 ID (FID 或註冊權杖) 應接收的主題。當使用者變更通知偏好設定或註冊 ID 變更時,請更新這筆記錄。如要修復缺少的訂閱項目,請使用 Firebase Admin SDK 或主題訂閱伺服器 API,從記錄中重新訂閱受影響的註冊項目:
    • 查看 API 錯誤代碼。當您向主題訂閱伺服器 API 傳送 POST 要求來建立訂閱項目時,HTTP 409 表示訂閱項目已存在,因此可以視為成功。這個 API 的其他方法和用戶端 SDK 不會傳回 HTTP 409。HTTP 404 通常表示註冊本身已失效。請參閱「偵測並復原已刪除的註冊」。
    • 調整大量要求的速度。重新訂閱多個應用程式執行個體時,請分散要求時間,並使用指數輪詢重試 429 RESOURCE_EXHAUSTED 錯誤。請參閱「訂閱項目節流」。