• 沒有找到結果。

Amazon Pinpoint

N/A
N/A
Protected

Academic year: 2022

Share "Amazon Pinpoint"

Copied!
391
0
0

加載中.... (立即查看全文)

全文

(1)

Amazon Pinpoint

Developer Guide

(2)

Amazon Pinpoint: Developer Guide

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

(3)

Table of Contents

What is Amazon Pinpoint? ... 1

Amazon Pinpoint features ... 1

Define audience segments ... 1

Engage your audience with messaging campaigns ... 1

Send transactional messages ... 1

Analyze user behavior ... 1

Regional availability ... 2

Tutorials ... 3

Using Postman with Amazon Pinpoint ... 3

About this tutorial ... 3

Prerequisites ... 4

Step 1: Create IAM policies and roles ... 4

Step 2: Set up Postman ... 6

Step 3: Send additional requests ... 12

Setting up an SMS registration system ... 17

About double opt-in ... 18

About this solution ... 18

Prerequisites ... 19

Step 1: Set up Amazon Pinpoint ... 20

Step 2: Create IAM policies and roles ... 23

Step 3: Create Lambda functions ... 24

Step 4: Set up Amazon API Gateway ... 32

Step 5: Create and deploy the web form ... 37

Next steps ... 42

Integrating with your application ... 45

Using Amazon Pinpoint with an AWS SDK ... 45

Integrating the mobile SDKs or JS library ... 46

Integrating mobile SDKs ... 46

Integrating AWS Amplify ... 46

Next step ... 47

Registering endpoints ... 47

Before you begin ... 47

AWS mobile SDKs ... 47

AWS Amplify ... 47

Next steps ... 47

Reporting events ... 48

Before you begin ... 48

AWS mobile SDKs ... 49

Web and react native ... 47

Amazon Pinpoint events API ... 49

Next step ... 49

Handling push notifications ... 49

Setting up push notifications ... 49

Handling push notifications ... 51

Defining your audience ... 52

Adding endpoints ... 52

Examples ... 53

Related information ... 57

Associating users with endpoints ... 57

Examples ... 57

Related information ... 60

Adding a batch of endpoints ... 61

Examples ... 61

Related information ... 65

(4)

Importing endpoints ... 65

Before you begin ... 66

Examples ... 66

Related information ... 74

Deleting endpoints ... 74

Examples ... 74

Accessing audience data ... 76

Looking up endpoints ... 76

Examples ... 76

Related information ... 80

Exporting endpoints ... 80

Before you begin ... 80

Examples ... 80

Related information ... 86

Listing endpoint IDs ... 86

Creating segments ... 88

Building segments ... 88

Building segments with the AWS SDK for Java ... 88

Importing segments ... 90

Importing a segment ... 91

Customizing segments with AWS Lambda ... 91

Event data ... 92

Creating a Lambda function ... 93

Assigning a Lambda function policy ... 94

Assigning a Lambda function to a campaign ... 96

Creating campaigns ... 97

Creating standard campaigns ... 97

Creating campaigns with the AWS SDK for Java ... 97

Creating A/B test campaigns ... 98

Creating A/B test campaigns with the AWS SDK for Java ... 98

Sending and validating one-time passwords ... 100

Sending an OTP message ... 100

SendOtpMessage Response ... 102

Validating an OTP message ... 102

VerifyOtpMessage Response ... 103

Code examples ... 104

Generating a reference ID ... 104

Sending OTP codes ... 104

Validating OTP codes ... 105

Sending and retrieving in-app messages ... 107

Retrieving in-app messages for an endpoint ... 107

Understanding GetInAppMessages API responses ... 109

InAppMessageCampaigns object ... 110

InAppMessage object ... 111

HeaderConfig object ... 111

BodyConfig object ... 112

InAppMessageContent object ... 112

Schedule object ... 113

InAppMessageButton object ... 113

DefaultButtonConfig object ... 114

OverrideButtonConfig object ... 115

Validating phone numbers ... 116

Phone number validation use cases ... 116

Using the phone number validation service ... 116

Phone number validation responses ... 117

Sending messages ... 120

Send email ... 120

(5)

Choosing an email-sending method ... 121

Choosing between Amazon Pinpoint and Amazon Simple Email Service (SES) ... 121

Using the API ... 121

Using the SMTP interface ... 129

Send SMS messages ... 136

Send voice messages ... 143

Send push notifications ... 147

Creating custom channels ... 153

Creating a campaign that sends messages through a custom channel ... 153

Understanding event data ... 154

Configuring webhooks ... 155

Configuring Lambda functions ... 155

Example Lambda function ... 155

Granting Amazon Pinpoint permission to invoke the Lambda function ... 158

Streaming events ... 160

Setting up event streaming ... 160

Prerequisites ... 161

AWS CLI ... 161

AWS SDK for Java ... 161

Disabling event streaming ... 162

App events ... 162

Example ... 162

App event attributes ... 163

Campaign events ... 166

Sample event ... 166

Campaign event attributes ... 167

Journey events ... 170

Sample event ... 170

Journey event attributes ... 171

Email events ... 173

Sample events ... 173

Email event attributes ... 178

SMS events ... 182

Example ... 182

SMS event attributes ... 182

Querying analytics data ... 187

Supported metrics ... 187

Query basics ... 188

IAM policies ... 189

Standard metrics ... 191

Application metrics for campaigns ... 192

Application metrics for transactional email messages ... 195

Application metrics for transactional SMS messages ... 201

Campaign metrics ... 204

Journey engagement metrics ... 209

Journey execution metrics ... 213

Journey activity execution metrics ... 214

Querying campaign data ... 216

Prerequisites ... 217

Querying data for one campaign ... 217

Querying data for multiple campaigns ... 221

Querying transactional messaging data ... 225

Prerequisites ... 225

Querying data for transactional email messages ... 226

Querying data for transactional SMS messages ... 229

Using query results ... 233

JSON structure ... 233

(6)

JSON objects and fields ... 237

Logging API calls ... 239

Amazon Pinpoint information in CloudTrail ... 239

Amazon Pinpoint API actions that can be logged by CloudTrail ... 240

Amazon Pinpoint email API actions that can be logged by CloudTrail ... 243

Amazon Pinpoint SMS and voice API actions that can be logged by CloudTrail ... 244

Examples: Amazon Pinpoint log file entries ... 244

Tagging resources ... 248

Managing tags ... 248

Using tags in IAM policies ... 248

Adding tags to resources ... 249

Adding tags by using the API ... 249

Adding tags by using the AWS CLI ... 250

Displaying tags for resources ... 251

Displaying tags by using the API ... 251

Displaying tags by using the AWS CLI ... 252

Updating tags for resources ... 252

Updating tags by using the API ... 253

Updating tags by using the AWS CLI ... 253

Removing tags from resources ... 254

Removing tags by using the API ... 255

Removing tags by using the AWS CLI ... 255

Related information ... 255

Customizing recommendations with AWS Lambda ... 257

Using recommendations in messages ... 257

Creating the Lambda function ... 259

Input event data ... 259

Response data and requirements ... 260

