Uygulama sunucusu gönderme istekleri oluşturma

Firebase Admin SDK veya FCM uygulama sunucusu protokollerini kullanarak mesaj istekleri oluşturabilir ve bunları aşağıdaki tür hedeflere gönderebilirsiniz:

  • Konu adı
  • Koşul
  • Cihaz kaydı jetonu
  • Cihaz grubu adı (yalnızca protokol)

Önceden tanımlanmış alanlardan, kendi kullanıcı tanımlı alanlarınızın veri yükünden veya her iki yük türünü de içeren bir mesajdan oluşan bildirim yüküyle mesajlar gönderebilirsiniz. Daha fazla bilgi için Mesaj türleri bölümüne göz atın.

Bu sayfadaki örneklerde, Firebase Admin SDK (Node, Java, Python, C# ve Go) ile v1 HTTP protokolü kullanılarak bildirim mesajlarının nasıl gönderileceği gösterilmektedir. Kullanımdan kaldırılan eski HTTP ve XMPP protokolleri aracılığıyla mesaj gönderme konusunda talimatlar da vardır.

Belirli cihazlara mesaj gönderme

Belirli bir cihaza göndermek için cihazın kayıt jetonunu gösterildiği şekilde iletin. Kayıt jetonları hakkında daha fazla bilgi edinmek için platformunuzla ilgili istemci kurulumu bilgilerine göz atı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)

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

REST

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ılı olursa her gönderme yöntemi bir ileti kimliği döndürür. Firebase Admin SDK'sı, 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 çok cihaza mesaj gönderme

Yönetici FCM API'leri, bir cihaz kayıt jetonları listesine çoklu yayın yapmanıza olanak tanır. Çağrı başına en fazla 500 cihaz kaydı 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))

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.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öndürülen değer, giriş jetonlarının sırasına karşılık gelen jeton listesidir. Bu, hangi jetonların hataya neden olduğunu 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))

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.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önderme

Bir konu oluşturduktan sonra, istemci uygulaması örneklerini istemci tarafında konuya abone olarak veya sunucu API'si aracılığıyla konuya mesaj gönderebilirsiniz. FCM için gönderme isteklerini ilk kez oluşturuyorsanız önemli arka plan ve kurulum bilgileri için sunucu ortamınız 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)

Go

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

REST

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

Bir konu kombinasyonuna mesaj göndermek için bir koşul belirtin. Bu koşul, hedef konuları belirten bir boole ifadesidir. Örneğin, aşağıdaki koşul TopicA ve TopicB ya da TopicC aboneliklerine abone olan cihazlara mesaj gönderir:

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

FCM, önce parantez içindeki tüm koşulları ve daha sonra, soldan sağa doğru ifadeyi değerlendirir. Yukarıdaki ifadede, herhangi bir konuya abone olan kullanıcı mesajı almaz. Benzer şekilde, TopicA hizmetine abone olmayan kullanıcı da bu iletiyi almaz. Şu 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)

Go

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

REST

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'yi kullanın. Şu anda HTTP veya XMPP için desteği sonlandırılmış eski gönderme API'lerini ya da Node.js için Firebase Yönetici SDK'sının eski protokolleri temel alan eski sürümlerinden birini kullanarak cihaz gruplarına gönderim yapıyorsanız en kısa sürede HTTP v1 API'ye geçmenizi önemle tavsiye ederiz. 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 benzer. token alanını grup bildirimi anahtarına ayarlayın:

REST

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

İletileri toplu olarak gönderme

Yönetici SDK'ları, iletilerin toplu olarak gönderilmesini destekler. 500 adede kadar mesajı tek bir grupta gruplandırabilir ve tümünü tek bir API çağrısında gönderebilirsiniz. Bu sayede, her mesaj için ayrı HTTP istekleri göndermeye kıyasla önemli bir performans artışı elde edilebilir.

Bu özellik, özelleştirilmiş bir mesaj grubu oluşturmak ve bunları konular veya belirli cihaz kayıt jetonları da dahil olmak üzere farklı alıcılara göndermek için kullanılabilir. Örneğin, ileti gövdesinde biraz farklı ayrıntılarla farklı kitlelere aynı anda mesaj göndermeniz gerektiğinde bu özelliği 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))

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.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 başlatma özellikli mesajlar gönderme (yalnızca Android)

