Uygulama sunucusu gönderme istekleri oluşturun

Firebase Yönetici SDK'sını veya FCM uygulama sunucusu protokollerini kullanarak mesaj istekleri oluşturabilir ve bunları şu türdeki hedeflere gönderebilirsiniz:

  • Konu adı
  • Durum
  • Cihaz kayıt jetonu
  • Cihaz grubu adı (yalnızca protokol)

Önceden tanımlanmış alanlardan oluşan bir bildirim yüküyle, kendi kullanıcı tanımlı alanlarınızın veri yüküyle veya her iki veri yükünü içeren bir mesajla mesaj gönderebilirsiniz. Daha fazla bilgi için Mesaj türleri konusuna bakın.

Bu sayfadaki örnekler, Firebase Admin SDK ( Node , Java , Python , C# ve Go desteğine sahiptir) ve v1 HTTP protokolünü kullanarak bildirim mesajlarının nasıl gönderileceğini gösterir. Ayrıca, kullanımdan kaldırılan eski HTTP ve XMPP protokolleri aracılığıyla mesaj göndermeye yönelik rehberlik de bulunmaktadır.

Belirli cihazlara mesaj gönderme

Tek ve belirli bir cihaza göndermek için cihazın kayıt jetonunu gösterildiği gibi iletin. Kayıt belirteçleri hakkında daha fazla bilgi edinmek için platformunuzun istemci kurulum bilgilerine bakın.

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)

Gitmek

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

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

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

{
   "message":{
      "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
      "notification":{
        "body":"This is an FCM notification message!",
        "title":"FCM Message"
      }
   }
}

cURL komutu:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
   "notification":{
     "title":"FCM Message",
     "body":"This is an FCM Message"
   },
   "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

Başarı durumunda her gönderme yöntemi bir mesaj kimliği döndürür. Firebase Admin SDK, kimlik dizesini projects/{project_id}/messages/{message_id} biçiminde döndürür. HTTP protokolü yanıtı tek bir JSON anahtarıdır:

    {
      "name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
    }

Birden fazla cihaza mesaj gönderin

Yönetici FCM API'leri, bir mesajı cihaz kayıt belirteçleri listesine çok noktaya yayınlamanıza olanak tanır. Çağrı başına en fazla 500 cihaz kayıt jetonu belirtebilirsiniz.

Node.js

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

Java

// Create a list containing up to 500 registration tokens.
// 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().sendMulticast(message);
// 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 registration tokens.
# 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_multicast(message)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

Gitmek

// 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.SendMulticast(context.Background(), message)
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 registration tokens.
// 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);
// See the BatchResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} messages were sent successfully");

Dönüş değeri, giriş jetonlarının sırasına karşılık gelen jetonların bir listesidir. Bu, hangi belirteçlerin hatalarla sonuçlandığını kontrol etmek istediğinizde kullanışlıdır.

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().sendMulticast(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().sendMulticast(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_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('List of tokens that caused failures: {0}'.format(failed_tokens))

Gitmek

// 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.SendMulticast(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}");
}

Konulara mesaj gönder

İstemci uygulaması örneklerini istemci tarafındaki konuya abone olarak veya sunucu API'si aracılığıyla bir konu oluşturduktan sonra konuya ileti gönderebilirsiniz. FCM için ilk kez gönderme istekleri oluşturuyorsanız, önemli arka plan ve kurulum bilgileri için sunucu ortamınıza ve FCM kılavuzuna bakın.

Arka uçtaki gönderme mantığınızda, istediğiniz konu adını gösterildiği gibi belirtin:

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
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

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Gitmek

// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
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#

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See documentation on defining a message payload.
var message = new Message()
{
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

cURL komutu:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Konuların bir kombinasyonuna mesaj göndermek için, hedef konuları belirten bir boole ifadesi olan bir koşul belirtin. Örneğin, aşağıdaki koşul TopicA ve TopicB veya TopicC abone olan cihazlara mesaj gönderecektir:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM önce parantez içindeki koşulları değerlendirir, ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya abone olan kullanıcı mesajı almıyor. Aynı şekilde TopicA abone olmayan bir kullanıcı da mesajı alamamaktadır. Bu kombinasyonlar bunu alır:

  • TopicA ve TopicB
  • TopicA ve TopicC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz.

Bir koşula göndermek için:

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
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

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Gitmek

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Condition: condition,
}

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
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#

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Condition = condition,
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

cURL komutu:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "FCM Message",
    "body": "This is a Firebase Cloud Messaging Topic Message!",
  },
  "condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Cihaz gruplarına mesaj gönderme

Cihaz gruplarına mesaj göndermek için HTTP v1 API'sini kullanın. Şu anda cihaz gruplarına HTTP veya XMPP için kullanımdan kaldırılmış eski gönderme API'lerini veya eski protokolleri temel alan Node.js için Firebase Admin SDK'nın eski sürümlerinden herhangi birini kullanarak gönderim yapıyorsanız, HTTP v1'e geçiş yapmanızı kesinlikle öneririz. API'yi ilk fırsatta kullanın. Eski gönderme API'leri Haziran 2024'te devre dışı bırakılacak ve kaldırılacaktır.

Bir cihaz grubuna mesaj göndermek, gönderme isteklerini yetkilendirmek için aynı yöntemi kullanarak tek bir cihaza mesaj göndermeye çok benzer. token alanını grup bildirim anahtarına ayarlayın:

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

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

{
   "message":{
      "token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ",
      "data":{
        "hello": "This is a Firebase Cloud Messaging device group message!"
      }
   }
}