Assigning a Lambda function policy ... 264

Authorizing Amazon Pinpoint to invoke the function ... 265

Configuring the Recommender Model ... 265

Deleting data ... 267

Deleting endpoints ... 267

Deleting Segment and Endpoint Data from Amazon S3 ... 267

Deleting all project data ... 268

Deleting All AWS Data ... 268

Code examples ... 270

Amazon Pinpoint examples ... 270

Actions ... 271

Amazon Pinpoint SMS and Voice API examples ... 304

Actions ... 304

Security ... 308

Data protection ... 308

Data encryption ... 310

Internetwork traffic privacy ... 310

Identity and access management ... 311

Audience ... 311

Authenticating with identities ... 311

Managing access using policies ... 313

How Amazon Pinpoint works with IAM ... 315

Amazon Pinpoint policy actions ... 319

Identity-based policy examples ... 339

IAM roles for common tasks ... 348

Troubleshooting ... 361

Logging and monitoring ... 363

Compliance validation ... 364

Resilience ... 364

(7)

Infrastructure security ... 365

Configuration and vulnerability analysis ... 365

Quotas ... 366

Project quotas ... 366

API request quotas ... 366

Campaign quotas ... 367

Email quotas ... 368

Email message quotas ... 368

Email sender and recipient quotas ... 368

Email sending quotas ... 369

Endpoint quotas ... 370

Endpoint import quotas ... 371

Event ingestion quotas ... 371

Journey quotas ... 372

Machine learning quotas ... 372

Message template quotas ... 373

Push notification quotas ... 374

In-app message quotas ... 375

Segment quotas ... 375

SMS quotas ... 375

10DLC quotas ... 376

Voice quotas ... 376

Requesting a quota increase ... 378

Document history ... 379

Earlier updates ... 382

(8)

Amazon Pinpoint features

What is Amazon Pinpoint?

Amazon Pinpoint is an AWS service that you can use to engage with your customers across multiple messaging channels. You can use Amazon Pinpoint to send push notifications, emails, SMS text messages, or voice messages.

The information in this developer guide is intended for application developers. This guide contains information about using the features of Amazon Pinpoint programmatically. It also contains information of particular interest to mobile app developers, such as procedures for integrating analytics and

messaging features with your application (p. 45).

There are several other documents that are companions to this document. The following documents provide reference information related to the Amazon Pinpoint APIs:

• Amazon Pinpoint API Reference

• Amazon Pinpoint SMS and voice API

If you're new to Amazon Pinpoint, you might find it helpful to review the Amazon Pinpoint User Guide before proceeding with this document.

Amazon Pinpoint features

This section describes the major features of Amazon Pinpoint and the tasks that you can perform by using them.

Define audience segments

Reach the right audience for your messages by defining audience segments (p. 88). A segment designates which users receive the messages that are sent from a campaign. You can define dynamic segments based on data that's reported by your application, such as operating system or mobile device type. You can also import static segments that you define by using another service or application.

Engage your audience with messaging campaigns

Engage your audience by creating a messaging campaign (p. 97). A campaign sends tailored messages on a schedule that you define. You can create campaigns that send mobile push, email, or SMS messages.

To experiment with alternative campaign strategies, set up your campaign as an A/B test, and analyze the results with Amazon Pinpoint analytics.

Send transactional messages

Keep your customers informed by sending transactional mobile push and SMS messages—such as new account activation messages, order confirmations, and password reset notifications— directly to specific users. You can send transactional messages by using the Amazon Pinpoint REST API.

Analyze user behavior

Gain insights about your audience and the effectiveness of your campaigns by using the analytics that Amazon Pinpoint provides. You can view trends about your users' level of engagement, purchase activity,

(9)

Regional availability

demographics, and more. You can also monitor your message traffic by viewing metrics such as the total number of messages that were sent or opened for a campaign or application. Through the Amazon Pinpoint API, your application can report custom data, which Amazon Pinpoint makes available for analysis, and you can query analytics data for certain standard metrics.

To analyze or store analytics data outside Amazon Pinpoint, you can configure Amazon Pinpoint to stream the data (p. 160) to Amazon Kinesis.

Regional availability

Amazon Pinpoint is available in several AWS Regions in North America, Europe, Asia, and Oceania.

In each Region, AWS maintains multiple Availability Zones. These Availability Zones are physically isolated from each other, but are united by private, low-latency, high-throughput, and highly redundant network connections. These Availability Zones enable us to provide very high levels of availability and redundancy, while also minimizing latency.

To learn more about AWS Regions, see Managing AWS Regions in the Amazon Web Services General Reference. For a list of all the Regions where Amazon Pinpoint is currently available, see AWS service endpoints in the Amazon Web Services General Reference. To learn more about the number of Availability Zones that are available in each Region, see AWS global infrastructure.

(10)

Using Postman with Amazon Pinpoint

Tutorials

The tutorials in this section are intended to show new Amazon Pinpoint users how to complete several important tasks. If you're new to Amazon Pinpoint, or just unfamiliar with certain features, these tutorials are a good place to start.

The tutorials in this guide include tasks that are oriented toward a developer or system administrator audience. These tutorials show you how to perform tasks by using the Amazon Pinpoint API, the AWS SDKs, and the AWS CLI. If you mainly interact with Amazon Pinpoint by using the web-based console, see the Tutorials section of the Amazon Pinpoint User Guide.

Tutorials

• Tutorial: Using Postman with the Amazon Pinpoint API (p. 3)

• Tutorial: Setting up an SMS registration system (p. 17)

Tutorial: Using Postman with the Amazon Pinpoint API

Postman is a popular tool for testing APIs in an easy-to-use graphical environment. You can use Postman to send API requests to any REST API, and to receive responses to your requests. Using Postman is a convenient way to test and troubleshoot the calls that you make to the Amazon Pinpoint API. This tutorial includes procedures for setting up and using Postman with Amazon Pinpoint.

NotePostman is developed by a third-party company. It isn't developed or supported by Amazon Web Services (AWS). To learn more about using Postman, or for assistance with issues related to Postman, see the Support center on the Postman website.

About this tutorial

This section contains an overview of this tutorial.

Intended Audience

This tutorial is intended for developers and system implementers. You don't have to be familiar with Amazon Pinpoint or Postman to complete the steps in this tutorial. You should be comfortable managing IAM policies and modifying JSON code examples.

The procedures in this tutorial were designed to prevent new users from using API operations that can permanently delete Amazon Pinpoint resources. Advanced users can remove this restriction by modifying the policy that's associated with their IAM users.

Features Used

This tutorial includes usage examples for the following Amazon Pinpoint feature:

• Interacting with the Amazon Pinpoint API by using Postman

Time Required

It should take about 15 minutes to complete this tutorial.

(11)

Prerequisites

Regional Restrictions

There are no regional restrictions associated with using this solution.

Resource Usage Costs

There's no charge for creating an AWS account. However, by implementing this solution, you might incur AWS usage costs if you use Postman to do any of the following:

• Send email, SMS, mobile push, or voice messages

• Create and send campaigns

