傳送訊息 - AWS 終端使用者訊息推送

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

傳送訊息

「一 AWS 般使用者訊息推送」API 可以傳送交易推播通知給特定裝置識別碼。本節包含完整的程式碼範例,您可以使用這些範例,透API過使用 AWS SDK. AWS

您可以使用這些範例,透過「一 AWS 般使用者訊息推送」支援的任何推播通知服務傳送推播通知。目前, AWS 最終用戶消息推送支持以下渠道:Firebase 雲消息傳遞(FCM),蘋果推送通知服務(APNs),百度雲推送和 Amazon 設備消息傳遞(ADM)。

如需有關端點、區段和通道的更多程式碼範例,請參閱程式碼範例

注意

當您通過 Firebase 雲消息傳遞(FCM)服務發送推送通知時,請GCM在呼叫 AWS 最終用戶消息傳遞推送時使用該服務名稱API。谷歌雲消息傳遞(GCM)服務已於 2018 年 4 月 10 日由谷歌停產。不過,「一 AWS 般API使用者訊息推送」會針對透過GCM服務傳送的訊息使用FCM服務名稱,以維持與停止服GCM務之前撰寫之API程式碼的相容性。

GCM (AWS CLI)

下列範例會使用傳送訊息來傳送GCM推播通知。 AWS CLI Replace (取代) token 具有設備的唯一令牌 611e3e3cdd47474c9c1399a50example 與您的應用程序標識符。

aws pinpoint send-messages \ --application-id 611e3e3cdd47474c9c1399a50example \ --message-request file://myfile.json \ --region us-west-2 Contents of myfile.json: { "Addresses": { "token": { "ChannelType" : 'GCM' } }, "MessageConfiguration": { "GCMMessage": { "Action": "URL", "Body": "This is a sample message", "Priority": "normal", "SilentPush": True, "Title": "My sample message", "TimeToLive": 30, "Url": "https://www.example.com" } } }

下列範例會使用傳送訊息來傳送GCM推播通知,並使用所有舊金鑰與. AWS CLI Replace (取代) token 具有設備的唯一令牌 611e3e3cdd47474c9c1399a50example 與您的應用程序標識符。

aws pinpoint send-messages \ --application-id 611e3e3cdd47474c9c1399a50example \ --message-request '{ "MessageConfiguration": { "GCMMessage":{ "RawContent": "{\"notification\": {\n \"title\": \"string\",\n \"body\": \"string\",\n \"android_channel_id\": \"string\",\n \"body_loc_args\": [\n \"string\"\n ],\n \"body_loc_key\": \"string\",\n \"click_action\": \"string\",\n \"color\": \"string\",\n \"icon\": \"string\",\n \"sound\": \"string\",\n \"tag\": \"string\",\n \"title_loc_args\": [\n \"string\"\n ],\n \"title_loc_key\": \"string\"\n },\"data\":{\"message\":\"hello in data\"} }", "TimeToLive" : 309744 } }, "Addresses": { "token": { "ChannelType":"GCM" } } }' \ --region us-east-1

下列範例會使用傳送訊息,使用傳送訊息來傳送包含FCMv1訊息承載的GCM推播通知。 AWS CLI Replace (取代) token 具有設備的唯一令牌 611e3e3cdd47474c9c1399a50example 與您的應用程序標識符。