cURL komutu

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message":{
   "data":{
     "hello": "This is a Firebase Cloud Messaging device group message!"
   },
   "token":"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ"
}}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

Toplu mesaj gönderme

Yönetici SDK'ları mesajların toplu olarak gönderilmesini destekler. 500'e kadar mesajı tek bir grupta gruplandırabilir ve hepsini tek bir API çağrısında gönderebilirsiniz; bu, her mesaj için ayrı HTTP istekleri göndermeye göre önemli bir performans artışı sağlar.

Bu özellik, özelleştirilmiş bir dizi mesaj oluşturmak ve bunları konular veya belirli cihaz kayıt belirteçleri dahil olmak üzere farklı alıcılara göndermek için kullanılabilir. Bu özelliği, örneğin farklı hedef kitlelere aynı anda mesaj gövdesinde biraz farklı ayrıntılara sahip mesajlar göndermeniz gerektiğinde kullanın.

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().sendAll(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().sendAll(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_all(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))

Gitmek

// 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.SendAll(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");

Doğrudan önyüklemenin etkin olduğu mesajları gönder (yalnızca Android)

HTTP v1 veya eski HTTP API'lerini kullanarak doğrudan önyükleme modundaki cihazlara mesaj gönderebilirsiniz. Doğrudan önyükleme modundaki cihazlara göndermeden önce, istemci cihazlarının doğrudan önyükleme modunda FCM mesajlarını almasını sağlayacak adımları tamamladığınızdan emin olun.

FCM v1 HTTP API'sini kullanarak gönderin

Mesaj isteği, istek gövdesinin AndroidConfig seçeneklerinde "direct_boot_ok" : true anahtarını içermelidir. Örneğin:

https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send
Content-Type:application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

{
  "message":{
    "token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
    "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "android": {
      "direct_boot_ok": true,
    },
}

FCM eski HTTP API'sini kullanarak gönderin

Mesaj isteği, istek gövdesinin en üst düzeyinde "direct_boot_ok" : true anahtarını içermelidir. Örneğin:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  "direct_boot_ok" : true
}

İstek gövdesinde bu anahtarla gönderilen mesajlar, o anda doğrudan önyükleme modunda olan (ve ayrıca bu modda olmadığında) cihazlardaki uygulamalar tarafından işlenebilir.

Mesajları platformlar arasında özelleştirin

Firebase Yönetici SDK'sı ve FCM v1 HTTP protokolünün her ikisi de mesaj isteklerinizin, message nesnesindeki mevcut tüm alanları ayarlamasına olanak tanır. Bu içerir:

  • mesajı alan tüm uygulama örnekleri tarafından yorumlanacak ortak bir alan kümesi.
  • AndroidConfig ve WebpushConfig gibi platforma özgü alan kümeleri, yalnızca belirtilen platformda çalışan uygulama örnekleri tarafından yorumlanır.

Platforma özel bloklar, mesajların alındığında doğru şekilde işlenmesini sağlamak amacıyla farklı platformlar için mesajları özelleştirme esnekliği sağlar. FCM arka ucu belirtilen tüm parametreleri dikkate alacak ve mesajı her platform için özelleştirecektir.

Ortak alanlar ne zaman kullanılmalı?

Aşağıdaki durumlarda ortak alanları kullanın:

  • Tüm platformlardaki uygulama örneklerini hedefleme (Apple, Android ve web)
  • Konulara mesaj gönderme

Platformdan bağımsız olarak tüm uygulama örnekleri aşağıdaki ortak alanları yorumlayabilir:

Platforma özgü alanlar ne zaman kullanılmalı?

Aşağıdakileri yapmak istediğinizde platforma özel alanları kullanın:

  • Alanları yalnızca belirli platformlara gönder
  • Ortak alanlara ek olarak platforma özel alanlar gönderin

Değerleri yalnızca belirli platformlara göndermek istediğinizde ortak alanları kullanmayın ; platforma özgü alanları kullanın. Örneğin, yalnızca Apple platformlarına ve web'e bildirim göndermek, ancak Android'e göndermemek için biri Apple ve diğeri web için olmak üzere iki ayrı alan kümesi kullanmanız gerekir.

Belirli teslimat seçeneklerine sahip mesajlar gönderirken bunları ayarlamak için platforma özel alanları kullanın. İsterseniz platform başına farklı değerler belirleyebilirsiniz. Ancak platformlar arasında temelde aynı değeri ayarlamak istediğinizde bile platforma özgü alanları kullanmanız gerekir. Bunun nedeni, her platformun değeri biraz farklı yorumlayabilmesidir; örneğin, yaşam süresi Android'de saniye cinsinden bir sona erme süresi olarak ayarlanırken, Apple'da bir son kullanma tarihi olarak ayarlanır.

Örnek: renk ve simge seçeneklerine sahip bildirim mesajı

Bu örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı ve içeriği gönderir, ancak aynı zamanda Android cihazlara platforma özgü bazı geçersiz kılmalar da gönderir.

Android için istek, Android cihazlarda görüntülenecek özel bir simge ve renk ayarlar. AndroidNotification referansında belirtildiği gibi, renk #rrggbb biçiminde belirtilir ve görüntünün, Android uygulamasına özgü, çizilebilir bir simge kaynağı olması gerekir.

Burada kullanıcının cihazındaki görsel efektin yaklaşık bir tahmini verilmiştir:

Biri özel simge ve renk görüntüleyen iki cihazın basit çizimi

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: '`$FooCorp` up 1.43% on the day',
    body: 'FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  android: {
    notification: {
      icon: 'stock_ticker_update',
      color: '#7e55c3'
    }
  },
  topic: topicName,
};

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

Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setAndroidConfig(AndroidConfig.builder()
        .setTtl(3600 * 1000)
        .setNotification(AndroidNotification.builder()
            .setIcon("stock_ticker_update")
            .setColor("#f45342")
            .build())
        .build())
    .setApnsConfig(ApnsConfig.builder()
        .setAps(Aps.builder()
            .setBadge(42)
            .build())
        .build())
    .setTopic("industry-tech")
    .build();

Python

message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    android=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=3600),
        priority='normal',
        notification=messaging.AndroidNotification(
            icon='stock_ticker_update',
            color='#f45342'
        ),
    ),
    apns=messaging.APNSConfig(
        payload=messaging.APNSPayload(
            aps=messaging.Aps(badge=42),
        ),
    ),
    topic='industry-tech',
)

Gitmek

oneHour := time.Duration(1) * time.Hour
badge := 42
message := &messaging.Message{
	Notification: &messaging.Notification{
		Title: "$GOOG up 1.43% on the day",
		Body:  "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
	},
	Android: &messaging.AndroidConfig{
		TTL: &oneHour,
		Notification: &messaging.AndroidNotification{
			Icon:  "stock_ticker_update",
			Color: "#f45342",
		},
	},
	APNS: &messaging.APNSConfig{
		Payload: &messaging.APNSPayload{
			Aps: &messaging.Aps{
				Badge: &badge,
			},
		},
	},
	Topic: "industry-tech",
}

C#

var message = new Message
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Android = new AndroidConfig()
    {
        TimeToLive = TimeSpan.FromHours(1),
        Notification = new AndroidNotification()
        {
            Icon = "stock_ticker_update",
            Color = "#f45342",
        },
    },
    Apns = new ApnsConfig()
    {
        Aps = new Aps()
        {
            Badge = 42,
        },
    },
    Topic = "industry-tech",
};

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"`$FooCorp` up 1.43% on the day",
       "body":"FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day."
     },
     "android":{
       "notification":{
         "icon":"stock_ticker_update",
         "color":"#7e55c3"
       }
     }
   }
 }

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlara ilişkin tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: özel görsel içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir ancak aynı zamanda bir resim de gönderir. Burada kullanıcının cihazındaki görsel efektin yaklaşık bir tahmini verilmiştir:

Bir ekran bildirimindeki görüntünün basit çizimi

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Sparky says hello!'
  },
  android: {
    notification: {
      imageUrl: 'https://foo.bar.pizza-monster.png'
    }
  },
  apns: {
    payload: {
      aps: {
        'mutable-content': 1
      }
    },
    fcm_options: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  webpush: {
    headers: {
      image: 'https://foo.bar.pizza-monster.png'
    }
  },
  topic: topicName,
};

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

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Sparky says hello!",
     },
     "android":{
       "notification":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "mutable-content":1
         }
       },
       "fcm_options": {
           "image":"https://foo.bar/pizza-monster.png"
       }
     },
     "webpush":{
       "headers":{
         "image":"https://foo.bar/pizza-monster.png"
       }
     }
   }
 }

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlara ilişkin tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: ilişkili tıklama eylemi içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir, ancak aynı zamanda kullanıcının bildirimle etkileşimde bulunmasına yanıt olarak uygulamanın gerçekleştirmesi için bir eylem de gönderir. Burada kullanıcının cihazındaki görsel efektin yaklaşık bir tahmini verilmiştir:

Bir web sayfasını açan kullanıcının dokunuşunun basit çizimi

Node.js

const topicName = 'industry-tech';

const message = {
  notification: {
    title: 'Breaking News....'
  },
  android: {
    notification: {
      clickAction: 'news_intent'
    }
  },
  apns: {
    payload: {
      aps: {
        'category': 'INVITE_CATEGORY'
      }
    }
  },
  webpush: {
    fcmOptions: {
      link: 'breakingnews.html'
    }
  },
  topic: topicName,
};

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

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
     "topic":"industry-tech",
     "notification":{
       "title":"Breaking News...",
     },
     "android":{
       "notification":{
         "click_action":"news_intent"
       }
     },
     "apns":{
       "payload":{
         "aps":{
           "category" : "INVITE_CATEGORY"
         }
       },
     },
     "webpush":{
       "fcm_options":{
         "link":"breakingnews.html"
       }
     }
   }
 }

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlara ilişkin tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

Örnek: yerelleştirme seçeneklerini içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, istemcinin yerelleştirilmiş mesajları görüntülemesi için yerelleştirme seçeneklerini gönderir. Burada kullanıcının cihazındaki görsel efektin yaklaşık bir tahmini verilmiştir:

İngilizce ve İspanyolca metin görüntüleyen iki cihazın basit çizimi

Node.js

var topicName = 'industry-tech';

var message = {
  android: {
    ttl: 3600000,
    notification: {
      bodyLocKey: 'STOCK_NOTIFICATION_BODY',
      bodyLocArgs: ['FooCorp', '11.80', '835.67', '1.43']
    }
  },
  apns: {
    payload: {
      aps: {
        alert: {
          locKey: 'STOCK_NOTIFICATION_BODY',
          locArgs: ['FooCorp', '11.80', '835.67', '1.43']
        }
      }
    }
  },
  topic: topicName,
};

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

DİNLENMEK

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
             "topic":"Tech",
             "android":{
               "ttl":"3600s",
               "notification":{
                 "body_loc_key": "STOCK_NOTIFICATION_BODY",
                 "body_loc_args":  ["FooCorp", "11.80", "835.67", "1.43"],
               },
             },
             "apns":{
               "payload":{
                 "aps":{
                   "alert" : {
                     "loc-key": "STOCK_NOTIFICATION_BODY",
                     "loc-args":  ["FooCorp", "11.80", "835.67", "1.43"],
                    },
                 },
               },
             },
  },
}'