• Use the phone number validation feature

For more information about the charges that are associated with using Amazon Pinpoint, see Amazon Pinpoint pricing.

Prerequisites

Before you begin this tutorial, you have to complete the following prerequisites:

• You have to have an AWS account. To create an AWS account, go to https://console.aws.amazon.com/

and choose Create a new AWS account.

• The account that you use to sign in to the AWS Management Console has to be able to create new IAM policies and roles.

• You have to download and install Postman on your computer. You can download Postman from the Postman website.

• After you install Postman on your computer, you have to create a Postman account. When you first start the Postman application, you're prompted to log in or create a new account. Complete the instructions shown on the screen to log in to your account (if you already have one), or to create an account (if you don't already have one).

Step 1: Create IAM policies and roles

The first step in using Postman to test the Amazon Pinpoint API is to create an IAM user. In this section, you create a policy that provides users with the ability to interact with all the Amazon Pinpoint resources.

You then create a user account and attach the policy directly to the user account.

Step 1.1: Create an IAM policy

This section shows you how to create an IAM policy. Users and roles that use this policy are able to interact with all of the resources in the Amazon Pinpoint API. It also provides access to resources that are associated with the Amazon Pinpoint Email API, as well as the Amazon Pinpoint SMS and Voice API.

To create the policy

1. Sign in to the AWS Management Console and open the IAM console at https://

console.aws.amazon.com/iam/.

2. In the navigation pane, choose Policies, and then choose Create policy.

3. On the JSON tab, paste the following code.

{ "Version": "2012-10-17", "Statement": [

{

(12)

Step 1: Create IAM policies and roles

"Sid": "VisualEditor0", "Effect": "Allow", "Action": [

"mobiletargeting:Update*", "mobiletargeting:Get*", "mobiletargeting:Send*", "mobiletargeting:Put*", "mobiletargeting:Create*"

],

"Resource": [

"arn:aws:mobiletargeting:*:123456789012:apps/*",

"arn:aws:mobiletargeting:*:123456789012:apps/*/campaigns/*", "arn:aws:mobiletargeting:*:123456789012:apps/*/segments/*"

] }, {

"Sid": "VisualEditor1", "Effect": "Allow", "Action": [

"mobiletargeting:TagResource",

"mobiletargeting:PhoneNumberValidate", "mobiletargeting:ListTagsForResource", "mobiletargeting:CreateApp"

],

"Resource": "arn:aws:mobiletargeting:*:123456789012:*"

}, {

"Sid": "VisualEditor2", "Effect": "Allow", "Action": [

"ses:TagResource", "ses:Send*", "ses:Create*", "ses:Get*", "ses:List*", "ses:Put*", "ses:Update*",

"sms-voice:SendVoiceMessage", "sms-voice:List*",

"sms-voice:Create*", "sms-voice:Get*", "sms-voice:Update*"

],

"Resource": "*"

} ] }

In the preceding example, replace 123456789012 with the unique ID for your AWS account.

Note

To protect the data in your Amazon Pinpoint account, this policy only includes permissions that allow you to read, create, and modify resources. It doesn't include permissions that allow you to delete resources. You can modify this policy by using the visual editor in the IAM console. For more information, see Managing IAM policies in the IAM User Guide. You can also use the CreatePolicyVersion operation in the IAM API to update this policy.

Also note that this policy includes permissions that allow you to interact with the ses and sms-voice services, in addition to the mobiletargeting service. The ses and sms- voice permissions allow you to interact with the Amazon Pinpoint Email API and Amazon Pinpoint SMS and Voice API, respectively. The mobiletargeting permissions allow you to interact with the Amazon Pinpoint API.

4. Choose Review policy.

5. For Name, enter a name for the policy, such as PostmanAccessPolicy. Choose Create policy.

(13)

Step 2: Set up Postman

Step 1.2: Create an IAM user

After you create the policy, you can create an IAM user and attach the policy to it. When you create the user, IAM provides you with a set of credentials that you can use to allow Postman to execute Amazon Pinpoint API operations.

To create the user

1. Open the IAM console at https://console.aws.amazon.com/iam/.

2. On the IAM console, in the navigation pane, choose Users, and then choose Add user.

3. Under Set user details, for User name, enter a name that identifies the user account, such as PostmanUser.

4. Under Select AWS access type, for Access type, choose Programmatic access. Then choose Next:

Permissions.

5. Under Set permissions, choose Attach existing policies directly. In the list of policies, choose the policy that you created in Step 1.1 (p. 4). Then choose Next: Tags.

6. On the Add tags page, optionally add tags that help you identify the user. For more information about using tags, see Tagging IAM users and roles in the IAM User Guide. Then choose Next: Review.

7. On the Review page, review and confirm the settings for the user. When you're ready to create the user, choose Create user.

8. On the Success page, copy the credentials that are shown in the Access key ID and Secret access key columns.

NoteYou need to provide both the access key ID and the secret access key later in this tutorial.

This is the only time that you're able to view the secret access key, so you should copy it and save it in a safe location.

Step 2: Set up Postman

Now that you've created an IAM user account that's able to access the Amazon Pinpoint API, you can set up Postman. In this section, you create one or more environments in Postman. Next, you import a collection that contains a request template for each of the operations in the Amazon Pinpoint API.

Step 2.1: Create Postman environments

In Postman, an environment is a set of variables that are stored as key-value pairs. You can use environments to quickly change the configuration of the requests that you make through Postman, without having to change the API requests themselves.

In this section, you create at least one environment to use with Amazon Pinpoint. Each environment that you create contains a set of variables that are specific to your account in a single AWS Region. If you use the procedures in this section to create more than one environment, you can easily change between Regions by choosing a different environment from the Environment menu in Postman.

To create an environment

1. In Postman, on the File menu, choose New.

2. On the Create New window, choose Environment.

3. On the MANAGE ENVIRONMENTS window, for Environment Name, enter Amazon Pinpoint - Region Name. Replace Region Name with one of the following values:

• US East (N. Virginia)

• US West (Oregon)

(14)

Step 2: Set up Postman

• Asia Pacific (Mumbai)

• Asia Pacific (Sydney)

• Europe (Frankfurt)

• Europe (Ireland)

4. Create six new variables: endpoint, region, serviceName, accountId, accessKey, and secretAccessKey. Use the following table to determine which value to enter in the Initial Value column for each variable.

Region Variable Initial value

endpoint pinpoint.us-

east-1.amazonaws.com

region us-east-1

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

US East (N. Virginia)

secretAccessKey (your IAM secret access key)  

endpoint pinpoint.us-

west-2.amazonaws.com

region us-west-2

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

US West (Oregon)

secretAccessKey (your IAM secret access key)  

endpoint pinpoint.ap-

south-1.amazonaws.com

region ap-south-1

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

Asia Pacific (Mumbai)

secretAccessKey (your IAM secret access key)  

endpoint pinpoint.ap-

southeast-2.amazonaws.com Asia Pacific (Sydney)

region ap-southeast-2

(15)

Step 2: Set up Postman

Region Variable Initial value

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

secretAccessKey (your IAM secret access key)  

