

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 메시지 전송
<a name="reference-send-message"></a>

 AWS End User Messaging Push API는 트랜잭션 푸시 알림을 특정 디바이스 식별자로 전송할 수 있습니다. 이 섹션에는 AWS SDK를 사용하여 AWS 최종 사용자 메시징 푸시 API를 통해 푸시 알림을 보내는 데 사용할 수 있는 전체 코드 예제가 포함되어 있습니다.

다음 예제를 사용하여 AWS End User Messaging Push가 지원하는 모든 푸시 알림 서비스를 통해 푸시 알림을 보낼 수 있습니다. 현재 AWS End User Messaging Push는 Firebase Cloud Messaging(FCM), Apple Push Notification Service(APNs), Baidu Cloud Push 및 Amazon Device Messaging(ADM) 채널을 지원합니다.

엔드포인트, 세그먼트 및 채널에 대한 추가 코드 예제는 [코드 예제](https://docs.aws.amazon.com/pinpoint/latest/developerguide/service_code_examples.html)를 참조하세요.

**참고**  
Firebase Cloud Messaging(FCM) 서비스를 통해 푸시 알림을 보낼 때는 AWS End User Messaging Push API 호출`GCM`에 서비스 이름을 사용합니다. Google에서는 2018년 4월 10일 Google Cloud Messaging(GCM) 서비스를 중단했습니다. 그러나 AWS End User Messaging Push API는 GCM `GCM` 서비스 중단 전에 작성된 API 코드와의 호환성을 유지하기 위해 FCM 서비스를 통해 전송하는 메시지의 서비스 이름을 사용합니다.

------
#### [ GCM (AWS CLI) ]

다음 예제에서는 [send-messages](https://docs.aws.amazon.com/cli/latest/reference/pinpoint/send-messages.html)를 사용하여 로 GCM 푸시 알림을 보냅니다 AWS CLI. *토큰*을 디바이스의 고유 토큰으로 바꾸고 *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"
      }
  }
}
```

다음 예제에서는 [send-messages](https://docs.aws.amazon.com/cli/latest/reference/pinpoint/send-messages.html)를 사용하여와 함께 모든 레거시 키를 사용하여 GCM 푸시 알림을 보냅니다 AWS CLI. *토큰*을 디바이스의 고유 토큰으로 바꾸고 *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
```

다음 예제에서는 [send-messages](https://docs.aws.amazon.com/cli/latest/reference/pinpoint/send-messages.html)를 사용하여를 사용하여 FCMv1 메시지 페이로드로 GCM 푸시 알림을 보냅니다 AWS CLI. *토큰*을 디바이스의 고유 토큰으로 바꾸고 *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
```

GCM에 `ImageUrl` 필드를 사용하는 경우 Pinpoint는 필드를 데이터 알림으로 전송하고 키는 이므로 이미지가 상자에서 렌더링되지 않을 `pinpoint.notification.imageUrl`수 있습니다. RawContent를 사용하거나 앱 통합과 같은 데이터 키 처리를 추가하세요 AWS Amplify.

------
#### [ Safari (AWS CLI) ]

 AWS End User Messaging Push를 사용하여 Apple의 Safari 웹 브라우저를 사용하는 macOS 컴퓨터에 메시지를 보낼 수 있습니다. Safari 브라우저로 메시지를 보내려면 원시 메시지 콘텐츠를 지정하고 메시지 페이로드에 특정 속성을 포함해야 합니다. 원[시 메시지 페이로드로 푸시 알림 템플릿을 생성](https://docs.aws.amazon.com//pinpoint/latest/userguide/message-templates-creating-push.html#message-templates-creating-push-raw)하거나 *Amazon Pinpoint 사용 설명서*의 [캠페인](https://docs.aws.amazon.com//pinpoint/latest/userguide/campaigns-message.html#campaigns-message-push) 메시지에 원시 메시지 콘텐츠를 직접 지정하여이 작업을 수행할 수 있습니다.

**참고**  
이 특별한 속성은 Safari 웹 브라우저를 사용하는 macOS 랩톱 및 데스크톱 컴퓨터로 전송하는 데 필요합니다. iPhone 및 iPad와 같은 iOS 디바이스로 전송할 때는 필요하지 않습니다.

Safari 웹 브라우저로 메시지를 보내려면 원시 메시지 페이로드를 지정해야 합니다. 원시 메시지 페이로드의 `aps` 객체 내에 `url-args` 배열이 포함되어야 합니다. Safari 웹 브라우저에 푸시 알림을 보내려면 `url-args` 배열이 필요합니다. 하지만 배열에 비어 있는 단일 요소가 포함되어도 괜찮습니다.

다음 예제에서는 [send-messages](https://docs.aws.amazon.com/cli/latest/reference/pinpoint/send-messages.html)를 사용하여를 사용하여 Safari 웹 브라우저에 알림을 보냅니다 AWS CLI. *토큰*을 디바이스의 고유 토큰으로 바꾸고 *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 푸시 알림 구성](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/NotificationProgrammingGuideForWebsites/PushNotifications/PushNotifications.html)을 참조하세요.

------
#### [ APNS (AWS CLI) ]

다음 예제에서는 [send-messages](https://docs.aws.amazon.com/cli/latest/reference/pinpoint/send-messages.html)를 사용하여 로 APNS 푸시 알림을 보냅니다 AWS CLI. *토큰*을 디바이스의 고유 토큰으로, *611e3e3cdd47474c9c1399a50example*을 애플리케이션 식별자로, *GAME\$1INVITATION*을 고유 식별자로 바꿉니다.

```
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) ]

이 예제를 사용하여 Node.js의 JavaScript용 AWS SDK를 사용하여 푸시 알림을 보냅니다. 이 예제에서는 Node.js의 JavaScript용 SDK를 이미 설치 및 구성했다고 가정합니다.

또한 이 예제에서는 공유 자격 증명 파일을 사용하여 기존 사용자의 액세스 키 및 보안 액세스 키를 지정한다고 가정합니다. 자세한 내용은 *Node.js의 JavaScript용AWS SDK 개발자 설명서*의 [보안 인증 정보 설정](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials.html)을 참조하세요.

```
'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)를 사용하여 푸시 알림을 보내려면 이 예를 사용하세요. 이 예제에서는 Python용 SDK(Boto3)를 이미 설치 및 구성했다고 가정합니다.

또한 이 예제에서는 공유 자격 증명 파일을 사용하여 기존 사용자의 액세스 키 및 보안 액세스 키를 지정한다고 가정합니다. 자세한 내용은 *Python용AWS SDK(Boto3) API 참조*의 [보안 인증 정보](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials.html)를 참조하세요.

```
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()
```

------

## 추가 리소스
<a name="reference_additional_resources-send-message"></a>
+ 푸시 채널 템플릿에 대한 자세한 내용은 *Amazon Pinpoint 사용 설명서*의 [푸시 알림 템플릿 생성을](https://docs.aws.amazon.com/pinpoint/latest/userguide/message-templates-creating-push.html) 참조하세요.