İleti gövdesindeki platforma özgü bloklarda bulunan anahtarlara ilişkin tüm ayrıntılar için HTTP v1 referans belgelerine bakın.

HTTP v1 API'si için REST hata kodları

HTTP v1 API'sine ilişkin HTTP hata yanıtları bir hata kodu, bir hata mesajı ve hata durumu içerir. Ayrıca hatayla ilgili daha fazla ayrıntı içeren bir details dizisi de içerebilirler.

Aşağıda iki örnek hata yanıtı verilmiştir:

Örnek 1: Veri mesajında ​​geçersiz değer bulunan bir HTTP v1 API isteğinden gelen hata yanıtı

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "message.data[0].value",
            "description": "Invalid value at 'message.data[0].value' (TYPE_STRING), 12"
          }
        ]
      }
    ]
  }
}

Örnek 2: Geçersiz kayıt belirtecine sahip bir HTTP v1 API isteğinden gelen hata yanıtı

{
  "error": {
    "code": 400,
    "message": "The registration token is not a valid FCM registration token",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError",
        "errorCode": "INVALID_ARGUMENT"
      }
    ]
   }
}

Her iki mesajın da aynı kod ve duruma sahip olduğunu ancak ayrıntılar dizisinin farklı türlerde değerler içerdiğini unutmayın. İlk örnekte, istek değerlerinde bir hata olduğunu belirten type.googleapis.com/google.rpc.BadRequest türü vardır. type.googleapis.com/google.firebase.fcm.v1.FcmError türündeki ikinci örnekte FCM'ye özgü bir hata var. Birçok hata için ayrıntılar dizisi, hata ayıklamak ve çözüm bulmak için ihtiyaç duyacağınız bilgileri içerir.

Aşağıdaki tabloda FCM v1 REST API hata kodları ve açıklamaları listelenmektedir.