endpoint pinpoint.eu-

central-1.amazonaws.com

region eu-central-1

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

Europe (Frankfurt)

secretAccessKey (your IAM secret access key)  

endpoint pinpoint.eu-

west-1.amazonaws.com

region eu-west-1

serviceName mobiletargeting

accountId (your AWS account ID)

accessKey (your IAM access key ID)

Europe (Ireland)

secretAccessKey (your IAM secret access key)

After you create these variables, the MANAGE ENVIRONMENTS window resembles the example shown in the following image.

(16)

Step 2: Set up Postman

When you finish, choose Add.

Important

The access keys shown in the preceding image are fictitious. Never share your IAM access keys with others.

Postman includes features that enable you to share and export environments. If you use these features, be careful to not share your access key ID and secret access key with anybody who shouldn't have access to these credentials.

For more information, see IAM best practices in the IAM User Guide.

5. (Optional) Repeat steps 1–4 for each additional environment that you want to create.

TipIn Postman, you can create as many environments as you need. You can use environments in several ways. For example, you can do all of the following:

• Create a separate environment for every Region where you need to test the Amazon Pinpoint API.

• Create environments that are associated with different AWS accounts.

• Create environments that use credentials that are associated with other IAM users.

6. When you finish creating environments, proceed to the next section.

Step 2.2: Create an Amazon Pinpoint collection in Postman

In Postman, a collection is a group of API requests. Requests in a collection are typically united by a common purpose. In this section, you create a new collection that contains a request template for each operation in the Amazon Pinpoint API.

(17)

Step 2: Set up Postman

To create the Amazon Pinpoint collection 1. In Postman, on the File menu, choose Import.

2. On the Import window, choose Import From Link, and then enter the following URL: https://

raw.githubusercontent.com/awsdocs/amazon-pinpoint-developer-guide/master/Amazon

%20Pinpoint.postman_collection.json.

Choose Import. Postman imports the Amazon Pinpoint collection, which contains 120 example requests.

Step 2.3: Test your Postman configuration

After you import the Amazon Pinpoint collection, you should perform a quick test to make sure that all of the components are properly configured. You can test your configuration by submitting a GetApps request. This request returns a list of all of the projects that exist in your Amazon Pinpoint account in the current AWS Region. This request doesn't require any additional configuration, so it's a good way to quickly test your configuration.

To test the configuration of the Amazon Pinpoint collection

1. In the navigation pane, expand the Amazon Pinpoint collection, and then expand the Apps folder.

2. In the list of requests, choose GetApps.

3. Use the Environment selector to choose the environment that you created in Step 2.1 (p. 6), as shown in the following image.

(18)

Step 2: Set up Postman

4. Choose Send. If the request is sent successfully, the response pane shows a status of 200 OK. You see a response that resembles the example in the following image.

This response shows a list of all of the Amazon Pinpoint projects that exist in your account in the Region that you chose in step 3.

Troubleshooting

When you submit your request, you might see an error. See the following list for several common errors that you might encounter, and for steps that you can take to resolve them.

Error message Problem Resolution

Could not get any response There was an error connecting to https://%7B%7Bendpoint%7D

%7D/v1/apps.

There is no current value for the {{endpoint}} variable, which is set when you choose an environment.

Use the environment selector to choose an environment.

The security token included in

the request is invalid. Postman wasn't able to find the current value of your access key ID or secret access key.

Choose the gear icon near the environment selector, and then choose the current environment.

(19)

Step 3: Send additional requests

Error message Problem Resolution

Make sure that the accessKey and secretAccessKey values appear in both the INITIAL VALUE and CURRENT VALUE columns, and that you entered the credentials correctly.

"Message": "User:

arn:aws:iam::123456789012:user/

PinpointPostmanUser is not authorized to perform:

mobiletargeting:GetApps on resource:

arn:aws:mobiletargeting:us- west-2:123456789012:*"

The IAM policy associated with your user doesn't include the appropriate permissions.

Make sure that your IAM user has the permissions that are described in Step 1.1 (p. 4), and that you provided the correct credentials when you created the environment in Step 2.1 (p. 6).

Step 3: Send additional requests

When you finish configuring and testing Postman, you can start sending additional requests to the Amazon Pinpoint API. This section includes information that you need to know before you start sending requests. It also includes two sample requests that help you understand how to use the Amazon Pinpoint collection.

Important

When you complete the procedures in this section, you submit requests to the Amazon Pinpoint API. These requests are capable of creating new resources in your Amazon Pinpoint account, modifying existing resources, sending messages, changing the configuration of your Amazon Pinpoint projects, and using other Amazon Pinpoint features. Use caution when you execute these requests.

About the examples in the Amazon Pinpoint Postman collection

You have to configure most of the operations in the Amazon Pinpoint Postman collection before you can use them. For GET and DELETE operations, you typically only need to modify the variables that are set on the Pre-request Script tab.

Note

When you use the IAM policy that's shown in Step 1.1 (p. 4), you can't execute any of the DELETE requests that are included in this collection.

For example, the GetCampaign operation requires you to specify a projectId and a campaignId. On the Pre-request Script tab, both of these variables are present, and are populated with example values.

Delete the example values and replace them with the appropriate values for your Amazon Pinpoint project and campaign.

Of these variables, the most commonly used is the projectId variable. The value for this variable should be the unique identifier for the project that your request applies to. To get a list of these identifiers for your projects, you can refer to the response to the GetApps request that you sent in the preceding step of this tutorial. (In Amazon Pinpoint, a "project" is the same thing as an "app" or

"application.") In that response, the Id field provides the unique identifier for a project. To learn more about the GetApps operation and the meaning of each field in the response, see Apps in the Amazon Pinpoint API Reference.

For POST and PUT operations, you also need to modify the request body to include the values that you want to send to the API. For example, when you submit a CreateApp request (which is a POST request),

(20)

Step 3: Send additional requests

you have to specify a name for the project that you create. You can modify the request on the Body tab.

In this example, replace the value next to "Name" with the name of the project. If you want to add tags to the project, you can specify them in the tags object. Or, if you don't want to add tags, you can delete the entire tags object.

NoteThe UntagResource operation also requires you to specify URL parameters. You can specify these parameters on the Params tab. Replace the values in the VALUE column with the tags that you want to delete for the specified resource.

Example request: Creating a project by using the CreateApp operation

Before you create segments and campaigns in Amazon Pinpoint, you first have to create a project. In Amazon Pinpoint, a project consists of segments, campaigns, configurations, and data that are united by a common purpose. For example, you could use a project to contain all of the content that's related to a particular app, or to a specific brand or marketing initiative. When you add customer information to Amazon Pinpoint, that information is associated with a project.

To create a project by sending a CreateApp API request

1. On the Environments menu, choose the AWS Region that you want to create the project in, as shown in the following image.

2. In the Apps folder, choose the CreateApp operation, as shown in the following image.

(21)

Step 3: Send additional requests

3. On the Body tab, next to "Name", replace the placeholder value ("string") with a name for the campaign, such as "MySampleProject".