aws pinpoint send-messages \ --application-id 6a2dafd84bec449ea75fb773f4c41fa1 \ --message-request '{ "MessageConfiguration": { "GCMMessage":{ "RawContent": "{\n \"fcmV1Message\": \n {\n \"message\" :{\n \"notification\": {\n \"title\": \"string\",\n \"body\": \"string\"\n },\n \"android\": {\n \"priority\": \"high\",\n \"notification\": {\n \"title\": \"string\",\n \"body\": \"string\",\n \"icon\": \"string\",\n \"color\": \"string\",\n \"sound\": \"string\",\n \"tag\": \"string\",\n \"click_action\": \"string\",\n \"body_loc_key\": \"string\",\n \"body_loc_args\": [\n \"string\"\n ],\n \"title_loc_key\": \"string\",\n \"title_loc_args\": [\n \"string\"\n ],\n \"channel_id\": \"string\",\n \"ticker\": \"string\",\n \"sticky\": true,\n \"event_time\": \"2024-02-06T22:11:55Z\",\n \"local_only\": true,\n \"notification_priority\": \"PRIORITY_UNSPECIFIED\",\n \"default_sound\": false,\n \"default_vibrate_timings\": true,\n \"default_light_settings\": false,\n \"vibrate_timings\": [\n \"22s\"\n ],\n \"visibility\": \"VISIBILITY_UNSPECIFIED\",\n \"notification_count\": 5,\n \"light_settings\": {\n \"color\": {\n \"red\": 1,\n \"green\": 2,\n \"blue\": 3,\n \"alpha\": 6\n },\n \"light_on_duration\": \"112s\",\n \"light_off_duration\": \"1123s\"\n },\n \"image\": \"string\"\n },\n \"data\": {\n \"dataKey1\": \"priority message\",\n \"data_key_3\": \"priority message\",\n \"dataKey2\": \"priority message\",\n \"data_key_5\": \"priority message\"\n },\n \"ttl\": \"10023.32s\"\n },\n \"apns\": {\n \"payload\": {\n \"aps\": {\n \"alert\": {\n \"subtitle\": \"string\",\n \"title-loc-args\": [\n \"string\"\n ],\n \"title-loc-key\": \"string\",\n \"launch-image\": \"string\",\n \"subtitle-loc-key\": \"string\",\n \"subtitle-loc-args\": [\n \"string\"\n ],\n \"loc-args\": [\n \"string\"\n ],\n \"loc-key\": \"string\",\n \"title\": \"string\",\n \"body\": \"string\"\n },\n \"thread-id\": \"string\",\n \"category\": \"string\",\n \"content-available\": 1,\n \"mutable-content\": 1,\n \"target-content-id\": \"string\",\n \"interruption-level\": \"string\",\n \"relevance-score\": 25,\n \"filter-criteria\": \"string\",\n \"stale-date\": 6483,\n \"content-state\": {},\n \"timestamp\": 673634,\n \"dismissal-date\": 4,\n \"attributes-type\": \"string\",\n \"attributes\": {},\n \"sound\": \"string\",\n \"badge\": 5\n }\n }\n },\n \"webpush\": {\n \"notification\": {\n \"permission\": \"granted\",\n \"maxActions\": 2,\n \"actions\": [\n \"title\"\n ],\n \"badge\": \"URL\",\n \"body\": \"Hello\",\n \"data\": {\n \"hello\": \"hey\"\n },\n \"dir\": \"auto\",\n \"icon\": \"icon\",\n \"image\": \"image\",\n \"lang\": \"string\",\n \"renotify\": false,\n \"requireInteraction\": true,\n \"silent\": false,\n \"tag\": \"tag\",\n \"timestamp\": 1707259524964,\n \"title\": \"hello\",\n \"vibrate\": [\n 100,\n 200,\n 300\n ]\n },\n \"data\": {\n \"data1\": \"priority message\",\n \"data2\": \"priority message\",\n \"data12\": \"priority message\",\n \"data3\": \"priority message\"\n }\n },\n \"data\": {\n \"data7\": \"priority message\",\n \"data5\": \"priority message\",\n \"data8\": \"priority message\",\n \"data9\": \"priority message\"\n }\n }\n \n}\n}", "TimeToLive" : 309744 } }, "Addresses": { token: { "ChannelType":"GCM" } } }' \ --region us-east-1

如果使用 ImageUrl field forGCM,則精確定位將字段作為數據通知發送,密鑰為pinpoint.notification.imageUrl,這可以防止圖像被渲染開箱即用。請使用 RawContent 或添加對數據鍵的處理,例如將您的應用程序與之集成 AWS Amplify。

Safari (AWS CLI)

您可以使用「一 AWS 般使用者訊息推送」,將訊息傳送至使用 Apple Safari 網頁瀏覽器的 macOS 電腦。若要傳訊到 Safari 瀏覽器,必須指定原始訊息內容,且須在訊息承載中包含特定屬性。您可以透過建立具有原始訊息承載的推播通知範本,或在 Amazon Pinpoint 使用者指南中直接在行銷活動訊息中指定原始訊息內容,以達到此目的。

注意

傳送到使用 Safari 網頁瀏覽器的 macOS 筆記型電腦和桌上型電腦,需要此特殊屬性。發送到 iOS 設備(例如 iPhones 和)不需要它iPads。

若要傳訊到 Safari 網頁瀏覽器,必須指定原始訊息承載。原始訊息承載必須在 aps 物件中包含一個 url-args 陣列。需要 url-args 陣列才能將推播通知傳送到 Safari 網頁瀏覽器。但可以接受陣列包含單一空白元素。