Hata kodu Açıklama ve Çözüm Adımları
UNSPECIFIED_ERROR Bu hata hakkında daha fazla bilgi mevcut değil. Hiçbiri.
INVALID_ARGUMENT (HTTP hata kodu = 400) İstek parametreleri geçersizdi. Hangi alanın geçersiz olduğunu belirtmek için google.rpc.BadRequest türünde bir uzantı döndürülür. Olası nedenler arasında geçersiz kayıt, geçersiz paket adı, çok büyük mesaj, geçersiz veri anahtarı, geçersiz TTL veya diğer geçersiz parametreler yer alır.
Geçersiz kayıt : Sunucuya ilettiğiniz kayıt jetonunun biçimini kontrol edin. İstemci uygulamasının FCM'ye kaydolurken aldığı kayıt jetonuyla eşleştiğinden emin olun. Belirteci kesmeyin veya ek karakterler eklemeyin.
Geçersiz paket adı : İletinin, paket adı istekte iletilen değerle eşleşen bir kayıt belirtecine gönderildiğinden emin olun.
Mesaj çok büyük : Bir mesaja dahil edilen yük verilerinin toplam boyutunun FCM sınırlarını aşmadığını kontrol edin: çoğu mesaj için 4096 bayt veya konulara yönelik mesajlar için 2048 bayt. Buna hem anahtarlar hem de değerler dahildir.
Geçersiz veri anahtarı : Yük verilerinin, FCM tarafından dahili olarak kullanılan bir anahtar (from, gcm veya google'ın ön eki olan herhangi bir değer gibi) içermediğini kontrol edin. Bazı kelimelerin (çöküş_anahtarı gibi) da FCM tarafından kullanıldığını ancak veri yükünde izin verildiğini, bu durumda veri yükü değerinin FCM değeri tarafından geçersiz kılınacağını unutmayın.
Geçersiz TTL : ttl'de kullanılan değerin, 0 ile 2.419.200 (4 hafta) arasında saniye cinsinden bir süreyi temsil eden bir tam sayı olup olmadığını kontrol edin.
Geçersiz parametreler : Sağlanan parametrelerin doğru ada ve türe sahip olup olmadığını kontrol edin.
UNREGISTERED (HTTP hata kodu = 404) Uygulama örneğinin FCM'deki kaydı kaldırıldı. Bu genellikle kullanılan tokenın artık geçerli olmadığı ve yeni bir token kullanılması gerektiği anlamına gelir. Bu hata, eksik kayıt belirteçlerinden veya kaydedilmemiş belirteçlerden kaynaklanabilir.
Eksik Kayıt : Mesajın hedefi bir token değeri ise isteğin bir kayıt belirteci içerip içermediğini kontrol edin.
Kayıtlı değil : Mevcut bir kayıt jetonunun geçerliliği, aşağıdakiler de dahil olmak üzere çeşitli senaryolarda sona erebilir:
- İstemci uygulamasının FCM'deki kaydı silinirse.
- İstemci uygulamasının kaydı otomatik olarak silinirse, bu durum kullanıcının uygulamayı kaldırması durumunda meydana gelebilir. Örneğin, iOS'ta APN Geri Bildirim Hizmeti, APN belirtecinin geçersiz olduğunu bildirdiyse.
- Kayıt jetonunun süresi dolarsa (örneğin Google, kayıt jetonlarını yenilemeye karar verebilir veya iOS cihazları için APNs jetonunun süresi dolmuşsa).
- İstemci uygulaması güncellendiyse ancak yeni sürüm mesaj alacak şekilde yapılandırılmadıysa.
Tüm bu durumlarda, bu kayıt jetonunu uygulama sunucusundan kaldırın ve mesaj göndermek için kullanmayı bırakın.
SENDER_ID_MISMATCH (HTTP hata kodu = 403) Kimliği doğrulanmış gönderen kimliği, kayıt belirtecinin gönderen kimliğinden farklıdır. Bir kayıt jetonu belirli bir gönderen grubuna bağlanır. Bir istemci uygulaması FCM'ye kaydolduğunda hangi gönderenlerin mesaj göndermesine izin verildiğini belirtmelidir. İstemci uygulamasına mesaj gönderirken bu gönderen kimliklerinden birini kullanmalısınız. Farklı bir gönderene geçerseniz mevcut kayıt jetonları çalışmaz.
QUOTA_EXCEEDED (HTTP hata kodu = 429) İleti hedefi için gönderme sınırı aşıldı. Hangi kotanın aşıldığını belirtmek için google.rpc.QuotaFailure türünde bir uzantı döndürülür. Bu hata, mesaj hızı kotasının aşılması, cihaz mesaj hızı kotasının aşılması veya konu mesaj hızı kotasının aşılmasından kaynaklanabilir.
Mesaj hızı aşıldı : Mesajların gönderilme hızı çok yüksek. Genel mesaj gönderme hızınızı azaltmalısınız. Reddedilen mesajları yeniden denemek için minimum başlangıç ​​gecikmesi olan üstel geri çekmeyi kullanın.
Cihaz mesaj hızı aşıldı : Belirli bir cihaza gönderilen mesajların oranı çok yüksek. Tek bir cihaza yönelik mesaj hızı sınırına bakın . Bu cihaza gönderilen mesajların sayısını azaltın ve göndermeyi yeniden denemek için üstel gerilemeyi kullanın.
Konu mesaj oranı aşıldı : Belirli bir konuya ilişkin abonelere gönderilen mesaj oranı çok yüksek. Bu konu için gönderilen iletilerin sayısını azaltın ve göndermeyi yeniden denemek için minimum başlangıç ​​gecikmesi olan üstel gerilemeyi kullanın.
UNAVAILABLE (HTTP hata kodu = 503) Sunucu aşırı yüklenmiş. Sunucu isteği zamanında işleyemedi. Aynı isteği yeniden deneyin, ancak şunları yapmalısınız:
- FCM Bağlantı Sunucusundan gelen yanıtta yer alıyorsa Retry-Aft başlığını dikkate alın.
- Yeniden deneme mekanizmanıza üstel geri çekilme uygulayın. (örneğin, ilk tekrar denemeden önce bir saniye beklediyseniz, bir sonraki denemeden önce en az iki saniye bekleyin, ardından 4 saniye vb. bekleyin). Birden fazla mesaj gönderiyorsanız titremeyi uygulamayı düşünün. Daha fazla bilgi için bkz . Yeniden denemeleri işleme . Soruna neden olan gönderenler reddedilen listeye alınma riskiyle karşı karşıyadır.
INTERNAL (HTTP hata kodu = 500) Bilinmeyen bir dahili hata oluştu. Sunucu, isteği işlemeye çalışırken bir hatayla karşılaştı. Yeniden denemeleri işleme bölümündeki önerileri izleyerek aynı isteği yeniden deneyebilirsiniz . Hata devam ederse lütfen Firebase desteğiyle iletişime geçin.
THIRD_PARTY_AUTH_ERROR (HTTP hata kodu = 401) APN sertifikası veya web push kimlik doğrulama anahtarı geçersiz veya eksikti. Bir iOS cihazını veya web push kaydını hedefleyen bir mesaj gönderilemedi. Geliştirme ve üretim kimlik bilgilerinizin geçerliliğini kontrol edin.

Yönetici hata kodları

Aşağıdaki tabloda Firebase Admin FCM API hata kodları ve bunların açıklamaları, önerilen çözüm adımları da dahil olmak üzere listelenmektedir.

Hata kodu Açıklama ve Çözüm Adımları
messaging/invalid-argument Bir FCM yöntemine geçersiz bir bağımsız değişken sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-recipient Amaçlanan ileti alıcısı geçersiz. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-payload Geçersiz bir mesaj yükü nesnesi sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-data-payload-key Veri mesajı verisi geçersiz bir anahtar içeriyor. Kısıtlanmış anahtarlar için DataMessagePayload referans belgelerine bakın.
messaging/payload-size-limit-exceeded Sağlanan mesaj yükü, FCM boyut sınırlarını aşıyor. Çoğu mesaj için sınır 4096 bayttır. Konulara gönderilen mesajlar için sınır 2048 bayttır. Toplam veri yükü boyutu hem anahtarları hem de değerleri içerir.
messaging/invalid-options Geçersiz bir mesaj seçenekleri nesnesi sağlandı. Hata mesajı ek bilgiler içermelidir.
messaging/invalid-registration-token Geçersiz kayıt jetonu sağlandı. İstemci uygulamasının FCM'ye kaydolurken aldığı kayıt jetonuyla eşleştiğinden emin olun. Kesmeyin veya ek karakterler eklemeyin.
messaging/registration-token-not-registered Sağlanan kayıt jetonu kayıtlı değil. Daha önce geçerli bir kayıt jetonunun kaydı, aşağıdakiler de dahil olmak üzere çeşitli nedenlerden dolayı iptal edilebilir:
  • İstemci uygulamasının FCM'deki kaydı kaldırıldı.
  • İstemci uygulamasının kaydı otomatik olarak iptal edildi. Bu durum, kullanıcının uygulamayı kaldırması veya Apple platformlarında APN Geri Bildirim Hizmeti'nin APN belirtecinin geçersiz olduğunu bildirmesi durumunda meydana gelebilir.
  • Kayıt jetonunun süresi doldu. Örneğin Google, kayıt jetonlarını yenilemeye karar verebilir veya Apple cihazları için APN jetonunun süresi dolmuş olabilir.
  • İstemci uygulaması güncellendi ancak yeni sürüm mesaj alacak şekilde yapılandırılmadı.
Tüm bu durumlarda, bu kayıt jetonunu kaldırın ve mesaj göndermek için kullanmayı bırakın.
messaging/invalid-package-name İleti, paket adı sağlanan restrictedPackageName seçeneğiyle eşleşmeyen bir kayıt belirtecine gönderilmiştir.
messaging/message-rate-exceeded Belirli bir hedefe gönderilen mesajların oranı çok yüksektir. Bu cihaza veya konuya gönderilen mesajların sayısını azaltın ve bu hedefe hemen tekrar mesaj göndermeyi denemeyin.
messaging/device-message-rate-exceeded Belirli bir cihaza gönderilen mesajların oranı çok yüksek. Bu cihaza gönderilen mesajların sayısını azaltın ve bu cihaza göndermeyi hemen yeniden denemeyin.
messaging/topics-message-rate-exceeded Belirli bir konuya ilişkin abonelere mesaj gönderilme oranı çok yüksektir. Bu konuya gönderilen mesaj sayısını azaltın ve bu konuya hemen mesaj göndermeyi denemeyin.
messaging/too-many-topics Bir kayıt jetonu maksimum sayıda konuya abone oldu ve artık abone olunamaz.
messaging/invalid-apns-credentials Gerekli APN SSL sertifikası yüklenmediğinden veya süresi dolduğundan, bir Apple cihazını hedefleyen bir mesaj gönderilemedi. Geliştirme ve üretim sertifikalarınızın geçerliliğini kontrol edin.
messaging/mismatched-credential Bu SDK'nın kimliğini doğrulamak için kullanılan kimlik bilgisinin, sağlanan kayıt jetonuna karşılık gelen cihaza mesaj gönderme izni yok. Kimlik bilgisi ve kayıt jetonunun aynı Firebase projesine ait olduğundan emin olun. Firebase Yönetici SDK'larının kimliğinin nasıl doğrulanacağına ilişkin belgeler için Firebase'i uygulamanıza ekleme konusuna bakın.
messaging/authentication-error SDK, FCM sunucularında kimlik doğrulaması yapamadı. Firebase Yönetici SDK'sının kimliğini, FCM mesajları göndermek için uygun izinlere sahip bir kimlik bilgisiyle doğruladığınızdan emin olun. Firebase Yönetici SDK'larının kimliğinin nasıl doğrulanacağına ilişkin belgeler için Firebase'i uygulamanıza ekleme konusuna bakın.
messaging/server-unavailable FCM sunucusu isteği zamanında işleyemedi. Aynı isteği yeniden denemelisiniz ancak şunları yapmalısınız:
  • FCM Bağlantı Sunucusundan gelen yanıtta yer alıyorsa Retry-After başlığını dikkate alın.
  • Yeniden deneme mekanizmanıza üstel geri çekilme uygulayın. Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz, bir sonraki denemeden önce en az iki saniye bekleyin, ardından dört saniye vb. bekleyin. Birden fazla mesaj gönderiyorsanız, aynı anda tüm mesajlar için yeni bir istekte bulunulmasını önlemek amacıyla her birini bağımsız olarak rastgele ek bir miktar geciktirin.
Soruna neden olan gönderenler kara listeye alınma riskiyle karşı karşıyadır.
messaging/internal-error FCM sunucusu isteği işlemeye çalışırken bir hatayla karşılaştı. Yukarıdaki messaging/server-unavailable satırında listelenen gereksinimleri izleyerek aynı isteği yeniden deneyebilirsiniz. Hata devam ederse lütfen sorunu Hata Raporu destek kanalımıza bildirin.
messaging/unknown-error Bilinmeyen bir sunucu hatası döndürüldü. Daha fazla ayrıntı için hata mesajındaki ham sunucu yanıtına bakın. Bu hatayı alırsanız lütfen hata mesajının tamamını Hata Raporu destek kanalımıza bildirin.

Eski uygulama sunucusu protokollerini kullanarak mesaj gönderin

Şu anda eski protokolleri kullanıyorsanız mesaj isteklerini bu bölümde gösterildiği gibi oluşturun. HTTP aracılığıyla birden fazla platforma gönderim yapıyorsanız v1 protokolünün mesaj isteklerinizi büyük ölçüde basitleştirebileceğini unutmayın.

Belirli cihazlara mesaj gönderme

Belirli cihazlara mesaj göndermek için to anahtarını belirli uygulama örneğinin kayıt belirtecine ayarlayın. Kayıt belirteçleri hakkında daha fazla bilgi edinmek için platformunuzun istemci kurulum bilgilerine bakın.

HTTP POST isteği

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

HTTP yanıtı

{ "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}

XMPP mesajı

<message id="">
  <gcm xmlns="google:mobile:data">
    { "data": {
      "score": "5x1",
      "time": "15:10"
    },
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
  }
  </gcm>
</message>

XMPP yanıtı

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "from":"REGID",
      "message_id":"m-1366082849205"
      "message_type":"ack"
  }
  </gcm>
</message>

XMPP bağlantı sunucusu yanıtlar için başka seçenekler de sağlar. Bkz . Sunucu yanıt biçimi .

İstemci uygulamalarına aşağı akış mesajları gönderirken kullanılabilen mesaj seçeneklerinin tam listesi için, seçtiğiniz bağlantı sunucusu protokolü HTTP veya XMPP'ye ilişkin referans bilgilerine bakın.

Konulara mesaj gönder

Firebase Cloud Messaging konusuna mesaj göndermek, bireysel bir cihaza veya kullanıcı grubuna mesaj göndermeye çok benzer. Uygulama sunucusu, to /topics/yourTopic gibi bir değerle ayarlar. Geliştiriciler, normal ifadeyle eşleşen herhangi bir konu adını seçebilir: "/topics/[a-zA-Z0-9-_.~%]+" .

Birden çok konunun birleşimine göndermek için uygulama sunucusunun, condition anahtarını ( to anahtarı yerine) hedef konuları belirten bir boole koşuluna ayarlaması gerekir. Örneğin, TopicA ve TopicB veya TopicC abone olan cihazlara mesaj göndermek için:

'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)

FCM önce parantez içindeki koşulları değerlendirir, ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya abone olan kullanıcı mesajı almıyor. Aynı şekilde TopicA'ya abone olmayan bir kullanıcı da mesajı alamamaktadır. Bu kombinasyonlar bunu alır:

  • KonuA ve KonuB
  • KonuA ve KonuC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz ve parantezler desteklenir. Desteklenen operatörler: && , || .

Konu HTTP POST isteği

Tek bir konuya gönder:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA


"Köpekler" veya "kediler" konularına abone olan cihazlara gönderin:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA


Konu HTTP yanıtı

// Success example:
{
  "message_id": "1023456"
}

// failure example:
{
  "error": "TopicsMessageRateExceeded"
}

Konu XMPP mesajı

Tek bir konuya gönder:

<message id="">
  <gcm xmlns="google:mobile:data">


  </gcm>
</message>

"Köpekler" veya "kediler" konularına abone olan cihazlara gönderin:

<message id="">
  <gcm xmlns="google:mobile:data">


  </gcm>
</message>

Konu XMPP yanıtı

// Success example:
{
  "message_id": "1023456"
}

// failure example:
{
  "error": "TopicsMessageRateExceeded"
}

FCM Sunucusu konu gönderme isteklerine başarılı veya başarısız bir yanıt döndürmeden önce 30 saniyeye kadar gecikme beklenebilir. İstekte uygulama sunucusunun zaman aşımı değerini buna göre ayarladığınızdan emin olun.

Cihaz gruplarına mesaj gönderin

Kullanımdan kaldırılan eski API'leri kullanarak bir cihaz grubuna mesaj göndermek, tek bir cihaza mesaj göndermeye çok benzer. to parametresini cihaz grubu için benzersiz bildirim anahtarına ayarlayın. Bu bölümdeki örnekler, eski HTTP ve XMPP protokollerindeki cihaz gruplarına veri mesajlarının nasıl gönderileceğini gösterir.

Cihaz Grubu HTTP POST İsteği

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "aUniqueKey",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!",
   }
}