4. Delete the comma that after the campaign name, and then delete the entire tags object on lines 3 through 5. When you finish, your request should resemble the example that's shown in the following image.

5. Choose Send. If the campaign is created successfully, the response pane shows a status of 201 Created. You see a response that resembles the example in the following image.

Example: Sending an email by using the SendMessages operation

It's very common to use the Amazon Pinpoint SendMessages API to send transactional messages. One advantage to sending messages by using the SendMessages API (as opposed to creating campaigns), is that you can use the SendMessages API to send messages to any address (such as an email address, phone number, or device token). The address that you send messages to doesn't have to exist in your Amazon Pinpoint account already. Compare this to sending messages by creating campaigns. Before

(22)

Step 3: Send additional requests

you send a campaign in Amazon Pinpoint, you have to add endpoints to your Amazon Pinpoint account, create segments, create the campaign, and execute the campaign.

The example in this section shows you how to send a transactional email message directly to a specific email address. You can modify this request to send messages through other channels, such as SMS, mobile push, or voice.

To send an email message by submitting a SendMessages request

1. Verify the email address or domain that you want to use to send the message. For more information, see Verifying email identities in the Amazon Pinpoint User Guide.

NoteIn Amazon Pinpoint, you can only send email from addresses or domains that you've verified. You won't be able to complete the procedure in this section until you verify an email address.

2. On the Environments menu, choose the AWS Region that you want to send the message from, as shown in the following image.

3. In the Messages folder, choose the SendMessages operation.

(23)

Step 3: Send additional requests

4. On the Pre-request Script tab, replace the value of the projectId variable with the ID of a project that already exists in the Region that you selected in step 2 of this section.

5. On the Body tab, delete the example request that's shown in the request editor. Paste the following code:

{

"MessageConfiguration":{

"EmailMessage":{

"FromAddress":"[email protected]", "SimpleEmail":{

"Subject":{

"Data":"Sample Amazon Pinpoint message"

},

"HtmlPart":{

"Data":"<h1>Test message</h1><p>This is a sample message sent from <a href=\"https://aws.amazon.com/pinpoint\">Amazon Pinpoint</a> using the SendMessages API.</p>"

},

"TextPart":{

"Data":"This is a sample message sent from Amazon Pinpoint using the SendMessages API."

}

(24)

Setting up an SMS registration system

} } },

"Addresses":{

"[email protected]": { "ChannelType": "EMAIL"

} } }

6. In the preceding code, replace [email protected] with your verified email address. Replace [email protected] with the address that you want to send the message to.

NoteIf your account is still in the Amazon Pinpoint email sandbox, you can only send email to addresses or domains that are verified in your Amazon Pinpoint account. For more information about having your account removed from the sandbox, see Requesting production access for email in the Amazon Pinpoint User Guide.

7. Choose Send. If the message is sent successfully, the response pane shows a status of 200 OK. You see a response that resembles the example in the following image.

Tutorial: Setting up an SMS registration system

SMS messages (text messages) are a great way to send time-sensitive messages to your customers. These days, many people keep their phones nearby at all times. Also, SMS messages tend to capture people's attention more than push notifications, emails, or phone calls.

A common way to capture customers' mobile phone numbers is to use a web-based form. After you verify the customer's phone number and confirm their subscription, you can start sending promotional, transactional, and informational SMS messages to that customer.

This tutorial shows you how to set up a web form to capture customers' contact information. The web form sends this information to Amazon Pinpoint. Next, Amazon Pinpoint verifies that the phone number is valid, and captures other metadata that's related to the phone number. After that, Amazon Pinpoint sends the customer a message asking them to confirm their subscription. After the customer confirms their subscription, Amazon Pinpoint opts them in to receiving your messages.

The following architecture diagram shows the flow of data in this solution.

(25)

About double opt-in

About double opt-in

This tutorial shows you how to set up a double opt-in system in Amazon Pinpoint that uses two-way SMS messaging.

In an SMS double opt-in system, a customer provides you with their phone number by submitting it in a web form or within your app. When you receive the request from the customer, you create a new endpoint in Amazon Pinpoint. The new endpoint should be opted out of your communications. Next, you send a message to that phone number. In your message, you ask the recipient to confirm their subscription by replying with a specific word or phrase (such as "Yes" or "Confirm"). If the customer responds to the message with the word or phrase that you specified, you change the endpoint's status to opted-in. Otherwise, if the customer doesn't respond or they respond with a different word or phrase, you can leave the endpoint with a status of opted-out.

About this solution

This section contains information about the solution that you're building in this tutorial.

Intended Audience

This tutorial is intended for developer and system implementer audiences. You don't have to be familiar with Amazon Pinpoint to complete the steps in this tutorial. However, you should be comfortable managing IAM policies, creating Lambda functions in Node.js, and deploying web content.

Features Used

This tutorial includes usage examples for the following Amazon Pinpoint features:

• Sending transactional SMS messages

• Obtaining information about phone numbers by using phone number validation

• Receiving incoming SMS messages by using two-way SMS messaging

• Creating dynamic segments

• Creating campaigns

• Interacting with the Amazon Pinpoint API by using AWS Lambda

Time Required

It should take about one hour to complete this tutorial. After you implement this solution, there are additional steps that you can take to refine the solution to suit your unique use case.

(26)

Prerequisites

Regional Restrictions

This tutorial requires you to lease a long code by using the Amazon Pinpoint console. You can use the Amazon Pinpoint console to lease dedicated long codes that are based in several countries. However, only long codes that are based in the United States or Canada can be used to send SMS messages. (You can use long codes that are based in other countries and regions to send voice messages.)

We developed the code examples in this tutorial with this restriction in mind. For example, the code examples assume that the recipient's phone number always has 10 digits, and a country code of 1. If you implement this solution in countries or regions other than the United States or Canada, you have to modify the code examples appropriately.

Resource Usage Costs

There's no charge for creating an AWS account. However, by implementing this solution, you might incur the following costs:

Long code lease costs – To complete this tutorial, you have to lease a long code. Long codes that are based in the United States (excluding US Territories) and Canada cost $1.00 per month.

Phone number validation usage – The solution in this tutorial uses the phone number validation feature of Amazon Pinpoint to verify that each number you receive is valid and properly formatted, and to obtain additional information about the phone number. You pay $0.006 for each phone number validation request.

Message sending costs – The solution in this tutorial sends outbound SMS messages. You pay for each message that you send through Amazon Pinpoint. The price that you pay for each message depends on the country or region of the recipient. If you send messages to recipients in the United States (excluding US Territories), you pay $0.00645 per message. If you send messages to recipients in Canada, you pay between $0.00109–$0.02, depending on the recipient's carrier and location.

Message receiving costs – This solution also receives and processes incoming SMS messages. You pay for each incoming message that's sent to phone numbers that are associated with your Amazon Pinpoint account. The price that you pay depends on where the receiving phone number is based. If your receiving number is based in the United States (excluding US Territories), you pay $0.0075 per incoming message. If your number is based in Canada, you pay $0.00155 per incoming message.