下列範例會使用傳送訊息,將通知傳送至 Safari 網頁瀏覽器。 AWS CLI Replace (取代) token 具有設備的唯一令牌 611e3e3cdd47474c9c1399a50example 與您的應用程序標識符。

aws pinpoint send-messages \ --application-id 611e3e3cdd47474c9c1399a50example \ --message-request '{ "Addresses": { "token": { "ChannelType":"APNS" } }, "MessageConfiguration": { "APNSMessage": { "RawContent": "{\"aps\": {\"alert\": { \"title\": \"Title of my message\", \"body\": \"This is a push notification for the Safari web browser.\"},\"content-available\": 1,\"url-args\": [\"\"]}}" } } }' \ --region us-east-1

如需 Safari 推播通知的詳細資訊,請參閱 Apple 開發人員網站上的設定 Safari 推播通知

APNS (AWS CLI)

下列範例會使用傳送訊息來傳送APNS推播通知。 AWS CLI Replace (取代) token 使用設備的唯一令牌,611e3e3cdd47474c9c1399a50example 與您的應用程序標識符,以及 GAME_INVITATION 具有唯一標識符。

aws pinpoint send-messages \ --application-id 611e3e3cdd47474c9c1399a50example \ --message-request '{ "Addresses": { "token": { "ChannelType":"APNS" } }, "MessageConfiguration": { "APNSMessage": { "RawContent": "{\"aps\" : {\"alert\" : {\"title\" : \"Game Request\",\"subtitle\" : \"Five Card Draw\",\"body\" : \"Bob wants to play poker\"},\"category\" : \"GAME_INVITATION\"},\"gameID\" : \"12345678\"}" } } }' \ --region us-east-1
JavaScript (Node.js)

使用此範例可 JavaScript 在 Node.js 中使用的 AWS SDK傳送推播通知。此範例假設您已經 JavaScript 在 Node.js 中安裝並設定了。SDK

此範例也會假設您使用共用的登入資料檔案,指定現有 使用者的存取金鑰和私密存取金鑰。如需詳細資訊,請參閱 Node.js 開發人員指南 JavaScript 中AWS SDK的中設定認證

'use strict'; const AWS = require('aws-sdk'); // The AWS Region that you want to use to send the message. For a list of // AWS Regions where the API is available const region = 'us-east-1'; // The title that appears at the top of the push notification. var title = 'Test message sent from End User Messaging Push.'; // The content of the push notification. var message = 'This is a sample message sent from End User Messaging Push by using the ' + 'AWS SDK for JavaScript in Node.js'; // The application ID that you want to use when you send this // message. Make sure that the push channel is enabled for the project that // you choose. var applicationId = 'ce796be37f32f178af652b26eexample'; // An object that contains the unique token of the device that you want to send // the message to, and the push service that you want to use to send the message. var recipient = { 'token': 'a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5a6b7c8d8e9f0', 'service': 'GCM' }; // The action that should occur when the recipient taps the message. Possible // values are OPEN_APP (opens the app or brings it to the foreground), // DEEP_LINK (opens the app to a specific page or interface), or URL (opens a // specific URL in the device's web browser.) var action = 'URL'; // This value is only required if you use the URL action. This variable contains // the URL that opens in the recipient's web browser. var url = 'https://www.example.com'; // The priority of the push notification. If the value is 'normal', then the // delivery of the message is optimized for battery usage on the recipient's // device, and could be delayed. If the value is 'high', then the notification is // sent immediately, and might wake a sleeping device. var priority = 'normal'; // The amount of time, in seconds, that the push notification service provider // (such as FCM or APNS) should attempt to deliver the message before dropping // it. Not all providers allow you specify a TTL value. var ttl = 30; // Boolean that specifies whether the notification is sent as a silent // notification (a notification that doesn't display on the recipient's device). var silent = false; function CreateMessageRequest() { var token = recipient['token']; var service = recipient['service']; if (service == 'GCM') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'GCM' } }, 'MessageConfiguration': { 'GCMMessage': { 'Action': action, 'Body': message, 'Priority': priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'APNS') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'APNS' } }, 'MessageConfiguration': { 'APNSMessage': { 'Action': action, 'Body': message, 'Priority': priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'BAIDU') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'BAIDU' } }, 'MessageConfiguration': { 'BaiduMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'ADM') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'ADM' } }, 'MessageConfiguration': { 'ADMMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'Url': url } } }; } return messageRequest } function ShowOutput(data){ if (data["MessageResponse"]["Result"][recipient["token"]]["DeliveryStatus"] == "SUCCESSFUL") { var status = "Message sent! Response information: "; } else { var status = "The message wasn't sent. Response information: "; } console.log(status); console.dir(data, { depth: null }); } function SendMessage() { var token = recipient['token']; var service = recipient['service']; var messageRequest = CreateMessageRequest(); // Specify that you're using a shared credentials file, and specify the // IAM profile to use. var credentials = new AWS.SharedIniFileCredentials({ profile: 'default' }); AWS.config.credentials = credentials; // Specify the AWS Region to use. AWS.config.update({ region: region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); var params = { "ApplicationId": applicationId, "MessageRequest": messageRequest }; // Try to send the message. pinpoint.sendMessages(params, function(err, data) { if (err) console.log(err); else ShowOutput(data); }); } SendMessage()
Python

