ส่งข้อความโดยใช้ Firebase Admin SDK

หากยังไม่ได้ตั้งค่า Firebase Admin SDK ให้ทำตาม คู่มือเพื่อตั้งค่า Firebase Admin SDK ในเซิร์ฟเวอร์

เปิดใช้ FCM HTTP v1 API

เปิดใช้ Cloud Messaging API ใน หน้าการตั้งค่า Cloud Messaging สำหรับโปรเจ็กต์

ให้สิทธิ์บัญชีบริการจากโปรเจ็กต์อื่น

คุณสามารถส่งข้อความสำหรับโปรเจ็กต์หนึ่ง ซึ่งก็คือ "โปรเจ็กต์ปลายทาง" ขณะที่ใช้บัญชีบริการในโปรเจ็กต์อื่น ซึ่งก็คือ "โปรเจ็กต์ผู้ส่ง" วิธีนี้ช่วยให้คุณจัดการบัญชีบริการแบบรวมศูนย์ในโปรเจ็กต์เดียวขณะส่งข้อความในนามของผู้อื่น หากต้องการทราบวิธีดำเนินการ ให้ทำตามขั้นตอนต่อไปนี้

  1. ตรวจสอบว่าได้เปิดใช้ Firebase Cloud Messaging API ในโปรเจ็กต์ผู้ส่งแล้ว
  2. สร้างบัญชีบริการ ในโปรเจ็กต์ ผู้ส่ง
  3. ในโปรเจ็กต์ปลายทาง ให้สิทธิ์อีเมลของบัญชีบริการเป็น ผู้ดูแลระบบ Firebase Cloud Messaging API ในหน้า IAM ซึ่งจะช่วยให้บัญชีบริการจากโปรเจ็กต์อื่นส่งข้อความไปยังโปรเจ็กต์ปลายทางได้
  4. เริ่มต้น 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>",
});

ส่งข้อความไปยังอุปกรณ์ที่เฉพาะเจาะจง

หากต้องการส่งไปยังอุปกรณ์เครื่องเดียวที่เฉพาะเจาะจง ให้ส่งโทเค็นการลงทะเบียนของอุปกรณ์ตามที่แสดง

Node.js

// 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

// 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

# 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

// 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#

// 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" },
    },
    Token = registrationToken,
};

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

เมื่อส่งสำเร็จ เมธอดการส่งแต่ละรายการจะแสดงรหัสข้อความ Firebase Admin SDK จะแสดง สตริงรหัสในรูปแบบ projects/{project_id}/messages/{message_id}

ส่งข้อความเดียวไปยังอุปกรณ์หลายเครื่อง

Admin FCM SDK ช่วยให้คุณส่งข้อความแบบมัลติแคสต์ไปยังรายการโทเค็นการลงทะเบียนอุปกรณ์ได้ คุณสามารถใช้ฟีเจอร์นี้เมื่อต้องการส่งข้อความเดียวกันไปยังอุปกรณ์จำนวนมาก คุณสามารถระบุโทเค็นการลงทะเบียนอุปกรณ์ได้สูงสุด 500 รายการต่อการเรียกใช้

ค่าที่แสดงจะรวมรายการโทเค็นที่สอดคล้องกับลำดับของโทเค็นอินพุต ซึ่งจะมีประโยชน์เมื่อคุณต้องการตรวจสอบว่าโทเค็นใดทำให้เกิด ข้อผิดพลาด แล้วจัดการโทเค็นเหล่านั้นอย่างเหมาะสม

Node.js

// 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

// 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

# 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

// 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#

// 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()
{
    Tokens = registrationTokens,
    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 รายการ คุณสามารถใช้ฟีเจอร์นี้เพื่อสร้างชุดข้อความที่ปรับแต่งเองและส่งไปยังผู้รับต่างๆ รวมถึงหัวข้อหรือโทเค็นการลงทะเบียนอุปกรณ์ที่เฉพาะเจาะจง เช่น คุณสามารถใช้ฟีเจอร์นี้เมื่อต้องการส่งข้อความที่แตกต่างกันเล็กน้อยไปยังกลุ่มเป้าหมายต่างๆ

Node.js

// 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 = 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'),
        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",
		},
		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",
        },
        Token = registrationToken,
    },
    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");