Lambda usage – This solution uses two Lambda functions that interact with the Amazon Pinpoint API.

When you call a Lambda function, you're charged based on the number of requests for your functions, for the time that it takes for your code to execute, and for the amount of memory that your functions use. The functions in this tutorial use very little memory, and typically run for 1–3 seconds. Some or all of your usage of this solution might fall under the Lambda free usage tier. For more information, see Lambda pricing.

API Gateway usage – The web form in this solution calls an API that's managed by API Gateway. For every million calls to API Gateway, you pay $3.50–$3.70, depending on which AWS Region you use Amazon Pinpoint in. For more information, see API Gateway pricing.

Web hosting costs – This solution includes a web-based form that you have to host on your website.

The price that you pay for hosting this content depends on your web hosting provider.

NoteAll prices shown in this list are in US Dollars (USD).

Next: Prerequisites (p. 19)

Prerequisites

Before you begin this tutorial, you have to complete the following prerequisites:

• You have to have an AWS account. To create an AWS account, go to https://console.aws.amazon.com/

and choose Create a new AWS account.

(27)

Step 1: Set up Amazon Pinpoint

• The account that you use to sign in to the AWS Management Console has to be able to perform the following tasks:

• Create new IAM policies and roles

• Create new Amazon Pinpoint projects

• Create new Lambda functions

• Create new APIs in API Gateway

• You have to have a method of hosting webpages, and you should know how to publish webpages.

Although you can use AWS services to host your webpages, you aren't required to.

Tip

To learn more about hosting webpages using AWS services, see Host a static webpage.

Next: Set Up Amazon Pinpoint (p. 20)

Step 1: Set up Amazon Pinpoint

The first step in implementing this solution is to set up Amazon Pinpoint. In this section, you do the following:

• Create an Amazon Pinpoint project

• Enable the SMS channel and lease a long code

• Configure two-way SMS messaging

Before you begin with this tutorial, you should review the prerequisites (p. 19).

Step 1.1: Create an Amazon Pinpoint project

To get started, you need to create an Amazon Pinpoint project. In Amazon Pinpoint, a project consists of segments, campaigns, configurations, and data that are united by a common purpose. For example, you could use a project to contain all of the content that's related to a particular app, or to a specific brand or marketing initiative. When you add customer information to Amazon Pinpoint, that information is associated with a project.

The steps involved in creating a new project differ depending on whether you've created a project in Amazon Pinpoint previously.

Creating a project (new Amazon Pinpoint users)

These steps describe the process of creating a new Amazon Pinpoint project if you've never created a project in the current AWS Region.

To create a project

1. Sign in to the AWS Management Console and open the Amazon Pinpoint console at https://

console.aws.amazon.com/pinpoint/.

2. Use the Region selector to choose the AWS Region that you want to use, as shown in the following image. If you're unsure, choose the Region that's located closest to you.

(28)

Step 1: Set up Amazon Pinpoint

3. Under Get started, for Name, enter a name for the campaign (such as SMSRegistration), and then choose Create project.

4. On the Configure features page, choose Skip this step.

5. In the navigation pane, choose All projects.

6. On the All projects page, next to the project you just created, copy the value that's shown in the Project ID column.

TipYou need to use this ID in a few different places in this tutorial. Keep the project ID in a convenient place so that you can copy it later.

Creating a project (existing Amazon Pinpoint users)

These steps describe the process of creating a new Amazon Pinpoint project if you've already created projects in the current AWS Region.

To create a project

1. Sign in to the AWS Management Console and open the Amazon Pinpoint console at https://

console.aws.amazon.com/pinpoint/.

2. Use the Region selector to choose the AWS Region that you want to use, as shown in the following image. If you're unsure, choose the Region that's located closest to you.

3. On the All projects page, choose Create a project.

4. On the Create a project window, for Project name, enter a name for the project (such as SMSRegistration). Choose Create.

5. On the Configure features page, choose Skip this step.

6. In the navigation pane, choose All projects.

7. On the All projects page, next to the project you just created, copy the value that's shown in the Project ID column.

TipYou need to use this ID in a few different places in this tutorial. Keep the project ID in a convenient place so that you can copy it later.

Step 1.2: Obtain a dedicated long code

After you create a project, you can start to configure features within that project. In this section, you enable the SMS channel, and obtain a dedicated long code to use when sending SMS messages.

NoteThis section assumes that you're leasing a long code that's based in the United States or Canada.

If you follow the procedures in this section, but choose a country other than the United States or Canada, you won't be able to use that number to send SMS messages. To learn more about leasing SMS-capable long codes in countries other than the United States or Canada, see Requesting dedicated long codes for SMS messaging with Amazon Pinpoint in the Amazon Pinpoint User Guide.

1. In the navigation pane, under Settings, choose SMS and voice.

(29)

Step 1: Set up Amazon Pinpoint

2. Next to SMS settings, choose Edit.

3. Under General settings, choose Enable the SMS channel for this project, and then choose Save changes.

4. Next to Number settings, choose Request long codes.

5. Under Long code specifications, do the following:

• For Target country or region, choose United States or Canada.

• For Default call type, choose Transactional.

• For Quantity, choose 1.

6. Choose Request long code.

Step 1.3: Enable two-way SMS

Now that you have a dedicated phone number, you can set up two-way SMS. Enabling two-way SMS makes it possible for your customers to respond to the SMS messages that you send them. In this solution, you use two-way SMS to give your customers a way to confirm that they want to subscribe to your SMS program.

1. On the SMS and voice settings page, under Number settings, choose the long code that you received in the previous section.

2. Under Required keywords, do the following:

• Next to the HELP keyword, for Response message, enter the message that you want Amazon Pinpoint to automatically send recipients when they send the keyword "HELP" (or its variations) to this long code.

• Next to the STOP keyword, for Response message, enter the message that you want Amazon Pinpoint to automatically send recipients when they send the keyword "STOP" (or its variations) to this long code.

NoteWhen a recipient sends the keyword "STOP" to one of your long codes, Amazon Pinpoint automatically opts that recipient out of all future SMS messages that are sent from this project.

3. Under Registered keyword, for Keyword, enter the word that customers can send you to register to receive messages from you. Then, for Response message, enter the message that Amazon Pinpoint automatically sends when a customer sends the keyword to this long code.

NoteFor the purposes of this tutorial, the value that you enter in this section isn't important.

In this scenario, customers register for your SMS messaging program by completing a registration form, rather than by sending you a message directly.

4. Under Two-Way SMS, choose Enable two-way SMS.

5. Under Incoming message destination, choose Create a new SNS topic. Enter an Amazon SNS topic name, such as SMSRegistrationFormTopic.

6. Under Two-way SMS keywords, for Keyword, enter the word that customers send you to confirm their subscriptions (such as Yes or Confirm).

NoteThis value isn't case sensitive.

7. For Response message, enter the message that Amazon Pinpoint automatically sends to customers when they send you the keyword that you specified in the previous step.

8. Choose Save.

Next: Create IAM Policies and Roles (p. 23)

(30)

Step 2: Create IAM policies and roles

Step 2: Create IAM policies and roles