Cihaz Grubu HTTP Yanıtı

İşte bir "başarı" örneği: notification_key ilişkilendirilmiş 2 kayıt jetonu vardır ve mesaj her ikisine de başarıyla gönderilmiştir:

{
  "success": 2,
  "failure": 0
}

İşte "kısmi başarı" örneği: notification_key kendisiyle ilişkilendirilmiş 3 kayıt jetonu vardır. Mesaj, kayıt belirteçlerinden yalnızca 1 tanesine başarıyla gönderildi. Yanıt mesajı, mesajı alamayan kayıt belirteçlerini ( registration_ids ) listeler:

{
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

Bir mesaj, bir notification_key ile ilişkili bir veya daha fazla kayıt jetonuna teslim edilemediğinde, uygulama sunucusu, yeniden denemeler arasında geri çekilme ile yeniden denemelidir.

Sunucu, üyesi olmayan bir aygıt grubuna mesaj göndermeye çalışırsa, yanıt 0 başarı ve 0 başarısızlıkla aşağıdaki gibi görünür:

{
  "success": 0,
  "failure": 0
}

Cihaz Grubu XMPP Mesajı

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to": "aUniqueKey",
      "message_id": "m-1366082849205" ,
      "data": {
          "hello":"This is a Firebase Cloud Messaging Device Group Message!"
      }
  }
  </gcm>