HTTP v1 veya eski HTTP API'lerini kullanarak doğrudan başlatma modundaki cihazlara mesaj gönderebilirsiniz. Doğrudan başlatma modundaki cihazlara göndermeden önce, istemci cihazların FCM mesajlarını doğrudan başlatma modunda almasına izin verme adımlarını tamamladığınızdan emin olun.

FCM v1 HTTP API'yi kullanarak gönder

Mesaj isteğinin, istek gövdesinin AndroidConfig seçeneklerinde "direct_boot_ok" : true anahtarını içermesi gerekir. Örnek:

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önder

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

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 başlatma modunda olan (ve bu modda olmayan) cihazlarda bulunan uygulamalar tarafından işlenebilir.

Farklı platformlardan mesajları özelleştirme

Firebase Admin SDK'sı ve FCM v1 HTTP protokolü, mesaj isteklerinizin message nesnesindeki tüm alanları ayarlamasına izin verir. Bunlardan bazıları:

  • mesajı alan tüm uygulama örnekleri tarafından yorumlanacak ortak bir alan grubudur.
  • Yalnızca belirtilen platformda çalışan uygulama örnekleri tarafından yorumlanan AndroidConfig ve WebpushConfig gibi platforma özgü alan grupları.

Platforma özel engellemeler, alındıklarında doğru şekilde işlenmelerini sağlamak amacıyla size farklı platformlar için mesajları özelleştirme esnekliği sunar. FCM arka ucu, belirtilen tüm parametreleri dikkate alır ve mesajı her platform için özelleştirir.

Ortak alanlar ne zaman kullanılır?

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

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

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

Platforma özel alanlar ne zaman kullanılır?

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 özel alanları kullanın. Örneğin, Android'e değil de yalnızca Apple platformlarına ve web'e bildirim göndermek isterseniz biri Apple, diğeri web için olmak üzere iki ayrı alan grubu kullanmanız gerekir.

Belirli teslim seçenekleriyle ileti gönderirken bunları ayarlamak için platforma özel alanları kullanın. İsterseniz her platform için farklı değerler belirtebilirsiniz. Ancak platformlar genelinde temelde aynı değeri ayarlamak isteseniz bile platforma özel alanları kullanmanız gerekir. Bunun nedeni, her platformun değeri biraz farklı yorumlayabilmesidir. Örneğin, geçerlilik süresi Android'de saniye cinsinden süre sonu olarak, Apple'da ise geçerlilik tarihi olarak ayarlanır.

Örnek: renk ve simge seçenekleri içeren bildirim mesajı

Bu örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı ve içeriği gönderirken 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. AndroidBildirim referansında belirtildiği gibi, renk #rrggbb biçiminde belirtilir ve resim, Android uygulamasına özgü bir çekilebilir simge kaynağı olmalıdır.

Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

Birinde özel simge ve renk gösterilen 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',
)

Go

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",
};

REST

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 anahtarlar hakkında ayrıntılı bilgi için HTTP v1 referans belgelerine bakın.

Örnek: özel resim 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. Kullanıcının cihazı üzerindeki görsel etkinin yaklaşık bir tahminini aşağıda görebilirsiniz:

Ekran bildirimindeki bir resmin 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);
  });

REST

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 anahtarlar hakkında ayrıntılı bilgi için HTTP v1 referans belgelerine bakın.

Örnek: İlişkili tıklama işlemi içeren bildirim mesajı

Aşağıdaki örnek gönderme isteği, tüm platformlara ortak bir bildirim başlığı gönderir ancak kullanıcının bildirimle etkileşime girmesine yanıt olarak uygulamanın gerçekleştireceği bir işlem de gönderir. Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

Bir kullanıcının web sayfasına dokunduğu basit çizim

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

REST

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 anahtarlar hakkında ayrıntılı bilgi için HTTP v1 referans belgelerine bakın.

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

Aşağıdaki örnek gönderme isteği, yerelleştirilmiş mesajları görüntülemesi için istemciye yerelleştirme seçenekleri gönderir. Kullanıcının cihazındaki görsel etkinin yaklaşık özeti:

İngilizce ve İspanyolca metinlerin gösterildiği 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);
  });

REST

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 anahtarlar hakkında ayrıntılı bilgi için HTTP v1 referans belgelerine bakın.

HTTP v1 API için REST hata kodları

HTTP v1 API için HTTP hata yanıtları; hata kodu, hata mesajı ve hata durumunu içerir. Ayrıca, hatayla ilgili daha fazla ayrıntı içeren bir details dizisi de içerebilir.

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