The next step in implementing the SMS registration solution is to configure a policy and a role in AWS Identity and Access Management (IAM). For this solution, you need to create a policy that provides access to certain resources that are related to Amazon Pinpoint. You then create a role and attach the policy to it. Later in this tutorial, you create an AWS Lambda function that uses this role to call certain operations in the Amazon Pinpoint API.

Step 2.1: Create an IAM policy

This section shows you how to create an IAM policy. Users and roles that use this policy are able to do the following:

• Use the Phone Number Validate feature

• View, create, and update Amazon Pinpoint endpoints

• Send messages to Amazon Pinpoint endpoints

In this tutorial, you want to give Lambda the ability to perform these tasks. However, for added security, this policy uses the principal of granting least privilege. In other words, it grants only the permissions that are required to complete this solution, and no more. This policy is restricted in the following ways:

• You can only use it to call the Phone Number Validate API in a specific Region.

• You can only use it to view, create, or update endpoints that are associated with a specific Amazon Pinpoint project.

• You can only use it to send messages to endpoints that are associated with a specific Amazon Pinpoint project.

To create the policy

1. Sign in to the AWS Management Console and open the IAM console at https://

console.aws.amazon.com/iam/.

2. In the navigation pane, choose Policies, and then choose Create policy.

3. On the JSON tab, paste the following code.