</message>

Cihaz Grubu XMPP Yanıtı

Mesaj gruptaki cihazlardan herhangi birine başarıyla gönderildiğinde, XMPP bağlantı sunucusu bir ACK ile yanıt verir. Gruptaki tüm cihazlara gönderilen mesajların tamamı başarısız olursa XMPP bağlantı sunucusu bir NACK ile yanıt verir.

İşte bir "başarı" örneği: notification_key kendisiyle ilişkilendirilmiş 3 kayıt jetonu vardır ve mesaj bunların hepsine başarıyla gönderilmiştir:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success": 3,
  "failure": 0,
  "message_id": "m-1366082849205"
}

İşte "kısmi başarı" örneği: notification_key kendisiyle ilişkilendirilmiş 3 kayıt jetonu vardır. Mesaj, kayıt belirteçlerinden yalnızca 1 tanesine başarıyla gönderildi. Yanıt mesajı, mesajı alamayan kayıt jetonlarını listeler:

{
  "from": "aUniqueKey",
  "message_type": "ack",
  "success":1,
  "failure":2,
  "failed_registration_ids":[
     "regId1",
     "regId2"
  ]
}

FCM bağlantı sunucusu gruptaki tüm cihazlara dağıtım yapamadığında. Uygulama sunucusu bir nack yanıtı alacaktır.

