如果尚未設定 Firebase Admin SDK,請按照指南在伺服器上設定 Firebase Admin SDK。
啟用 FCM HTTP v1 API
在 Firebase 控制台中,依序前往「設定」
>「一般」。然後按一下「Cloud Messaging」分頁標籤。 啟用 Cloud Messaging API。
授權其他專案的服務帳戶
您可以使用「傳送者專案」中的服務帳戶,為「目標專案」傳送訊息。這樣一來,您就能在一個專案中集中管理服務帳戶,同時代表他人傳送訊息。如要瞭解如何執行這項操作,請按照下列步驟操作:
在傳送者專案中,請確認已啟用 Firebase Cloud Messaging API。如要檢查是否已啟用,請前往 Firebase 控制台,然後依序點選「設定」
「一般」 。然後按一下「Cloud Messaging」分頁標籤。在傳送者專案中,建立服務帳戶。
在目標專案中,將 Firebase Cloud Messaging API 管理員角色指派給服務帳戶的電子郵件地址。您可以在 Google Cloud 控制台的「IAM & Admin」(IAM 與管理) >「IAM」(身分與存取權管理)頁面執行這項操作。這個角色可讓傳送端專案的服務帳戶將訊息傳送至目標專案。
使用傳送者專案的服務帳戶金鑰檔案和目標專案的專案 ID,初始化 SDK。
Node.js
import { initializeApp, applicationDefault } from 'firebase-admin/app'; initializeApp({ // The credential is configured to be the sender project's service // account key via the environment variable GOOGLE_APPLICATION_CREDENTIALS credential: applicationDefault(), projectId: '<TARGET_PROJECT_ID>', });Java
FirebaseOptions options = FirebaseOptions.builder() // The credential is configured to be the sender project's service // account key via the environment variable GOOGLE_APPLICATION_CREDENTIALS .setCredentials(GoogleCredentials.getApplicationDefault()) .setProjectId("<TARGET_PROJECT_ID>") .build(); FirebaseApp.initializeApp(options);Python
import firebase_admin app_options = {'projectId': '<TARGET_PROJECT_ID>'} # Initialize with the default credential, i.e. the sender project's service # account key, stored in GOOGLE_APPLICATION_CREDENTIALS default_app = firebase_admin.initialize_app(options=app_options)Go
config := &firebase.Config{ProjectID: "<TARGET_PROJECT_ID>"} // Initialize with the default credential, i.e. the sender project's service // account key, stored in GOOGLE_APPLICATION_CREDENTIALS app, err := firebase.NewApp(context.Background(), config) if err != nil { log.Fatalf("error initializing app: %v\n", err) }C#
FirebaseApp.Create(new AppOptions() { // The credential is configured to be the sender project's service // account key via the environment variable GOOGLE_APPLICATION_CREDENTIALS Credential = GoogleCredential.GetApplicationDefault(), ProjectId = "<TARGET_PROJECT_ID>", });
將訊息傳送至特定裝置
如要傳送至特定單一裝置,可以指定該裝置的 Firebase 安裝 ID (FID) 或註冊權杖。
Node.js
使用 FID (建議):
// This installation ID comes from the client FCM SDKs.
const fid = 'YOUR_REGISTERED_FID';
const message = {
data: {
score: '850',
time: '2:45'
},
fid: fid
};
// Send a message to the device corresponding to the provided FID.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
使用註冊權杖 (已淘汰):
// This registration token comes from the client FCM SDKs.
const registrationToken = 'YOUR_REGISTRATION_TOKEN';
const message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Java
使用 FID (建議):
// This installation ID comes from the client FCM SDKs.
String fid = "YOUR_REGISTERED_FID";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setFid(fid)
.build();
// Send a message to the device corresponding to the provided FID.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
使用註冊權杖 (已淘汰):
// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Python
使用 FID (建議):
# This installation ID comes from the client FCM SDKs.
fid = 'YOUR_REGISTERED_FID'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
fid=fid,
)
# Send a message to the device corresponding to the provided FID.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
使用註冊權杖 (已淘汰):
# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
token=registration_token,
)
# Send a message to the device corresponding to the provided
# registration token.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
Go
使用 FID (建議):
// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
log.Fatalf("error getting Messaging client: %v\n", err)
}
// This installation ID comes from the client FCM SDKs.
fid := "YOUR_REGISTERED_FID"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Fid: fid,
}
// Send a message to the device corresponding to the provided FID.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
使用註冊權杖 (已淘汰):
// Obtain a messaging.Client from the App.
ctx := context.Background()
client, err := app.Messaging(ctx)
if err != nil {
log.Fatalf("error getting Messaging client: %v\n", err)
}
// This registration token comes from the client FCM SDKs.
registrationToken := "YOUR_REGISTRATION_TOKEN"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Token: registrationToken,
}
// Send a message to the device corresponding to the provided
// registration token.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
C#
使用 FID (建議):
// This installation ID comes from the client FCM SDKs.
var fid = "YOUR_REGISTERED_FID";
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Fid = fid,
};
// Send a message to the device corresponding to the provided FID.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
使用註冊權杖 (已淘汰):
// This registration token comes from the client FCM SDKs.
var registrationToken = "YOUR_REGISTRATION_TOKEN";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
#pragma warning disable CS0618
Token = registrationToken,
#pragma warning restore CS0618
};
// Send a message to the device corresponding to the provided
// registration token.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
成功時,每個傳送方法都會傳回郵件 ID。Firebase Admin SDK 會傳回 projects/{project_id}/messages/{message_id} 格式的 ID 字串。
將訊息傳送至多部裝置
您可以使用 Admin FCM SDK,將訊息多播至 Firebase 安裝 ID (FID) 或裝置註冊權杖清單。如需將相同訊息傳送至大量裝置,可以使用這項功能。每次呼叫最多可指定 500 個 FID 和/或權杖。
傳回值包含與輸入目標、FID 和/或權杖順序對應的回覆清單。如要查看哪些目標導致錯誤,這項功能就非常實用。如果同時提供權杖和 FID,系統會先處理權杖,再處理 FID。
Node.js
使用 FID (建議):
// These Firebase Installation IDs (FIDs) come from the client FCM SDKs.
const fids = [
'YOUR_REGISTERED_FID_1',
// ...
'YOUR_REGISTERED_FID_N'
];
const message = {
data: {score: '850', time: '2:45'},
fids: fids,
};
getMessaging().sendEachForMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
if (response.failureCount > 0) {
const failedFids = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedFids.push(fids[idx]);
}
});
console.log('List of FIDs that caused failures: ' + failedFids);
}
});
使用註冊權杖 (已淘汰):
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
data: {score: '850', time: '2:45'},
tokens: registrationTokens,
};
getMessaging().sendEachForMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
});
Java
使用 FID (建議):
// These Firebase Installation IDs (FIDs) come from the client FCM SDKs.
List<String> fids = Arrays.asList(
"YOUR_REGISTERED_FID_1",
// ...
"YOUR_REGISTERED_FID_N"
);
MulticastMessage message = MulticastMessage.builder()
.putData("score", "850")
.putData("time", "2:45")
.addAllFids(fids)
.build();
BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
if (response.getFailureCount() > 0) {
List<SendResponse> responses = response.getResponses();
List<String> failedFids = new ArrayList<>();
for (int i = 0; i < responses.size(); i++) {
if (!responses.get(i).isSuccessful()) {
// The order of responses corresponds to the order of the destination FIDs.
failedFids.add(fids.get(i));
}
}
System.out.println("List of FIDs that caused failures: " + failedFids);
}
使用註冊權杖 (已淘汰):
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
MulticastMessage message = MulticastMessage.builder()
.putData("score", "850")
.putData("time", "2:45")
.addAllTokens(registrationTokens)
.build();
BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
if (response.getFailureCount() > 0) {
List<SendResponse> responses = response.getResponses();
List<String> failedTokens = new ArrayList<>();
for (int i = 0; i < responses.size(); i++) {
if (!responses.get(i).isSuccessful()) {
// The order of responses corresponds to the order of the registration tokens.
failedTokens.add(registrationTokens.get(i));
}
}
System.out.println("List of tokens that caused failures: " + failedTokens);
}
Python
使用 FID (建議):
# These Firebase Installation IDs (FIDs) come from the client FCM SDKs.
fids = [
'YOUR_REGISTERED_FID_1',
# ...
'YOUR_REGISTERED_FID_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
fids=fids,
)
response = messaging.send_each_for_multicast(message)
if response.failure_count > 0:
responses = response.responses
failed_fids = []
for idx, resp in enumerate(responses):
if not resp.success:
# The order of responses corresponds to the order of the destination FIDs.
failed_fids.append(fids[idx])
print('List of FIDs that caused failures: {0}'.format(failed_fids))
使用註冊權杖 (已淘汰):
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens=registration_tokens,
)
response = messaging.send_each_for_multicast(message)
if response.failure_count > 0:
responses = response.responses
failed_tokens = []
for idx, resp in enumerate(responses):
if not resp.success:
# The order of responses corresponds to the order of the registration tokens.
failed_tokens.append(registration_tokens[idx])
print(f'List of tokens that caused failures: {failed_tokens}')
Go
使用 FID (建議):
// Create a list containing up to 500 Firebase Installation IDs (FIDs).
// These Firebase Installation IDs (FIDs) come from the client FCM SDKs.
fids := []string{
"YOUR_REGISTERED_FID_1",
// ...
"YOUR_REGISTERED_FID_N",
}
message := &messaging.MulticastMessage{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Fids: fids,
}
br, err := client.SendEachForMulticast(ctx, message)
if err != nil {
log.Fatalln(err)
}
if br.FailureCount > 0 {
var failedFids []string
for idx, resp := range br.Responses {
if !resp.Success {
// The order of responses corresponds to the order of the destination FIDs.
failedFids = append(failedFids, fids[idx])
}
}
fmt.Printf("List of FIDs that caused failures: %v\n", failedFids)
}
使用註冊權杖 (已淘汰):
// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Tokens: registrationTokens,
}
br, err := client.SendEachForMulticast(context.Background(), message)
if err != nil {
log.Fatalln(err)
}
if br.FailureCount > 0 {
var failedTokens []string
for idx, resp := range br.Responses {
if !resp.Success {
// The order of responses corresponds to the order of the registration tokens.
failedTokens = append(failedTokens, registrationTokens[idx])
}
}
fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}
C#
使用 FID (建議):
// These Firebase Installation IDs (FIDs) come from the client FCM SDKs.
var fids = new List<string>()
{
"YOUR_REGISTERED_FID_1",
// ...
"YOUR_REGISTERED_FID_N",
};
var message = new MulticastMessage()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Fids = fids,
};
var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(message);
if (response.FailureCount > 0)
{
var failedFids = new List<string>();
for (var i = 0; i < response.Responses.Count; i++)
{
if (!response.Responses[i].IsSuccess)
{
// The order of responses corresponds to the order of the destination FIDs.
failedFids.add(fids[i]);
}
}
Console.WriteLine($"List of FIDs that caused failures: {string.Join(", ", failedFids)}");
}
使用註冊權杖 (已淘汰):
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
var message = new MulticastMessage()
{
#pragma warning disable CS0618
Tokens = registrationTokens,
#pragma warning restore CS0618
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
};
var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(message);
if (response.FailureCount > 0)
{
var failedTokens = new List<string>();
for (var i = 0; i < response.Responses.Count; i++)
{
if (!response.Responses[i].IsSuccess)
{
// The order of responses corresponds to the order of the registration tokens.
failedTokens.Add(registrationTokens[i]);
}
}
Console.WriteLine($"List of tokens that caused failures: {failedTokens}");
}
傳送訊息清單
Admin SDK 最多可傳送 500 則訊息。這項功能可用於建立自訂訊息集,並傳送給不同收件者,包括主題、Firebase 安裝 ID (FID) 或裝置註冊權杖。舉例來說,如果需要向不同目標對象傳送不同訊息,就可以使用這項功能。
Node.js
使用混合目標 (建議做法):
// Create a list containing up to 500 messages.
const messages = [
{
notification: { title: 'Price drop', body: '5% off all electronics' },
fid: 'YOUR_REGISTERED_FID', // Using FID (Recommended)
},
{
notification: { title: 'Price drop', body: '2% off all books' },
token: 'YOUR_REGISTRATION_TOKEN', // Using token (Deprecated)
},
{
notification: { title: 'Price drop', body: '10% off all shoes' },
topic: 'readers-club',
}
];
getMessaging().sendEach(messages)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
使用註冊權杖 (已淘汰):
// Create a list containing up to 500 messages.
const messages = [];
messages.push({
notification: { title: 'Price drop', body: '5% off all electronics' },
token: registrationToken,
});
messages.push({
notification: { title: 'Price drop', body: '2% off all books' },
topic: 'readers-club',
});
getMessaging().sendEach(messages)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
Java
使用混合目標 (建議做法):
// Create a list containing up to 500 messages.
List<Message> messages = new ArrayList<>();
messages.add(Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("5% off all electronics")
.build())
.setFid("YOUR_REGISTERED_FID") // Using FID (Recommended)
.build());
messages.add(Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("2% off all books")
.build())
.setToken("YOUR_REGISTRATION_TOKEN") // Using token (Deprecated)
.build());
messages.add(Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("10% off all shoes")
.build())
.setTopic("readers-club")
.build());
BatchResponse response = FirebaseMessaging.getInstance().sendEach(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
使用註冊權杖 (已淘汰):
// Create a list containing up to 500 messages.
List<Message> messages = Arrays.asList(
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("5% off all electronics")
.build())
.setToken(registrationToken)
.build(),
// ...
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("2% off all books")
.build())
.setTopic("readers-club")
.build()
);
BatchResponse response = FirebaseMessaging.getInstance().sendEach(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
Python
使用混合目標 (建議做法):
# Create a list containing up to 500 messages.
messages = [
messaging.Message(
notification=messaging.Notification('Price drop', '5% off all electronics'),
fid='YOUR_REGISTERED_FID', # Using FID (Recommended)
),
messaging.Message(
notification=messaging.Notification('Price drop', '2% off all books'),
token='YOUR_REGISTRATION_TOKEN', # Using token (Deprecated)
),
messaging.Message(
notification=messaging.Notification('Price drop', '10% off all shoes'),
topic='readers-club',
),
]
response = messaging.send_each(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))
使用註冊權杖 (已淘汰):
# Create a list containing up to 500 messages.
messages = [
messaging.Message(
notification=messaging.Notification('Price drop', '5% off all electronics'),
token=registration_token,
),
# ...
messaging.Message(
notification=messaging.Notification('Price drop', '2% off all books'),
topic='readers-club',
),
]
response = messaging.send_each(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print(f'{response.success_count} messages were sent successfully')
Go
使用混合目標 (建議做法):
// Create a list containing up to 500 messages.
messages := []*messaging.Message{
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "5% off all electronics",
},
Fid: "YOUR_REGISTERED_FID", // Using FID (Recommended)
},
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "2% off all books",
},
Token: "YOUR_REGISTRATION_TOKEN", // Using token (Deprecated)
},
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "10% off all shoes",
},
Topic: "readers-club",
},
}
br, err := client.SendEach(ctx, messages)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
使用註冊權杖 (已淘汰):
// Create a list containing up to 500 messages.
messages := []*messaging.Message{
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "5% off all electronics",
},
Token: registrationToken,
},
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "2% off all books",
},
Topic: "readers-club",
},
}
br, err := client.SendEach(context.Background(), messages)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
C#
使用混合目標 (建議做法):
// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "5% off all electronics",
},
Fid = "YOUR_REGISTERED_FID", // Using FID (Recommended)
},
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "2% off all books",
},
Token = "YOUR_REGISTRATION_TOKEN", // Using token (Deprecated)
},
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "10% off all shoes",
},
Topic = "readers-club",
},
};
var response = await FirebaseMessaging.DefaultInstance.SendEachAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");
使用註冊權杖 (已淘汰):
// Create a list containing up to 500 messages.
var messages = new List<Message>()
{
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "5% off all electronics",
},
#pragma warning disable CS0618
Token = registrationToken,
#pragma warning restore CS0618
},
new Message()
{
Notification = new Notification()
{
Title = "Price drop",
Body = "2% off all books",
},
Topic = "readers-club",
},
};
var response = await FirebaseMessaging.DefaultInstance.SendEachAsync(messages);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");