使用 AWS SDK for Python (Boto3)藉此範例傳送推送通知。這個範例假設您已經安裝並設定SDK了 Python (Boto3)。

此範例也會假設您使用共用的登入資料檔案,指定現有 使用者的存取金鑰和私密存取金鑰。如需詳細資訊,請參閱AWS SDK針對 Python (Boto3) API 參考資中的認證。

import json import boto3 from botocore.exceptions import ClientError # The AWS Region that you want to use to send the message. For a list of # AWS Regions where the API is available region = "us-east-1" # The title that appears at the top of the push notification. title = "Test message sent from End User Messaging Push." # The content of the push notification. message = ("This is a sample message sent from End User Messaging Push by using the " "AWS SDK for Python (Boto3).") # The application ID to use when you send this message. # Make sure that the push channel is enabled for the project or application # that you choose. application_id = "ce796be37f32f178af652b26eexample" # A dictionary that contains the unique token of the device that you want to send the # message to, and the push service that you want to use to send the message. recipient = { "token": "a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5a6b7c8d8e9f0", "service": "GCM" } # The action that should occur when the recipient taps the message. Possible # values are OPEN_APP (opens the app or brings it to the foreground), # DEEP_LINK (opens the app to a specific page or interface), or URL (opens a # specific URL in the device's web browser.) action = "URL" # This value is only required if you use the URL action. This variable contains # the URL that opens in the recipient's web browser. url = "https://www.example.com" # The priority of the push notification. If the value is 'normal', then the # delivery of the message is optimized for battery usage on the recipient's # device, and could be delayed. If the value is 'high', then the notification is # sent immediately, and might wake a sleeping device. priority = "normal" # The amount of time, in seconds, that the push notification service provider # (such as FCM or APNS) should attempt to deliver the message before dropping # it. Not all providers allow you specify a TTL value. ttl = 30 # Boolean that specifies whether the notification is sent as a silent # notification (a notification that doesn't display on the recipient's device). silent = False # Set the MessageType based on the values in the recipient variable. def create_message_request(): token = recipient["token"] service = recipient["service"] if service == "GCM": message_request = { 'Addresses': { token: { 'ChannelType': 'GCM' } }, 'MessageConfiguration': { 'GCMMessage': { 'Action': action, 'Body': message, 'Priority' : priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "APNS": message_request = { 'Addresses': { token: { 'ChannelType': 'APNS' } }, 'MessageConfiguration': { 'APNSMessage': { 'Action': action, 'Body': message, 'Priority' : priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "BAIDU": message_request = { 'Addresses': { token: { 'ChannelType': 'BAIDU' } }, 'MessageConfiguration': { 'BaiduMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "ADM": message_request = { 'Addresses': { token: { 'ChannelType': 'ADM' } }, 'MessageConfiguration': { 'ADMMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'Url': url } } } else: message_request = None return message_request # Show a success or failure message, and provide the response from the API. def show_output(response): if response['MessageResponse']['Result'][recipient["token"]]['DeliveryStatus'] == "SUCCESSFUL": status = "Message sent! Response information:\n" else: status = "The message wasn't sent. Response information:\n" print(status, json.dumps(response,indent=4)) # Send the message through the appropriate channel. def send_message(): token = recipient["token"] service = recipient["service"] message_request = create_message_request() client = boto3.client('pinpoint',region_name=region) try: response = client.send_messages( ApplicationId=application_id, MessageRequest=message_request ) except ClientError as e: print(e.response['Error']['Message']) else: show_output(response) send_message()

其他資源

  • 如需有關推播通道範本的詳細資訊,請參閱 Amazon Pinpoint 使用者指南中的建立推播通知範本