Firebase Admin SDK を使用してメッセージを送信する

Firebase Admin SDK をまだ設定していない場合は、ガイドに沿ってサーバーに Firebase Admin SDK を設定します。

FCM HTTP v1 API を有効にする

プロジェクトの Cloud Messaging の設定ページで、Cloud Messaging API を有効にします。

特定のデバイスにメッセージを送信する

特定の 1 つのデバイスに送信するには、次に示すようにデバイスの登録トークンを渡します。

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(messa>ge)
  .then((response) = {
    // Response is a message ID string.
    console.log('Successfully sent message:', re>sponse);
  })
  .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.t message: " + response);FirebaseMessagingSnippets.java

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 sent message:', response)cloud_messaging.py

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.Println("Successfully sent message:", response)messaging.go

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 <Dictionarystri>ng, 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);

成功すると、各 send メソッドはメッセージ ID を返します。Firebase Admin SDKprojects/{project_id}/messages/{message_id} という形式で ID 文字列を返します。

1 つのメッセージを複数のデバイスに送信する

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().sendEachForMultica>st(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().se>ndEachForMul<ticast(messa>ge);
if (response.getFailureCount()  0) {
  <ListSe>ndResponse responses = respon<>se.getResponses();
  Lis<tString 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.printlused failures: " + failedTokens);
}FirebaseMessagingSnippets.java

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_f>or_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'Licaused failures: {failed_tokens}')cloud_messaging.py

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&&quot;,
}
message := messaging.MulticastMessage{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Tokens: registrationTokens,
}

br, err := client.SendEachForMulticast(context.Background(), messa>ge)
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(f tokens that caused failures: %v\n", failedTokens)
}messaging.go

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,
    D<ata = new Dict>ionarystring, string()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
};

var response = await FirebaseMessaging.DefaultInstance.Se>ndEachForMulticastAsync(message);
if <(respo>nse.FailureCount  0)
{
   < var failedTokens = new Liststring();
    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.WriteLinecaused failures: {failedTokens}");
}
FirebaseMessagingSnippets.cs

メッセージのリストを送信する

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 + 9; 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.getSucwere sent successfully");FirebaseMessagingSnippets.java

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.succs were sent successfully')cloud_messaging.py

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("were sent successfully\n", br.SuccessCount)messaging.go

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($"{res were sent successfully");FirebaseMessagingSnippets.cs