1. Örnek: Veri mesajında geçersiz değer içeren bir HTTP v1 API isteğindeki 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"
          }
        ]
      }
    ]
  }
}

2. Örnek: Geçersiz kayıt jetonuna 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 örnek, istek değerlerinde hata olduğunu gösteren type.googleapis.com/google.rpc.BadRequest türüne sahiptir. type.googleapis.com/google.firebase.fcm.v1.FcmError türündeki ikinci örnekte FCM'ye özgü bir hata vardır. Hataların çoğu, ayrıntılar dizisinde 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 yok. Yok.
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ı, ileti çok büyük, geçersiz veri anahtarı, geçersiz TTL veya diğer geçersiz parametreler bulunur.
Geçersiz kayıt: Sunucuya ilettiğiniz kayıt jetonunun biçimini kontrol edin. Bu adresin, istemci uygulamasının FCM'ye kaydolurken aldığı kayıt jetonuyla eşleştiğinden emin olun. Jetonu kısaltmayın veya başka karakterler eklemeyin.
Geçersiz paket adı: İletinin, paket adı istekte iletilen değerle eşleşen bir kayıt jetonuna gönderildiğinden emin olun.
İleti çok büyük: Bir iletiye eklenen yük verilerinin toplam boyutunun FCM sınırlarını aşmadığından emin olun: çoğu ileti için 4.096 bayt veya konulara gönderilen mesajlar için 2.048 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 (ör. gönderen, gcm ya da Google'ın önekli herhangi bir değeri) içermediğinden emin olun. Bazı kelimelerin (daraltma_anahtarı gibi) FCM tarafından da kullanıldığını, ancak yük içinde kullanılmasına izin verildiğini unutmayın. Bu durumda, yük değeri FCM değeri tarafından geçersiz kılınır.
Geçersiz TTL: ttl dosyasında kullanılan değerin, 0 ile 2.419.200 (4 hafta) arasında saniye cinsinden bir süreyi temsil eden bir tam sayı olduğundan emin olun.
Geçersiz parametreler: Sağlanan parametrelerin doğru ad ve türe sahip olup olmadığını kontrol edin.
UNREGISTERED (HTTP hata kodu = 404) Uygulama örneğinin FCM kaydı iptal edildi. Bu genellikle kullanılan jetonun artık geçerli olmadığı ve yeni bir jetonun kullanılması gerektiği anlamına gelir. Bu hata, eksik kayıt jetonları veya kaydedilmemiş jetonlardan kaynaklanabilir.
Kayıt Eksik: İletinin hedefi token değeriyse isteğin bir kayıt jetonu içerdiğinden emin olun.
Kayıtlı değil: Mevcut bir kayıt jetonunun geçerliliği, aşağıdakiler dahil çeşitli senaryolarda sona erebilir:
- İstemci uygulaması FCM'deki kaydını iptal ederse.
- İstemci uygulamasının kaydı otomatik olarak iptal edilirse kullanıcı uygulamayı kaldırdığında ortaya çıkabilir. Örneğin, iOS'te APNs Geri Bildirim Hizmeti, APNs jetonunun 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ş olabilir).
- İstemci uygulaması güncellenmişse ancak yeni sürüm mesaj alacak şekilde yapılandırılmamışsa.
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ğrulanan gönderen kimliği, kayıt jetonundaki gönderen kimliğinden farklı. Kayıt jetonu belirli bir gönderen grubuna bağlıdır. Bir istemci uygulaması FCM'ye kaydolduğunda, hangi gönderenlerin ileti göndermesine izin verildiğini belirtmelidir. İstemci uygulamasına ileti gönderirken bu gönderen kimliklerinden birini kullanmanız gerekir. 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.
İleti hızı aşıldı: İletilerin gönderme hızı çok yüksek. Genel mesaj gönderme hızını azaltmanız gerekir. Reddedilen iletileri yeniden denemek için en az 1 dakikalık bir başlangıç gecikmesiyle eksponansiyel geri yükleme kullanın.
Cihaz mesaj hızı aşıldı: Belirli bir cihaza mesaj gönderme hızı çok yüksek. Tek bir cihazla mesaj gönderme hızı sınırını inceleyin. Bu cihaza gönderilen ileti sayısını azaltın ve göndermeyi yeniden denemek için eksponansiyel geri yükleme özelliğini kullanın.
Konu mesajı oranı aşıldı: Belirli bir konunun abonelere gönderilme oranı çok yüksek. Bu konuda gönderilen ileti sayısını azaltın ve göndermeyi yeniden denemek için en az 1 dakikalık bir başlangıç gecikmesiyle üstel geri yüklemeyi 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 yapmanız gerekenler:
- FCM Bağlantı Sunucusu'nun yanıtında yer alıyorsa Retry-After başlığını dikkate alın.
- Yeniden deneme mekanizmanıza eksponansiyel geri çekme uygulayabilirsiniz. (Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz, sonraki denemeden önce en az iki saniye, ardından 4 saniye vb. bekleyin). Birden çok mesaj gönderiyorsanız ses dalgalanması özelliğini uygulayabilirsiniz. Daha fazla bilgi için Yeniden denemeleri işleme başlıklı makaleyi inceleyin. Soruna neden olan gönderenler, ret listesine alınma riskine girer.
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 uygulayarak aynı isteği yeniden deneyebilirsiniz. Hata devam ederse lütfen Firebase destek ekibiyle iletişime geçin.
THIRD_PARTY_AUTH_ERROR (HTTP hata kodu = 401) APNs sertifikası veya web push kimlik doğrulama anahtarı geçersiz ya da eksik. iOS cihazı veya web push kaydına hedeflenen mesaj gönderilemedi. Geliştirme ve üretim kimlik bilgilerinizin geçerliliğini kontrol edin.

Yönetici hata kodları

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

Hata Kodu Açıklama ve Çözüm Adımları
messaging/invalid-argument Bir FCM yöntemine geçersiz bağımsız değişken sağlandı. Hata mesajında ek bilgiler yer almalıdır.
messaging/invalid-recipient Hedeflenen ileti alıcısı geçersiz. Hata mesajında ek bilgiler bulunmalıdır.
messaging/invalid-payload Geçersiz bir mesaj yük nesnesi sağlandı. Hata mesajında ek bilgiler bulunmalıdır.
messaging/invalid-data-payload-key Veri mesajı yükü geçersiz bir anahtar içeriyor. Kısıtlanmış anahtarlar için DataMessagePayload ile ilgili referans dokümanlara bakın.
messaging/payload-size-limit-exceeded Sağlanan mesaj yükü, FCM boyutu sınırlarını aşıyor. Çoğu mesaj için sınır 4.096 bayttır. Konulara gönderilen mesajlar için sınır 2.048 bayttır. Toplam yük boyutu hem anahtarları hem de değerleri içerir.
messaging/invalid-options Geçersiz mesaj seçenekleri nesnesi sağlandı. Hata mesajında ek bilgiler bulunmalıdır.
messaging/invalid-registration-token Sağlanan kayıt jetonu geçersiz. Bu adresin, istemci uygulamasının FCM'ye kaydolurken aldığı kayıt jetonuyla eşleştiğinden emin olun. Metni kısaltmayın veya başka karakterler eklemeyin.
messaging/registration-token-not-registered Sağlanan kayıt jetonu kayıtlı değil. Daha önce geçerli olan bir kayıt jetonunun kaydı, aşağıdakiler gibi çeşitli nedenlerden dolayı iptal edilebilir:
  • İstemci uygulaması FCM'deki kaydını iptal etti.
  • İstemci uygulamasının kaydı otomatik olarak iptal edildi. Bu durum, kullanıcı uygulamayı kaldırırsa veya Apple platformlarında APNs Geri Bildirim Hizmeti, APNs jetonunun geçersiz olduğunu bildirirse gerçekleşebilir.
  • Kayıt jetonunun süresi doldu. Örneğin Google, kayıt jetonlarını yenilemeye karar verebilir veya Apple cihazlar için APNs jetonunun süresi dolmuş olabilir.
  • İstemci uygulaması güncellendi ancak yeni sürüm mesaj alacak şekilde yapılandırılmamış.
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 Mesaj, paket adı sağlanan restrictedPackageName seçeneğiyle eşleşmeyen bir kayıt jetonuna gönderildi.
messaging/message-rate-exceeded Belirli bir hedefe gönderilen mesajların oranı çok yüksek. Bu cihaza veya konuya gönderilen mesaj sayısını azaltın ve bu hedefe göndermeyi hemen tekrar 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 tekrarlamayın.
messaging/topics-message-rate-exceeded Belirli bir konunun abonelere gönderilen mesajların oranı çok yüksek. Bu konu için gönderilen mesaj sayısını azaltın ve bu konuya göndermeyi hemen tekrar denemeyin.
messaging/too-many-topics Bir kayıt jetonu, maksimum sayıda konuya abone olunduğu için daha fazla konuya abone olunamaz.
messaging/invalid-apns-credentials Gerekli APNs SSL sertifikası yüklenmediği veya süresi dolduğu için Apple cihazı 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 Admin SDK'larının kimliğini doğrulamayla ilgili belgeler için Firebase'i uygulamanıza ekleme bölümüne bakın.
messaging/authentication-error SDK, FCM sunucularının kimliğini doğrulayamadı. Firebase Admin SDK'nın kimliğini, FCM mesajları göndermek için uygun izinlere sahip bir kimlik bilgisiyle doğruladığınızdan emin olun. Firebase Admin SDK'larının kimliğini doğrulamayla ilgili belgeler için Firebase'i uygulamanıza ekleme bölümüne bakın.
messaging/server-unavailable FCM sunucusu, isteği zamanında işleyemedi. Aynı isteği yeniden denemeniz gerekir ancak şunları yapmanız gerekir:
  • FCM Bağlantı Sunucusu'ndan gelen yanıta dahilse Retry-After üst bilgisini dikkate alın.
  • Yeniden deneme mekanizmanıza eksponansiyel geri çekilme uygulayın. Örneğin, ilk yeniden denemeden önce bir saniye beklediyseniz, ilk yeniden denemeden önce en az iki saniye, ardından dört saniye bekleyin. Birden fazla mesaj gönderiyorsanız tüm mesajlar için aynı anda yeni bir istek gönderilmesini önlemek amacıyla her birini rastgele ek bir miktarla ayrı ayrı geciktirin.
Soruna neden olan gönderenler kara listeye alınma riskiyle karşı karşıya kalı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 uygulayarak 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 bilgi için hata mesajındaki ham sunucu yanıtını inceleyin. 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 üzerinden birden fazla platforma içerik gönderiyorsanı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ı söz konusu uygulama örneğine ait kayıt jetonuna ayarlayın. Kayıt jetonları hakkında daha fazla bilgi edinmek için platformunuzun istemci kurulumu 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 sunar. Sunucu yanıtı biçimi bölümüne bakın.

İstemci uygulamalarına aşağı akış mesajları gönderirken kullanılabilecek mesaj seçeneklerinin tam listesi için seçtiğiniz bağlantı sunucusu protokolüne ( HTTP veya XMPP) ait referans bilgilerine bakın.

Konulara mesaj gönderme

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

Birden fazla konunun kombinasyonuna gönderim yapmak için uygulama sunucusunun condition anahtarını (to anahtarı yerine) hedef konuları belirten bir boole koşulu olarak ayarlaması gerekir. Örneğin, TopicA ve TopicB ya da TopicC aboneliklerine abone olan cihazlara ileti göndermek için:

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

FCM, önce parantez içindeki tüm koşulları değerlendirir, ardından da soldan sağa doğru ifadeyi değerlendirir. Yukarıdaki ifadede, tek bir konuya abone olan kullanıcı mesajı almaz. Benzer şekilde, TopicA'ya abone olmayan bir kullanıcı mesajı almaz. Bu kombinasyonlara izin verilir:

  • TopicA ve TopicB
  • TopicA ve TopicC

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önder:

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önder:

<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 olmasını bekleyebilirsiniz. İstekte uygulama sunucusunun zaman aşımı değerini buna uygun şekilde ayarladığınızdan emin olun.

Cihaz gruplarına mesaj gönderme

Desteği sonlandırılan eski API'leri kullanarak bir cihaz grubuna mesaj göndermek, tek bir cihaza mesaj göndermeye benzer. to parametresini, cihaz grubunun 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ı

"Başarı" örneğini aşağıda görebilirsiniz. notification_key, kendisiyle ilişkilendirilmiş 2 kayıt jetonuna sahiptir ve mesaj her ikisine de başarıyla gönderilmiştir:

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

"Kısmi başarı" örneğini burada görebilirsiniz. notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir. Mesaj, kayıt jetonlarından yalnızca 1 tanesine başarıyla gönderildi. Yanıt mesajında mesajı alamayan kayıt jetonları (registration_ids) listelenir:

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

Bir mesaj, notification_key ile ilişkili kayıt jetonlarından bir veya daha fazlasına teslim edilemediyse uygulama sunucusu, yeniden denemeler arasında geri yükleme yaparak tekrar denemelidir.

Sunucu, üyesi olmayan bir cihaz grubuna mesaj göndermeye çalışırsa yanıt aşağıdaki gibi görünür. Başarı oranı 0, başarısızlık oranı 0 olur:

{
  "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 birine başarıyla gönderildiğinde, XMPP bağlantı sunucusu ACK ile yanıt verir. Gruptaki tüm cihazlara gönderilen tüm mesajlar başarısız olursa XMPP bağlantı sunucusu NACK ile yanıt verir.

"Başarı" örneğini aşağıda görebilirsiniz. notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir ve mesaj, bunların tümüne başarıyla gönderilmiştir:

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

"Kısmi başarı" örneğini burada görebilirsiniz. notification_key, kendisiyle ilişkilendirilmiş 3 kayıt jetonuna sahiptir. Mesaj, kayıt jetonlarından 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 yayın yapamadığında. Uygulama sunucusu bir nack yanıtı alır.

Mesaj seçeneklerinin tam listesi için seçtiğiniz bağlantı sunucusu protokolünün (HTTP veya XMPP) referans bilgilerine bakın.

Firebase Admin SDK eski gönderme yöntemleri

Firebase Admin Node.js SDK'sı Eski FCM sunucu API'sine dayalı olarak mesaj gönderme (FCM) yöntemlerini destekler. Bu yöntemler, send() yöntemine kıyasla farklı bağımsız değişkenleri kabul eder. Mümkün olduğunda send() yöntemini kullanmalı ve bağımsız cihazlara ya da cihaz gruplarına mesaj gönderirken yalnızca bu sayfada açıklanan yöntemleri kullanmalısınız.

Cihazlara tek tek gönder

sendToDevice() yöntemine kayıt jetonu ileterek söz konusu cihaza mesaj gönderebilirsiniz:

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, tek bir kayıt jetonu yerine bir kayıt jetonları dizisi ileterek bir multicast mesajı (yani birden çok cihaza 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'nin yanıtını içeren bir MessagingDevicesResponse nesnesiyle çözümlenmiş bir taahhüt döndürür. Dönüş türü, tek bir kayıt jetonu veya kayıt jetonu dizisi iletilirken aynı biçime 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 taahhüt bir hatayla reddedilir. Açıklamalar ve çözüm adımları dahil olmak üzere hata kodlarının tam listesi için Yönetici FCM API Hataları bölümüne bakın.

Cihaz grubuna gönder

sendToDeviceGroup() yöntemi, bir cihaz grubu için bildirim anahtarını belirterek cihaz grubuna mesaj göndermenizi sağlar:

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'nin yanıtını içeren bir MessagingDevicesResponse nesnesiyle çözümlenmiş bir taahhüt 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 taahhüt bir hatayla reddedilir. Açıklamalar ve çözüm adımları dahil olmak üzere hata kodlarının tam listesi için Yönetici FCM API Hataları bölümüne bakın.

Mesaj yükünü tanımlama

Eski FCM protokollerine dayanan yukarıdaki yöntemler, ikinci bağımsız değişken olarak bir mesaj yükünü kabul eder ve hem bildirim hem de veri mesajlarını destekler. data ve / veya notification anahtarlarıyla bir nesne oluşturarak mesaj türlerinden birini veya ikisini birden belirtebilirsiniz. Örneğin, farklı mesaj yükü türlerinin 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ştirilmiş 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ı yükleri, geçerli özelliklerin önceden tanımlanmış bir alt kümesine sahiptir ve hedeflediğiniz mobil işletim sistemine göre biraz farklılık gösterir. Tam liste için NotificationMessagePayload referans belgelerini inceleyin.

Veri mesajı yükleri, tüm değerlerin dize olması dahil olmak üzere birkaç kısıtlama bulunan ö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

Eski FCM protokollerine dayanan yukarıdaki yöntemler, mesaj için bazı seçenekleri belirten isteğe bağlı üçüncü bağımsız değişkeni kabul eder. Örneğin, aşağıdaki örnek, 24 saat sonra süresi dolan bir cihaza yüksek öncelikli 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);
  });

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