Mesaj seçeneklerinin tam listesi için seçtiğiniz bağlantı sunucusu protokolü HTTP veya XMPP'ye ilişkin referans bilgilerine bakın.

Firebase Admin SDK'nın eski gönderme yöntemleri

Firebase Admin Node.js SDK'sı, Eski FCM sunucusu API'sine dayalı olarak (FCM) mesaj gönderme yöntemlerini destekler. Bu yöntemler send() yöntemiyle karşılaştırıldığında farklı argümanları kabul eder. Mümkün olduğunda send() yöntemini kullanmalı ve bireysel cihazlara veya cihaz gruplarına mesaj gönderirken yalnızca bu sayfada açıklanan yöntemleri kullanmalısınız.

Bireysel cihazlara gönder

İlgili cihaza bir mesaj göndermek için sendToDevice() yöntemine bir kayıt jetonu iletebilirsiniz:

Node.js

// This registration token comes from the client FCM SDKs.
const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device corresponding to the provided
// registration token.
getMessaging().sendToDevice(registrationToken, payload)
  .then((response) => {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

sendToDevice() yöntemi ayrıca tek bir kayıt belirteci yerine bir dizi kayıt belirteci ileterek çok noktaya yayın mesajı (yani birden fazla cihaza bir mesaj) gönderebilir:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...',
  // ...
  'ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf...'
];

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the devices corresponding to the provided
// registration tokens.
getMessaging().sendToDevice(registrationTokens, payload)
  .then((response) => {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

sendToDevice() yöntemi, FCM'den gelen yanıtı içeren MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür. Dönüş türü, tek bir kayıt jetonunu veya bir dizi kayıt jetonunu geçirirken aynı formata sahiptir.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlar, mesajın tamamının işlenememesine neden olur. Bu durumlarda sendToDevice() tarafından döndürülen söz bir hatayla reddedilir. Açıklamalar ve çözüm adımları da dahil olmak üzere hata kodlarının tam listesi için bkz . Yönetici FCM API Hataları .

Bir cihaz grubuna gönder

sendToDeviceGroup() yöntemi, bir aygıt grubu için bildirim anahtarını belirterek bir aygıt grubuna mesaj göndermenize olanak tanır:

Node.js

// See the "Managing device groups" link above on how to generate a
// notification key.
const notificationKey = 'some-notification-key';

// See the "Defining the message payload" section below for details
// on how to define a message payload.
const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

// Send a message to the device group corresponding to the provided
// notification key.
getMessaging().sendToDeviceGroup(notificationKey, payload)
  .then((response) => {
    // See the MessagingDeviceGroupResponse reference documentation for
    // the contents of response.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

sendToDeviceGroup() yöntemi, FCM'den gelen yanıtı içeren MessagingDevicesResponse nesnesiyle çözümlenen bir söz döndürür.

Kimlik doğrulama hatası veya hız sınırlaması gibi bazı durumlar, mesajın tamamının işlenememesine neden olur. Bu durumlarda sendToDeviceGroup() tarafından döndürülen söz bir hatayla reddedilir. Açıklamalar ve çözüm adımları da dahil olmak üzere hata kodlarının tam listesi için bkz . Yönetici FCM API Hataları .

Mesaj yükünün tanımlanması

FCM'nin eski protokollerini temel alan yukarıdaki yöntemler, ikinci argüman olarak bir mesaj yükünü kabul eder ve hem bildirim hem de veri mesajlarını destekler. data ve/veya notification tuşlarıyla bir nesne oluşturarak mesaj türlerinden birini veya her ikisini birden belirleyebilirsiniz. Örneğin, farklı türde mesaj yüklerinin nasıl tanımlanacağı aşağıda açıklanmıştır:

Bildirim mesajı

const payload = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  }
};

Veri mesajı

const payload = {
  data: {
    score: '850',
    time: '2:45'
  }
};

Birleşik mesaj

const payload = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  data: {
    stock: 'GOOG',
    open: '829.62',
    close: '635.67'
  }
};

Bildirim mesajı verileri, önceden tanımlanmış bir geçerli özellikler alt kümesine sahiptir ve hedeflediğiniz mobil işletim sistemine bağlı olarak biraz farklılık gösterir. Tam liste için NotificationMessagePayload referans belgelerine bakın.

Veri mesajı yükleri, tüm değerlerin dize olması gerektiği gerçeği de dahil olmak üzere birkaç kısıtlamaya sahip özel anahtar/değer çiftlerinden oluşur. Kısıtlamaların tam listesi için DataMessagePayload referans belgelerine bakın.

Mesaj seçeneklerini tanımlama

FCM'nin eski protokollerini temel alan yukarıdaki yöntemler, mesaj için bazı seçenekleri belirten isteğe bağlı üçüncü bir argümanı kabul eder. Örneğin, aşağıdaki örnek, süresi 24 saat sonra dolacak bir cihaza yüksek öncelikli bir mesaj gönderir:

Node.js

// This registration token comes from the client FCM SDKs.
const registrationToken = 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...';

// See the "Defining the message payload" section above for details
// on how to define a message payload.
const payload = {
  notification: {
    title: 'Urgent action needed!',
    body: 'Urgent action is needed to prevent your account from being disabled!'
  }
};

// Set the message as high priority and have it expire after 24 hours.
const options = {
  priority: 'high',
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
getMessaging().sendToDevice(registrationToken, payload, options)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Mevcut seçeneklerin tam listesi için MessagingOptions referans belgelerine bakın.