{

"Version": "2012-10-17", "Statement": [

{

"Effect": "Allow", "Action": [

"logs:CreateLogStream", "logs:PutLogEvents", "logs:CreateLogGroup"

],

"Resource": "arn:aws:logs:*:*:*"

}, {

"Effect": "Allow",

"Action": "mobiletargeting:SendMessages",

"Resource": "arn:aws:mobiletargeting:region:accountId:apps/projectId/*"

}, {

"Effect": "Allow", "Action": [

"mobiletargeting:GetEndpoint", "mobiletargeting:UpdateEndpoint",

(31)

Step 3: Create Lambda functions

"mobiletargeting:PutEvents"

],

"Resource": "arn:aws:mobiletargeting:region:accountId:apps/projectId/

endpoints/*"

}, {

"Effect": "Allow",

"Action": "mobiletargeting:PhoneNumberValidate",

"Resource": "arn:aws:mobiletargeting:region:accountId:phone/number/validate"

} ] }

In the preceding example, do the following:

• Replace region with the AWS Region that you use Amazon Pinpoint in, such as us-east-1 or eu-central-1.

TipFor a complete list of AWS Regions where Amazon Pinpoint is available, see AWS regions and endpoints in the AWS General Reference.

• Replace accountId with the unique ID for your AWS account.

• Replace projectId with the unique ID of the project that you created in Step 1.1 (p. 20) of this tutorial.

NoteThe logs actions enable Lambda to log its output in CloudWatch Logs.

4. Choose Review policy.

5. For Name, enter a name for the policy, such as RegistrationFormPolicy. Choose Create policy.

Step 2.2: Create an IAM role

To create the role

1. Open the IAM console at https://console.aws.amazon.com/iam/.

2. In the IAM console, in the navigation pane, choose Roles, and then choose Create role.

3. Under Choose the service that will use this role, choose Lambda, and then choose Next:

Permissions.

NoteThe service that you choose in this step isn't important—regardless of the service that you choose, you apply your own policy in the next step.

4. Under Attach permissions policies, choose the policy that you created in the previous section, and then choose Next: Tags.

5. Choose Next: Review.

6. Under Review, for Name, enter a name for the role, such as SMSRegistrationForm. Choose Create role.

Next: Create Lambda functions (p. 24)

Step 3: Create Lambda functions

This solution uses two Lambda functions. This section shows you how to create and configure these functions. Later, you set up API Gateway and Amazon Pinpoint to execute these functions when certain

(32)

Step 3: Create Lambda functions

events occur. Both of these functions create and update endpoints in the Amazon Pinpoint project that you specify. The first function also uses the phone number validation feature.

Step 3.1: Create the function that validates customer information and creates endpoints

The first function takes input from your registration form, which it receives from Amazon API Gateway.

It uses this information to obtain information about the customer's phone number by using the phone number validation (p. 116) feature of Amazon Pinpoint. The function then uses the validated data to create a new endpoint in the Amazon Pinpoint project that you specify. By default, the endpoint that the function creates is opted out of future communications from you, but this status can be changed by the second function. Finally, this function sends the customer a message asking them to verify that they want to receive SMS communications from you.

To create the Lambda function

1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.

2. Choose Create function.

3. Under Create a function, choose Blueprints.

4. In the search field, enter hello, and then press Enter. In the list of results, choose the hello-world Node.js function, as shown in the following image. Choose Configure.

5. Under Basic information, do the following:

• For Name, enter a name for the function, such as RegistrationForm.

• For Role, select Choose an existing role.

(33)

Step 3: Create Lambda functions

• For Existing role, choose the SMSRegistrationForm role that you created in Step 2.2 (p. 24).

When you finish, choose Create function.

6. Delete the sample function in the code editor, and then paste the following code:

var AWS = require('aws-sdk');

var pinpoint = new AWS.Pinpoint({region: process.env.region});

// Make sure the SMS channel is enabled for the projectId that you specify.

// See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-setup.html var projectId = process.env.projectId;

// You need a dedicated long code in order to use two-way SMS.

// See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-voice- manage.html#channels-voice-manage-request-phone-numbers

var originationNumber = process.env.originationNumber;

// This message is spread across multiple lines for improved readability.

var message = "ExampleCorp: Reply YES to confirm your subscription. 2 msgs per "

+ "month. No purchase req'd. Msg&data rates may apply. Terms: "

+ "example.com/terms-sms";

var messageType = "TRANSACTIONAL";

exports.handler = (event, context, callback) => { console.log('Received event:', event);

validateNumber(event);

};

function validateNumber (event) {

var destinationNumber = event.destinationNumber;

if (destinationNumber.length == 10) {

destinationNumber = "+1" + destinationNumber;

} var params = {

NumberValidateRequest: { IsoCountryCode: 'US',

PhoneNumber: destinationNumber }

};

pinpoint.phoneNumberValidate(params, function(err, data) { if (err) {

console.log(err, err.stack);

} else {

console.log(data);

//return data;

if (data['NumberValidateResponse']['PhoneTypeCode'] == 0) {

createEndpoint(data, event.firstName, event.lastName, event.source);

} else {

console.log("Received a phone number that isn't capable of receiving "

+"SMS messages. No endpoint created.");

} } });

}

function createEndpoint(data, firstName, lastName, source) {

var destinationNumber = data['NumberValidateResponse']['CleansedPhoneNumberE164'];

var endpointId = data['NumberValidateResponse']

['CleansedPhoneNumberE164'].substring(1);

var params = {

(34)

Step 3: Create Lambda functions

ApplicationId: projectId,

// The Endpoint ID is equal to the cleansed phone number minus the leading // plus sign. This makes it easier to easily update the endpoint later.

EndpointId: endpointId, EndpointRequest: { ChannelType: 'SMS',

Address: destinationNumber,

// OptOut is set to ALL (that is, endpoint is opted out of all messages) // because the recipient hasn't confirmed their subscription at this // point. When they confirm, a different Lambda function changes this // value to NONE (not opted out).

OptOut: 'ALL', Location: {

PostalCode:data['NumberValidateResponse']['ZipCode'], City:data['NumberValidateResponse']['City'],

Country:data['NumberValidateResponse']['CountryCodeIso2'], },

Demographic: {

Timezone:data['NumberValidateResponse']['Timezone']

},

Attributes: { Source: [ source ] }, User: {

UserAttributes: { FirstName: [ firstName ],

LastName: [ lastName ]

} } }

}; pinpoint.updateEndpoint(params, function(err,data) { if (err) {

console.log(err, err.stack);

} else {

console.log(data);

//return data;

sendConfirmation(destinationNumber);

} });

}

function sendConfirmation(destinationNumber) { var params = {

ApplicationId: projectId, MessageRequest: {

Addresses: {

[destinationNumber]: { ChannelType: 'SMS' }

},

MessageConfiguration: { SMSMessage: {

Body: message,

MessageType: messageType,

OriginationNumber: originationNumber }

} }

(35)

Step 3: Create Lambda functions

};

pinpoint.sendMessages(params, function(err, data) { // If something goes wrong, print an error message.

if(err) {

console.log(err.message);

// Otherwise, show the unique ID for the message.

} else {

console.log("Message sent! "

+ data['MessageResponse']['Result'][destinationNumber]['StatusMessage']);

} });

}

7. Under Environment variables, do the following:

• In the first row, create a variable with a key of originationNumber. Next, set the value to the phone number of the dedicated long code that you received in Step 1.2 (p. 21).

NoteBe sure to include the plus sign (+) and the country code for the phone number. Don't include any other special characters, such as dashes (-), periods (.), or parentheses.

• In the second row, create a variable with a key of projectId. Next, set the value to the unique ID of the project that you created in Step 1.1 (p. 20).

• In the third row, create a variable with a key of region. Next, set the value to the Region that you use Amazon Pinpoint in, such as us-east-1 or us-west-2.

When you finish, the Environment Variables section should resemble the example shown in the following image.

8. At the top of the page, choose Save.

Step 3.1.1: Test the function

After you create the function, you should test it to make sure that it's configured properly. Also, make sure that the IAM role you created has the appropriate permissions.

To test the function 1. Choose Test.

2. On the Configure test event window, do the following:

• Choose Create new test event.

(36)

Step 3: Create Lambda functions

• For Event name, enter a name for the test event, such as MyPhoneNumber.

• Erase the example code in the code editor. Paste the following code:

{

"destinationNumber": "2065550142", "firstName": "Carlos",

"lastName": "Salazar",

"source": "Registration form test"

}

• In the preceding code example, replace the values of the destinationNumber, firstName, and lastName attributes with the values that you want to use for testing, such as your personal contact details. When you test this function, it sends an SMS message to the phone number that you specify in the destinationNumber attribute. Make sure that the phone number that you specify is able to receive SMS messages.

• Choose Create.

3. Choose Test again.

4. Under Execution result: succeeded, choose Details. In the Log output section, review the output of the function. Make sure that the function ran without errors.

Check the device that's associated with the destinationNumber that you specified to make sure that it received the test message.

5. Open the Amazon Pinpoint console at https://console.aws.amazon.com/pinpoint/.

6. On the All projects page, choose the project that you created in Step 1.1 (p. 20).

7. In the navigation pane, choose Segments. On the Segments page, choose Create a segment.

8. In Segment group 1, under Add filters to refine your segment, choose Filter by user.

9. For Choose a user attribute, choose FirstName. Then, for Choose values, choose the first name that you specified in the test event.

The Segment estimate section should show that there are zero eligible endpoints, and one total endpoint, as shown in the following image. This result is expected. When the function creates a new endpoint, the endpoint is opted out. Segments in Amazon Pinpoint automatically exclude opted-out endpoints.

(37)

Step 3: Create Lambda functions

Step 3.2: Create the function that opts in customers to your communications

The second function is only executed when a customer replies to the message that's sent by the first function. If the customer's reply includes the keyword that you specified in Step 1.3 (p. 21), the

function updates their endpoint record to opt them in to future communications. Amazon Pinpoint also automatically responds with the message that you specified in Step 1.3.

If the customer doesn't respond, or responds with anything other than the designated keyword, then nothing happens. The customer's endpoint remains in Amazon Pinpoint, but it can't be targeted by segments.

To create the Lambda function

1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.

2. Choose Create function.

3. Under Create function, choose Blueprints.

4. In the search field, enter hello, and then press Enter. In the list of results, choose the hello-world Node.js function, as shown in the following image. Choose Configure.

5. Under Basic information, do the following:

• For Name, enter a name for the function, such as RegistrationForm_OptIn.

• For Role, select Choose an existing role.

• For Existing role, choose the SMSRegistrationForm role that you created in Step 2.2 (p. 24).

When you finish, choose Create function.

6. Delete the sample function in the code editor, and then paste the following code:

var AWS = require('aws-sdk');

var projectId = process.env.projectId;

var confirmKeyword = process.env.confirmKeyword.toLowerCase();

var pinpoint = new AWS.Pinpoint({region: process.env.region});

exports.handler = (event, context) => { console.log('Received event:', event);

var timestamp = event.Records[0].Sns.Timestamp;

var message = JSON.parse(event.Records[0].Sns.Message);

var originationNumber = message.originationNumber;

var response = message.messageBody.toLowerCase();

if (response.includes(confirmKeyword)) {

updateEndpointOptIn(originationNumber, timestamp);

}};

function updateEndpointOptIn (originationNumber, timestamp) { var endpointId = originationNumber.substring(1);

var params = {

ApplicationId: projectId, EndpointId: endpointId, EndpointRequest: {

Address: originationNumber, ChannelType: 'SMS',

OptOut: 'NONE', Attributes: { OptInTimestamp: [

參考文獻

相關文件

– If your virus can infect all .COM files under the same folder, and when you open the infected file, it infects all other files, you get a nice score. • If your virus can do all

Once you get down to a purely business level, your influence is gone and the true light of your life isdimmed. You must work in the missionary spirit, with a breadth of charity

• When a system undergoes any chemical or physical change, the accompanying change in internal energy, ΔE, is the sum of the heat added to or liberated from the system, q, and the

Walsh, Hooven and Kronick (2013) reported that a critical step in reducing youth suicide is to move beyond having a single responder in a school. When responding to students with

You may spend more time chatting online than talking face-to-face with your friends or family.. So, are you a heavy

An OFDM signal offers an advantage in a channel that has a frequency selective fading response.. As we can see, when we lay an OFDM signal spectrum against the

• When a call is exercised, the holder pays the strike price in exchange for the stock.. • When a put is exercised, the holder receives from the writer the strike price in exchange

• When a call is exercised, the holder pays the strike price in exchange for the stock.. • When a put is exercised, the holder receives from the writer the strike price in exchange