با استفاده از Firebase Admin SDK یا پروتکلهای سرور برنامه FCM ، میتوانید درخواستهای پیام بسازید و آنها را به این نوع اهداف ارسال کنید:
- نام موضوع
- وضعیت
- رمز ثبت دستگاه
- نام گروه دستگاه (فقط پروتکل)
میتوانید پیامهایی را با یک محموله اعلان متشکل از فیلدهای از پیش تعریفشده، یک محموله داده از فیلدهای تعریفشده توسط کاربر یا پیامی حاوی هر دو نوع بار ارسال کنید. برای اطلاعات بیشتر به انواع پیام مراجعه کنید.
مثالهای موجود در این صفحه نحوه ارسال پیامهای اعلان را با استفاده از Firebase Admin SDK (که از Node ، Java ، Python ، C# و Go پشتیبانی میکند) و پروتکل HTTP v1 نشان میدهد.
ارسال پیام به دستگاه های خاص
برای ارسال به یک دستگاه خاص، رمز ثبت نام دستگاه را مطابق شکل ارسال کنید. برای کسب اطلاعات بیشتر در مورد نشانه های ثبت نام، اطلاعات راه اندازی مشتری برای پلتفرم خود را ببینید.
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);
});
جاوا
// 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);
پایتون
# 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)
برو
// 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)
سی شارپ
// 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);
استراحت
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:
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
در صورت موفقیت، هر روش ارسال یک شناسه پیام را برمی گرداند. Firebase Admin SDK رشته ID را در قالب projects/{project_id}/messages/{message_id}
برمیگرداند. پاسخ پروتکل HTTP یک کلید JSON است:
{
"name":"projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96"
}
ارسال یک پیام به چندین دستگاه
Admin FCM SDKs به شما این امکان را می دهد که یک پیام را به لیستی از نشانه های ثبت دستگاه چندپخش کنید. شما می توانید از این ویژگی زمانی استفاده کنید که نیاز به ارسال یک پیام مشابه به تعداد زیادی دستگاه دارید. شما می توانید تا 500 توکن ثبت دستگاه را در هر فراخوانی مشخص کنید.
مقدار بازگشتی شامل لیستی از نشانه ها است که با ترتیب توکن های ورودی مطابقت دارد. این زمانی مفید است که میخواهید بررسی کنید کدام نشانهها منجر به خطا شدهاند و سپس آنها را به درستی مدیریت کنید .
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
const message = {
data: {score: '850', time: '2:45'},
tokens: registrationTokens,
};
getMessaging().sendEachForMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
});
جاوا
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
MulticastMessage message = MulticastMessage.builder()
.putData("score", "850")
.putData("time", "2:45")
.addAllTokens(registrationTokens)
.build();
BatchResponse response = FirebaseMessaging.getInstance().sendEachForMulticast(message);
if (response.getFailureCount() > 0) {
List<SendResponse> responses = response.getResponses();
List<String> failedTokens = new ArrayList<>();
for (int i = 0; i < responses.size(); i++) {
if (!responses.get(i).isSuccessful()) {
// The order of responses corresponds to the order of the registration tokens.
failedTokens.add(registrationTokens.get(i));
}
}
System.out.println("List of tokens that caused failures: " + failedTokens);
}
پایتون
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_N',
]
message = messaging.MulticastMessage(
data={'score': '850', 'time': '2:45'},
tokens=registration_tokens,
)
response = messaging.send_each_for_multicast(message)
if response.failure_count > 0:
responses = response.responses
failed_tokens = []
for idx, resp in enumerate(responses):
if not resp.success:
# The order of responses corresponds to the order of the registration tokens.
failed_tokens.append(registration_tokens[idx])
print('List of tokens that caused failures: {0}'.format(failed_tokens))
برو
// Create a list containing up to 500 registration tokens.
// This registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
message := &messaging.MulticastMessage{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Tokens: registrationTokens,
}
br, err := client.SendEachForMulticast(context.Background(), message)
if err != nil {
log.Fatalln(err)
}
if br.FailureCount > 0 {
var failedTokens []string
for idx, resp := range br.Responses {
if !resp.Success {
// The order of responses corresponds to the order of the registration tokens.
failedTokens = append(failedTokens, registrationTokens[idx])
}
}
fmt.Printf("List of tokens that caused failures: %v\n", failedTokens)
}
سی شارپ
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
var message = new MulticastMessage()
{
Tokens = registrationTokens,
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
};
var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(message);
if (response.FailureCount > 0)
{
var failedTokens = new List<string>();
for (var i = 0; i < response.Responses.Count; i++)
{
if (!response.Responses[i].IsSuccess)
{
// The order of responses corresponds to the order of the registration tokens.
failedTokens.Add(registrationTokens[i]);
}
}
Console.WriteLine($"List of tokens that caused failures: {failedTokens}");
}
لیستی از پیام ها را ارسال کنید
Admin SDK از ارسال لیستی تا حداکثر 500 پیام پشتیبانی می کند. از این ویژگی می توان برای ایجاد مجموعه ای سفارشی از پیام ها و ارسال آنها به گیرندگان مختلف، از جمله موضوعات یا نشانه های ثبت دستگاه خاص استفاده کرد. به عنوان مثال، زمانی که نیاز به ارسال پیام های کمی متفاوت به مخاطبان مختلف دارید، می توانید از این ویژگی استفاده کنید.
Node.js
// Create a list containing up to 500 messages.
const messages = [];
messages.push({
notification: { title: 'Price drop', body: '5% off all electronics' },
token: registrationToken,
});
messages.push({
notification: { title: 'Price drop', body: '2% off all books' },
topic: 'readers-club',
});
getMessaging().sendEach(messages)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
جاوا
// Create a list containing up to 500 messages.
List<Message> messages = Arrays.asList(
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("5% off all electronics")
.build())
.setToken(registrationToken)
.build(),
// ...
Message.builder()
.setNotification(Notification.builder()
.setTitle("Price drop")
.setBody("2% off all books")
.build())
.setTopic("readers-club")
.build()
);
BatchResponse response = FirebaseMessaging.getInstance().sendEach(messages);
// See the BatchResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " messages were sent successfully");
پایتون
# Create a list containing up to 500 messages.
messages = [
messaging.Message(
notification=messaging.Notification('Price drop', '5% off all electronics'),
token=registration_token,
),
# ...
messaging.Message(
notification=messaging.Notification('Price drop', '2% off all books'),
topic='readers-club',
),
]
response = messaging.send_each(messages)
# See the BatchResponse reference documentation
# for the contents of response.
print('{0} messages were sent successfully'.format(response.success_count))
برو
// Create a list containing up to 500 messages.
messages := []*messaging.Message{
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "5% off all electronics",
},
Token: registrationToken,
},
{
Notification: &messaging.Notification{
Title: "Price drop",
Body: "2% off all books",
},
Topic: "readers-club",
},
}
br, err := client.SendEach(context.Background(), messages)
if err != nil {
log.Fatalln(err)
}
// See the BatchResponse reference documentation
// for the contents of response.
fmt.Printf("%d messages were sent successfully\n", br.SuccessCount)
سی شارپ
// 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");
ارسال پیام به موضوعات
پس از ایجاد یک موضوع، یا با اشتراک نمونههای برنامه مشتری در موضوع سمت سرویس گیرنده یا از طریق API سرور ، میتوانید پیامهایی را به موضوع ارسال کنید. اگر این اولین باری است که درخواست ارسال درخواست برای FCM را ایجاد میکنید، راهنمای محیط سرور و FCM را برای اطلاعات مهم پسزمینه و راهاندازی ببینید.
در منطق ارسال خود در باطن، نام موضوع مورد نظر را مطابق شکل مشخص کنید:
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);
});
جاوا
// 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);
پایتون
# 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)
برو
// 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)
سی شارپ
// 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);
استراحت
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:
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
برای ارسال پیام به ترکیبی از موضوعات، یک شرط را مشخص کنید، که یک عبارت بولی است که موضوعات مورد نظر را مشخص می کند. برای مثال، شرایط زیر پیامهایی را به دستگاههایی ارسال میکند که مشترک TopicA
و TopicB
یا TopicC
هستند:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM ابتدا هر شرایط داخل پرانتز را ارزیابی می کند و سپس عبارت را از چپ به راست ارزیابی می کند. در عبارت بالا، کاربری که در یک موضوع مشترک است، پیامی را دریافت نمی کند. به همین ترتیب، کاربری که در TopicA
مشترک نمی شود، پیام را دریافت نمی کند. این ترکیب ها آن را دریافت می کنند:
-
TopicA
وTopicB
-
TopicA
وTopicC
می توانید حداکثر پنج موضوع را در عبارت شرطی خود بگنجانید.
برای ارسال به یک شرط:
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);
});
جاوا
// 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);
پایتون
# 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)
برو
// 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)
سی شارپ
// 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);
استراحت
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:
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
ارسال پیام به گروه های دستگاه
ارسال پیام به یک گروه دستگاه بسیار شبیه به ارسال پیام به یک دستگاه جداگانه است، با استفاده از همان روش برای تأیید درخواستهای ارسال . فیلد token
را روی کلید اعلان گروه تنظیم کنید:
استراحت
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
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
ارسال پیامهای مستقیم با قابلیت بوت (فقط اندروید)
میتوانید با استفاده از HTTP v1 یا APIهای قدیمی HTTP، پیامها را در حالت بوت مستقیم به دستگاهها ارسال کنید. قبل از ارسال به دستگاهها در حالت بوت مستقیم، مطمئن شوید که مراحل فعال کردن دستگاههای سرویس گیرنده را برای دریافت پیامهای FCM در حالت راهاندازی مستقیم انجام دادهاید.
ارسال با استفاده از FCM v1 HTTP API
درخواست پیام باید شامل کلید "direct_boot_ok" : true
در گزینه های AndroidConfig
بدنه درخواست باشد. به عنوان مثال:
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,
},
}
سفارشی کردن پیام ها در پلتفرم ها
Firebase Admin SDK و پروتکل FCM v1 HTTP هر دو به درخواست های پیام شما اجازه می دهند تمام فیلدهای موجود در شی message
را تنظیم کنند. این شامل:
- مجموعه ای مشترک از فیلدها که باید توسط همه نمونه های برنامه ای که پیام را دریافت می کنند تفسیر شوند.
- مجموعههایی از فیلدهای مخصوص پلتفرم، مانند
AndroidConfig
وWebpushConfig
، که فقط توسط نمونههای برنامهای که در پلتفرم مشخصشده اجرا میشوند تفسیر میشوند.
بلوکهای مخصوص پلتفرم به شما انعطافپذیری میدهند تا پیامها را برای پلتفرمهای مختلف سفارشی کنید تا اطمینان حاصل کنید که هنگام دریافت بهدرستی با آنها برخورد میشود. پشتیبان FCM تمام پارامترهای مشخص شده را در نظر می گیرد و پیام را برای هر پلتفرم سفارشی می کند.
زمان استفاده از فیلدهای مشترک
وقتی هستید از فیلدهای مشترک استفاده کنید:
- هدف قرار دادن نمونه های برنامه در همه پلتفرم ها - اپل، اندروید و وب
- ارسال پیام به موضوعات
همه نمونه های برنامه، صرف نظر از پلتفرم، می توانند فیلدهای مشترک زیر را تفسیر کنند:
زمان استفاده از فیلدهای مخصوص پلتفرم
زمانی که می خواهید از فیلدهای مخصوص پلتفرم استفاده کنید:
- فیلدها را فقط به پلتفرم های خاص ارسال کنید
- علاوه بر فیلدهای مشترک، فیلدهای مخصوص پلتفرم را ارسال کنید
هر زمان که میخواهید مقادیر را فقط به پلتفرمهای خاصی ارسال کنید، از فیلدهای مشترک استفاده نکنید . از فیلدهای مخصوص پلتفرم استفاده کنید. به عنوان مثال، برای ارسال نوتیفیکیشن فقط به پلتفرمهای اپل و وب اما نه برای اندروید، باید از دو مجموعه فیلد جداگانه، یکی برای اپل و دیگری برای وب استفاده کنید.
وقتی پیام هایی با گزینه های تحویل خاص ارسال می کنید، از فیلدهای مخصوص پلتفرم برای تنظیم آنها استفاده کنید. در صورت تمایل می توانید مقادیر مختلفی را برای هر پلتفرم مشخص کنید. با این حال، حتی زمانی که میخواهید اساساً مقدار یکسانی را در بین پلتفرمها تنظیم کنید، باید از فیلدهای مخصوص پلتفرم استفاده کنید. این به این دلیل است که هر پلتفرم ممکن است مقدار را کمی متفاوت تفسیر کند - برای مثال، زمان برای زندگی در Android به عنوان زمان انقضا بر حسب ثانیه تنظیم می شود، در حالی که در اپل به عنوان تاریخ انقضا تنظیم می شود.
مثال: پیام اعلان با گزینه های رنگ و نماد
این درخواست ارسال مثال، عنوان و محتوای اعلان مشترک را به همه پلتفرمها ارسال میکند، اما برخی موارد لغو خاص پلتفرم را نیز به دستگاههای Android ارسال میکند.
برای اندروید، درخواست یک نماد و رنگ خاص را برای نمایش در دستگاه های اندرویدی تنظیم می کند. همانطور که در مرجع AndroidNotification اشاره شد، رنگ با فرمت #rrggbb مشخص شده است و تصویر باید یک منبع نماد قابل ترسیم محلی برای برنامه Android باشد.
در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:
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);
});
جاوا
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();
پایتون
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',
)
برو
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",
}
سی شارپ
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",
};
استراحت
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"
}
}
}
}
برای جزئیات کامل کلیدهای موجود در بلوکهای مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.
مثال: پیام اعلان با یک تصویر سفارشی
مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه پلتفرم ها ارسال می کند، اما یک تصویر نیز ارسال می کند. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:
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);
});
استراحت
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"
}
}
}
}
برای جزئیات کامل کلیدهای موجود در بلوکهای مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.
مثال: پیام اعلان با یک اقدام کلیک مرتبط
مثال زیر درخواست ارسال یک عنوان اعلان مشترک را به همه پلتفرمها ارسال میکند، اما همچنین اقدامی را برای برنامه ارسال میکند تا در پاسخ به تعامل کاربر با اعلان انجام دهد. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:
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);
});
استراحت
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"
}
}
}
}
برای جزئیات کامل کلیدهای موجود در بلوکهای مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.
مثال: پیام اعلان با گزینه های محلی سازی
مثال زیر درخواست ارسال گزینههای محلیسازی را برای مشتری ارسال میکند تا پیامهای محلی را نمایش دهد. در اینجا تقریبی از جلوه بصری روی دستگاه کاربر آورده شده است:
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);
});
استراحت
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"],
},
},
},
},
},
}'
برای جزئیات کامل کلیدهای موجود در بلوکهای مخصوص پلتفرم در متن پیام، به مستندات مرجع HTTP v1 مراجعه کنید.