

**End of support notice:** On October 30, 2026, AWS will end support for Amazon Pinpoint. After October 30, 2026, you will no longer be able to access the Amazon Pinpoint console or Amazon Pinpoint resources (endpoints, segments, campaigns, journeys, and analytics). For more information, see [Amazon Pinpoint end of support](https://docs.aws.amazon.com/console/pinpoint/migration-guide). **Note:** APIs related to SMS, voice, mobile push, OTP, and phone number validate are not impacted by this change and are supported by AWS End User Messaging.

# Tutorials
<a name="tutorials"></a>

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. 

**Topics**
+ [Using Postman with Amazon Pinpoint](tutorials-using-postman.md)
+ [Set up an SMS registration system](tutorials-two-way-sms.md)

# Tutorial: Using Postman with the Amazon Pinpoint API
<a name="tutorials-using-postman"></a>

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.

**Note**  
Postman 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](https://support.postman.com/hc/en-us) on the Postman website.

## About this tutorial
<a name="tutorials-using-postman-about"></a>

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

**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](https://aws.amazon.com/pinpoint/pricing/).

# Prerequisites for using Postman with Amazon Pinpoint
<a name="tutorials-using-postman-prerequisites"></a>

Before you begin this tutorial, complete the following prerequisites:
+ You must have an AWS account. To create an AWS account, go to [https://console.aws.amazon.com/](https://console.aws.amazon.com/) and choose **Create a new AWS account**.
+ Make sure that the account that you use to sign in to the AWS Management Console can create new IAM policies and roles.
+ Make sure you have at least one sample project created that has email turned on and a verified email identity. See [Creating an Amazon Pinpoint project with email support](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-email-setup-create.html) in the *Amazon Pinpoint User Guide*.
+ Make sure you have an AWS Account ID. Your AWS Account ID can be found in the upper-right corner of the console or you can use the command line interface (CLI). See [Finding your AWS account ID](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-identifiers.html#FindAccountId).
+ You must download and install Postman on your computer. You can download Postman from the [Postman website](https://www.getpostman.com).
+ After you install Postman on your computer, create a Postman account. When you first start the Postman application, you're prompted to log in or create a new account. Follow the instructions provided by Postman to log in to your account or to create an account if you don't already have one.

**Next**: [Create IAM policies and roles](tutorials-using-postman-iam-user.md)

# Create IAM policies and roles for use with Amazon Pinpoint
<a name="tutorials-using-postman-iam-user"></a>

When you use Postman to test the Amazon Pinpoint API, the first step is to create a user. In this section, you create a policy that permits users to interact with all the Amazon Pinpoint resources. Then, you create a user and attach the policy directly to the user .

## Create an IAM policy
<a name="tutorials-using-postman-iam-user-create-policy"></a>

Learn how to create an IAM policy. Users and roles that use this policy can 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/](https://console.aws.amazon.com/iam/).

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

1. In the **Policy editor** select **JSON**. Delete any JSON that is current in the **Policy editor** so that it is blank. Copy and paste the following JSON into the **Policy editor** and then in the **Policy editor** replace all instances of *123456789012* with your AWS account ID.

   Your AWS account ID can be found in the upper right hand corner of the console, or you can use the CLI, see [Finding your AWS account ID](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-identifiers.html#FindAccountId).
**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](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html) in the IAM User Guide. You can also use the [CreatePolicyVersion](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html) operation in the IAM API to update this policy.  
Also, this policy includes permissions that permit 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.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "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": "*"
           }
       ]
   }
   ```

------

   Choose **Next**.

1. For **Policy name**, enter a name for the policy, such as **PostmanAccessPolicy**. Choose **Create policy**.

1. (Optional) You can add tags to the policy by selecting **Add Tag**.

1. Choose **Next: Review**.

## Create an IAM user
<a name="tutorials-using-postman-iam-user-create-user"></a>

**Warning**  
IAM users have long-term credentials, which presents a security risk. To help mitigate this risk, we recommend that you provide these users with only the permissions they require to perform the task and that you remove these users when they are no longer needed.

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

**To create the user**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. On the IAM console, in the navigation pane, choose **Users**, and then choose **Create users**.

1. Under **User details**, for **User name**, enter a name that identifies the user, such as **PostmanUser**. Then choose **Next**.

1. Under **Set permissions**, for **Permissions options**, choose **Attach policies directly**. 

1. Under **Permissions policies**, choose the policy (**PostmanAccessPolicy**) that you created in [Create an IAM policy](#tutorials-using-postman-iam-user-create-policy). Then choose **Next**.

1. On the **Review and create** page, optionally add tags that help you identify the user. For more information about using tags, see [Tagging IAM resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) in the *IAM User Guide*. 

1. When you're ready to create the user, choose **Create user**.

## Create access keys
<a name="tutorials-using-postman-iam-user-create-key"></a>

**Warning**  
This scenario requires IAM users with programmatic access and long-term credentials, which presents a security risk. To help mitigate this risk, we recommend that you provide these users with only the permissions they require to perform the task and that you remove these users when they are no longer needed. Access keys can be updated if necessary. For more information, see [Update access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id-credentials-access-keys-update.html) in the *IAM User Guide*.

 IAM provides a set of credentials that you can use to allow Postman to carry out Amazon Pinpoint API operations.

**To create the user**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. On the IAM console, in the navigation pane, choose **Users**. Select the user (**PostmanUser**) created in [Create an IAM user](#tutorials-using-postman-iam-user-create-user), and then select the **Security credentials** tab.

1. In the **Access keys** section, choose **Create access key**.

1. On the **Access key best practices & alternatives** page, select **Application running outside AWS**. 

   Then choose **Next**.

1. (Optional) You can add a description tag to the policy.

1. Choose **Create access key**.

1. On the **Retrieve access keys** page, copy the credentials that are shown in the **Access key** and **Secret access key** columns.
**Note**  
You must 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. We recommend that you copy it and save it in a safe location.

1. After you've saved both keys, choose **Done**.

**Next**: [Set up Postman](tutorials-using-postman-configuration.md)

# Set up Postman for use with Amazon Pinpoint
<a name="tutorials-using-postman-configuration"></a>

Now that you've created a user 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.

## Create a Postman workspace
<a name="tutorials-using-postman-configuration-create-workspace"></a>

In Postman, a *workspace* is an organizational container for projects and environments. In this section, you create at least one workspace to use with Amazon Pinpoint.

**Create a workspace**

In Postman, choose the more actions choose **File**, then choose **New**.

1. On the **Create New** window, choose **Workspace**.

1. Enter a name, summary, and set the visibility to personal. Then choose **Create Workspace**.

## Create Postman environments
<a name="tutorials-using-postman-configuration-create-environments"></a>

In Postman, an *environment* is a set of variables that are stored as key-value pairs. You can use environments to 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 change between Regions by choosing a different environment from the **Environment** menu in Postman.

**To create an environment**

1. In Postman, choose the more actions menu, choose **File**, then choose **New**.

1. On the **Create New** window, choose **Environment**.

1. 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)
   + Asia Pacific (Mumbai)
   + Asia Pacific (Sydney)
   + Europe (Frankfurt)
   + Europe (Ireland)
**Note**  
At a minimum, you only need to create one environment for a single AWS Region, and that AWS Region must contain one project. If you haven't created a project in one of the previously listed AWS Regions, see [Creating an Amazon Pinpoint project with email support](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-email-setup-create.html) in the *Amazon Pinpoint User Guide*.

1. 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** and **Current Value** columns for each variable.     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/tutorials-using-postman-configuration.html)

   After you create these variables, the **MANAGE ENVIRONMENTS** window resembles the example shown in the following image.  
![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Postman_Tutorial_2.1_4.png)

   When you finish, choose **Save**.
**Important**  
The access keys shown in the preceding image are fictitious. Don't share your IAM access keys with others.  
Postman includes features that permit you to share and export environments. If you use these features, make sure not to 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](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

1. (Optional) Repeat steps 1–4 for each additional environment that you want to create.
**Tip**  
In Postman, you can create as many environments as you need. You can use environments in the following ways:  
Create a separate environment for every Region where you must test the Amazon Pinpoint API.
Create environments that are associated with different AWS accounts.
Create environments that use credentials that are associated with other user.

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

## Create an Amazon Pinpoint collection in Postman
<a name="tutorials-using-postman-configuration-create-pinpoint-collection"></a>

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.

**To create the Amazon Pinpoint collection**

1. In Postman, choose the more actions menu, choose **File**, then choose **Import**.

1. 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\$1collection.json](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.

## Test your Postman configuration
<a name="tutorials-using-postman-configuration-test-operation"></a>

After you import the Amazon Pinpoint collection, we recommend that you perform a quick test to verify 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 test your configuration.

**To test the configuration of the Amazon Pinpoint collection**

1. In the left navigation pane, select **Collections**, expand the **Amazon Pinpoint** collection, and then expand the **Apps** folder.

1. In the list of requests, choose **GetApps**.

1. Use the **Environment** selector to choose the environment that you created in [Create Postman environments](#tutorials-using-postman-configuration-create-environments).

1. 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.  
![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Postman_Tutorial_2.3_3.png)
**Note**  
If you don't have any projects created in the AWS Region then Amazon Pinpoint returns `{ "Item": [] }`.

   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
<a name="tutorials-using-postman-configuration-test-operation-troubleshooting"></a>

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. Verify 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:\$1"  |  The IAM policy associated with your user doesn't include the appropriate permissions.  |  Verify that your user has the permissions that are described in [Create an IAM policy](tutorials-using-postman-iam-user.md#tutorials-using-postman-iam-user-create-policy), and that you provided the correct credentials when you created the environment in [Create Postman workspace](#tutorials-using-postman-configuration-create-environments).  | 

**Next**: [Send additional requests](tutorials-using-postman-sample-requests.md)

# Send requests to the Amazon Pinpoint API
<a name="tutorials-using-postman-sample-requests"></a>

When you finish configuring and testing Postman, you can start sending additional requests to the Amazon Pinpoint API. This section includes information that you must know before you start sending requests. It also includes two sample requests that describe 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 create new resources in your Amazon Pinpoint account, modify existing resources, send messages, change the configuration of your Amazon Pinpoint projects, and use other Amazon Pinpoint features. Use caution when you carry out these requests.

## Examples in the Amazon Pinpoint Postman collection
<a name="tutorials-using-postman-sample-requests-about"></a>

You must 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 [Create an IAM policy](tutorials-using-postman-iam-user.md#tutorials-using-postman-iam-user-create-policy), you can't carry out 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 applicable 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, refer to the response to the `GetApps` request that you sent in the preceding step of this tutorial. 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](https://docs.aws.amazon.com/pinpoint/latest/apireference/apps.html) in the *Amazon Pinpoint API Reference*.

**Note**  
In Amazon Pinpoint, a "project" is the same as an "app" or "application."

For `POST` and `PUT` operations, you must also 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, you must 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.

**Note**  
The `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: Create a project by using the `CreateApp` operation
<a name="tutorials-using-postman-sample-requests-createapp"></a>

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.  
![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Postman_Tutorial_Environments.png)

    In this example, Postman has been configured so that the **Environments** menu shows the following four options:
   + US East (N. Virginia)
   + US West (Oregon)
   + Europe (Frankfurt)
   + Europe (Ireland)

1. In the **Apps** folder, choose the **CreateApp** operation>.  
![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Postman_Tutorial_3.2_2.png)

   The **Apps** folder in the Amazon Pinpoint Postman collection are expanded and show the following requests:
   + `GetApp`
   + `GetApps`
   + `CreateApp`
   + `DeleteApp`

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

1. Delete the comma 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 code snippet.

   ```
   {
       "Name": "MySampleProject"
   }
   ```

   Postman is configured to send the request as a raw JSON payload.

1. Choose **Send**. If the campaign is created successfully, the response pane shows a status of `201 Created`.

   ```
   {
       "Name": "MySampleProject"
       "Id": "12345678901234567890123456789012",
       "Arn": "arn:aws:mobiletargeting:us-east-1:123456789012:apps/12345678901234567890123456789012",
       "tags": {}
   }
   ```

## Example: Send an email by using the `SendMessages` operation
<a name="tutorials-using-postman-sample-requests-sendmessages"></a>

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 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. Let's compare this method to sending messages by creating campaigns. Before you send a campaign in Amazon Pinpoint, you must add endpoints to your Amazon Pinpoint account, create segments, create the campaign, and carry out 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 that the email channel is enabled for the project and the email address or domain that you want to use to send and receive the message is configured. For more information, see [Enabling and disabling the email channel](pinpoint/latest/userguide/channels-email-setup.html) and [Verifying email identities](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-email-manage-verify.html) in the *Amazon Pinpoint User Guide*.
**Note**  
To complete the procedure in this section, you must verify and email address

1. On the **Environments** menu, choose the AWS Region that you want to send the message from.

   In this example, Postman has been configured so that the **Environments** menu shows the following four options:
   + US East (N. Virginia)
   + US West (Oregon)
   + Europe (Frankfurt)
   + Europe (Ireland)

1. In the **Messages** folder, choose the **SendMessages** operation.  
![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Postman_Tutorial_3.3_3.png)

1. 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.

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

   ```
   {
       "MessageConfiguration":{
           "EmailMessage":{
               "FromAddress":"sender@example.com",
               "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."
                   }
               }
           }
       },
       "Addresses":{
           "recipient@example.com": {
               "ChannelType": "EMAIL"
           }
       }
   }
   ```

1. In the preceding code, replace *sender@example.com* with your verified email address. Replace *recipient@example.com* with the verified email address that you want to send the message to.
**Note**  
If your account is still in the Amazon Pinpoint email sandbox, you can only send emails 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](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-email-setup-production-access.html) in the *Amazon Pinpoint User Guide*.

1. Choose **Send**. If the message is sent successfully, the response pane shows a status of `200 OK`.

   ```
   {
       "ApplicationId": "12345678901234567890123456789012",
       "RequestId": "<sampleValue>",
       "Result": {
           "recipient@example.com": {
               "DeliveryStatus": "SUCCESSFUL",
               "StatusCode": 200,
               "StatusMessage": "<sampleValue>",
               "MessageId": "<sampleValue>"
           }
       }
   }
   ```

# Set up an SMS registration system in Amazon Pinpoint
<a name="tutorials-two-way-sms"></a>

SMS messages (text messages) are a great way to send time-sensitive messages to your customers using Amazon Pinpoint. Many people keep their phones nearby at all times, and 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.

![\[\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_Architecture.png)


## About double opt-in
<a name="tutorials-two-way-sms-double-opt-in"></a>

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
<a name="tutorials-two-way-sms-about"></a>

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.

**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 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 Canada cost \$11.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 \$10.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 \$10.00645 per message. If you send messages to recipients in Canada, you pay between \$10.00109–\$10.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 \$10.0075 per incoming message. If your number is based in Canada, you pay \$10.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](https://aws.amazon.com/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 \$13.50–\$13.70, depending on which AWS Region you use Amazon Pinpoint in. For more information, see [API Gateway pricing](https://aws.amazon.com/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.

**Note**  
All prices shown in this list are in US Dollars (USD).

**Next**: [Prerequisites](tutorials-two-way-sms-prereqs.md)

# Prerequisites for setting up SMS in Amazon Pinpoint
<a name="tutorials-two-way-sms-prereqs"></a>

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/](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 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 must have a method of hosting and publishing 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](https://aws.amazon.com/getting-started/hands-on/host-static-website/).

**Next**: [Set Up Amazon Pinpoint](tutorials-two-way-sms-part-1.md)

# Set up SMS in Amazon Pinpoint
<a name="tutorials-two-way-sms-part-1"></a>

Before you can set up SMS messages, you need an Amazon Pinpoint project. In this section, you do the following:
+ Create an Amazon Pinpoint project
+ Enable the SMS channel and lease a phone number
+ Configure two-way SMS messaging

Before you begin, review the [prerequisites](tutorials-two-way-sms-prereqs.md).

## Create an Amazon Pinpoint project
<a name="tutorials-two-way-sms-part-1-create-project"></a>

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)
<a name="tutorials-two-way-sms-part-1-create-project-opt-1"></a>

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/](https://console.aws.amazon.com/pinpoint/).

1. 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.  
![\[The Region drop down showing US East (N. Virginia) selected.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Region_Selector.png)

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

1. On the **Configure features** page, choose **Skip this step**.

1. In the navigation pane, choose **All projects**.

1. On the **All projects** page, next to the project you just created, copy the value that's shown in the **Project ID** column.
**Tip**  
You 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)
<a name="tutorials-two-way-sms-part-1-create-project-opt-2"></a>

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/](https://console.aws.amazon.com/pinpoint/).

1. 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.  
![\[The region drop down showing US East (N. Virginia) selected.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/Region_Selector.png)

1. On the **All projects** page, choose **Create a project**.

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

1. On the **Configure features** page, choose **Skip this step**.

1. In the navigation pane, choose **All projects**.

1. On the **All projects** page, next to the project you just created, copy the value that's shown in the **Project ID** column.
**Tip**  
You 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.

## Obtain a dedicated phone number
<a name="tutorials-two-way-sms-part-1-set-up-channel"></a>

**Note**  
Amazon Pinpoint has updated their user guide documentation. To get the latest information regarding how to create, configure, and manage your SMS and voice resources, see the new [AWS End User Messaging SMS user guide](https://docs.aws.amazon.com/sms-voice/latest/userguide/what-is-service.html). 

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 phone number to use when sending SMS messages.

**Note**  
This section assumes that you're leasing a United States 10DLC phone number after brand and campaign registration, United States Toll-Free number, or Canada long code. 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 [Supported countries and regions (SMS channel)](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-sms-by-country.html) in the *AWS End User Messaging SMS User Guide*.

To enable the SMS channel using the Amazon Pinpoint console, follow these steps:

**Enable SMS channel**

1. Sign in to the AWS Management Console and open the Amazon Pinpoint console at [https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/).

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

1. Next to **SMS settings**, choose **Edit**.

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

To request a phone number using the AWS End User Messaging SMS console, follow these steps:

**Request a phone number (Console)**

1. Open the AWS End User Messaging SMS console at [https://console.aws.amazon.com/sms-voice/](https://console.aws.amazon.com/sms-voice/).
**Note**  
Make sure you request a phone number in the same AWS Region that you created your Amazon Pinpoint project in.

1. In the navigation pane, under **Configurations**, choose **Phone numbers** and then **Request originator**.

1. On the **Select country** page for **Message destination country** choose either the United States or Canada. Choose **Next**.

1. On the **Messaging use case** section, enter the following:
   + Under **Number capabilities** choose **SMS**
**Important**  
Capabilities for SMS and Voice can't be changed once the phone number has been purchased.
   + For **Two-way messaging** choose **Yes**.

1. Choose **Next**.

1. Under **Select originator type** choose either **Long code** or **10DLC**.

   If you choose 10DLC and already have a registered campaign you can choose the campaign from the **Associate to registered campaign**.

1. Choose **Next**.

1. On **Review and request** you can verify and edit your request before submitting it. Choose **Request**.

1. A **Registration Required** window may appear depending on the type of phone number you requested. Your phone number is associated with this registration and you can't send messages until your registration has been approved. For more information about registrations requirements see [Registrations](https://docs.aws.amazon.com/sms-voice/latest/userguide/registrations.html).

   1. For **Registration form name** enter a friendly name.

   1. Choose **Begin registration** to finish registering the phone number or **Register later**.
**Important**  
Your phone number can't send messages until your registration has been approved.  
 You are still billed the recurring monthly lease fee for the phone number regardless of registration status. For more information about registrations requirements see [Registrations](https://docs.aws.amazon.com/sms-voice/latest/userguide/registrations.html).

## Enable two-way SMS
<a name="tutorials-two-way-sms-part-1-enable-two-way"></a>

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.

To enable two-way SMS using the AWS End User Messaging SMS console, follow these steps:

**Enable two-way SMS**

1. Open the AWS End User Messaging SMS console at [https://console.aws.amazon.com/sms-voice/](https://console.aws.amazon.com/sms-voice/).

1. In the navigation pane, under **Configurations**, choose **Phone numbers**.

1. On the **Phone numbers** page choose a phone number.

1. On the **Two-way SMS** tab choose the **Edit settings** button.

1. On the **Edit settings** page choose **Enable two-way message**.

1. For **Destination type** choose **Amazon SNS**.
   + **New Amazon SNS topic** – AWS End User Messaging SMS creates a topic in your account. The topic is automatically created with all of the required permissions. For more information on Amazon SNS topics see [Configuring Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-configuring.html) in the *Amazon SNS developer guide*. 
   + For **incoming message destination** enter a topic name, such as **SMSRegistrationFormTopic**.

1. For **Two-way channel role** choose **Use SNS topic policies**.

1. Choose **Save changes**.

Use the AWS End User Messaging SMS console to add keywords to your phone number that customers send you to confirm their subscriptions (such as **Yes** or **Confirm**).

**Add a keyword**

1. Open the AWS End User Messaging SMS console at [https://console.aws.amazon.com/sms-voice/](https://console.aws.amazon.com/sms-voice/).

1. In the navigation pane, under **Configurations**, choose **Phone number**.

1. On the **Phone number** page choose the phone number to add a keyword to.

1. On the **Keywords** tab choose the **Add keyword** button.

1. In the **Custom Keyword** pane add the following:
   + **Keyword** – The new keyword to add (such as **Yes** or **Confirm**).
   + **Response message** – The message to send back to the recipient.
   + **Keyword action** – The action to perform when the keyword is received. Choose **Automatic response**.

1. Choose **Add keyword**.

**Next**: [Create IAM policies and roles](tutorials-two-way-sms-part-2.md)

# Create IAM policies and roles for use with SMS in Amazon Pinpoint
<a name="tutorials-two-way-sms-part-2"></a>

The next step in implementing the SMS registration solution in Amazon Pinpoint 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.

## Create an IAM policy
<a name="tutorials-two-way-sms-part-2-create-policy"></a>

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/](https://console.aws.amazon.com/iam/).

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

1. On the **JSON** tab, paste the following code.

------
#### [ JSON ]

****  

   ```
   {
       "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:us-east-1:111122223333:apps/projectId/*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "mobiletargeting:GetEndpoint",
                   "mobiletargeting:UpdateEndpoint",
                   "mobiletargeting:PutEvents"
               ],
               "Resource": "arn:aws:mobiletargeting:us-east-1:111122223333:apps/projectId/endpoints/*"
           },
           {
               "Effect": "Allow",
               "Action": "mobiletargeting:PhoneNumberValidate",
               "Resource": "arn:aws:mobiletargeting:us-east-1:111122223333: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`.
**Tip**  
For a complete list of AWS Regions where Amazon Pinpoint is available, see [AWS regions and endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#pinpoint_region) 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 [Create an Amazon Pinpoint project](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project) of this tutorial.
**Note**  
The `logs` actions enable Lambda to log its output in CloudWatch Logs.

1. Choose **Next**.

1. For **Policy name**, enter a name for the policy, such as **RegistrationFormPolicy**. Choose **Create policy**.

## Create an IAM role
<a name="tutorials-two-way-sms-part-2-create-role"></a>

**To create the role**

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

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

1. Under **Trusted entity type**, choose **AWS service**, and then for **Service or user case** choose **Lambda** from the drop down list.

1. Choose **Next**.

1. Under **Permissions policies**, choose or search for the policy that you created in the previous section, and then choose **Next**.

1. Under **Role details**, for **Role name**, enter a name for the role, such as **SMSRegistrationForm**. Choose **Create role**.

**Next**: [Create Lambda functions](tutorials-two-way-sms-part-3.md)

# Create Lambda functions for use with Amazon Pinpoint SMS messaging
<a name="tutorials-two-way-sms-part-3"></a>

This section shows you how to create and configure two Lambda functions for use with Amazon Pinpoint SMS messaging. Later, you set up API Gateway and Amazon Pinpoint to invoke these functions when certain 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.

## Create the function that validates customer information and creates endpoints
<a name="tutorials-two-way-sms-part-3-create-register-function"></a>

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](https://docs.aws.amazon.com/pinpoint/latest/developerguide/validate-phone-numbers.html) 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/](https://console.aws.amazon.com/lambda/).

1. Choose **Create function**.

1. Under **Create a function**, choose **Use a blueprint**.

1. 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.   
![\[The Create function page showing Use a blueprint selected.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step1.5.png)

1. Under **Basic information**, do the following:
   + For **Name**, enter a name for the function, such as **RegistrationForm**.
   + For **Role**, select **Choose an existing role**.
   + For **Existing role**, choose the **SMSRegistrationForm** role that you created in [Create an IAM role](tutorials-two-way-sms-part-2.md#tutorials-two-way-sms-part-2-create-role).

   When you finish, choose **Create function**.

1. For **Code source** delete the sample function in the code editor, and then paste the following code:

   ```
   import { PinpointClient, PhoneNumberValidateCommand, UpdateEndpointCommand, SendMessagesCommand } from "@aws-sdk/client-pinpoint"; // ES Modules import
   const pinClient = new PinpointClient({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";
   
   export const handler = async (event, context) => {
     console.log('Received event:', event);
     await validateNumber(event);
   };
   
   async function validateNumber (event) {
     var destinationNumber = event.destinationNumber;
     if (destinationNumber.length == 10) {
       destinationNumber = "+1" + destinationNumber;
     }
     var params = {
       NumberValidateRequest: {
         IsoCountryCode: 'US',
         PhoneNumber: destinationNumber
       }
     };
     try{
       const PhoneNumberValidateresponse = await pinClient.send( new  PhoneNumberValidateCommand(params));
       console.log(PhoneNumberValidateresponse);
        if (PhoneNumberValidateresponse['NumberValidateResponse']['PhoneTypeCode'] == 0) {
           await createEndpoint(PhoneNumberValidateresponse, event.firstName, event.lastName, event.source);
           
         } else {
           console.log("Received a phone number that isn't capable of receiving "
                      +"SMS messages. No endpoint created.");
         }
     }catch(err){
       console.log(err);
     }
   }
   
   async function createEndpoint(data, firstName, lastName, source) {
     var destinationNumber = data['NumberValidateResponse']['CleansedPhoneNumberE164'];
     var endpointId = data['NumberValidateResponse']['CleansedPhoneNumberE164'].substring(1);
     
     var params = {
       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
             ]
           }
         }
       }
     };
     try{
       const UpdateEndpointresponse = await pinClient.send(new UpdateEndpointCommand(params));
       console.log(UpdateEndpointresponse);
       await sendConfirmation(destinationNumber);
     }catch(err){
       console.log(err);
     }  
   }
   
   async function sendConfirmation(destinationNumber) {
     var params = {
       ApplicationId: projectId,
       MessageRequest: {
         Addresses: {
           [destinationNumber]: {
             ChannelType: 'SMS'
           }
         },
         MessageConfiguration: {
           SMSMessage: {
             Body: message,
             MessageType: messageType,
             OriginationNumber: originationNumber
           }
         }
       }
     };
     try{
       const SendMessagesCommandresponse = await pinClient.send(new SendMessagesCommand(params));
       console.log("Message sent! " 
             + SendMessagesCommandresponse['MessageResponse']['Result'][destinationNumber]['StatusMessage']);
     }catch(err){
       console.log(err);
     }
   }
   ```

1. On the **Configuration** tab for **Environment variables**, choose **Edit** and then **Add environment variable**, 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](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel).
**Note**  
Be sure to include the plus sign (\$1) 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](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project).
   + 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.  
![\[The Environment Variables for originationNumber, projectId, and region.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step1.7.png)

1. At the top of the page, choose **Save**.

### Test the function
<a name="tutorials-two-way-sms-part-3-create-register-function-test"></a>

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 the **Test** tab.

1. Choose **Create new event**, do the following:
   + 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": "+12065550142",
       "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**.

1. Choose **Test**.

1. 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.

1. Open the Amazon Pinpoint console at [https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/).

1. On the **All projects** page, choose the project that you created in [Create an Amazon Pinpoint project](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project).

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

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

1. 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.  
![\[The segment group showing zero endpoints.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step8.9.png)

## Create the function that opts in customers to your communications
<a name="tutorials-two-way-sms-part-3-create-optin-function"></a>

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 [Enable two-way SMS](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel), 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 [Enable two-way SMS](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel).

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/](https://console.aws.amazon.com/lambda/).

1. Choose **Create function**.

1. Under **Create function**, choose **Blueprints**.

1. 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**.

1. Under **Basic information**, do the following:
   + For **Name**, enter a name for the function, such as **RegistrationForm\$1OptIn**.
   + For **Role**, select **Choose an existing role**.
   + For **Existing role**, choose the SMSRegistrationForm role that you created in [Create an IAM role](tutorials-two-way-sms-part-2.md#tutorials-two-way-sms-part-2-create-role).

   When you finish, choose **Create function**.

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

   ```
   import { PinpointClient, UpdateEndpointCommand } from "@aws-sdk/client-pinpoint"; // ES Modules import
   
   // Create a new Pinpoint client instance with the region specified in the environment variables
   const pinClient = new PinpointClient({ region: process.env.region });
   
   // Get the Pinpoint project ID and the confirm keyword from environment variables
   const projectId = process.env.projectId;
   const confirmKeyword = process.env.confirmKeyword.toLowerCase();
   
   // This is the main handler function that is invoked when the Lambda function is triggered
   export const handler = async (event, context) => {
       console.log('Received event:', event);
   
       try {
           // Extract the timestamp, message, and origination number from the SNS event
           const timestamp = event.Records[0].Sns.Timestamp;
           const message = JSON.parse(event.Records[0].Sns.Message);
           const originationNumber = message.originationNumber;
           const response = message.messageBody.toLowerCase();
   
           // Check if the response message contains the confirm keyword
           if (response.includes(confirmKeyword)) {
               // If the confirm keyword is found, update the endpoint's opt-in status
               await updateEndpointOptIn(originationNumber, timestamp);
           }
       }catch (error) {
           console.error('An error occurred:', error);
           throw error; // Rethrow the error to handle it upstream
       }
   };
   
   // This function updates the opt-in status of a Pinpoint endpoint
   async function updateEndpointOptIn(originationNumber, timestamp) {
       // Extract the endpoint ID from the origination number
       const endpointId = originationNumber.substring(1);
   
        // Prepare the parameters for the UpdateEndpointCommand
       const params = {
           ApplicationId: projectId,
           EndpointId: endpointId,
           EndpointRequest: {
               Address: originationNumber,
               ChannelType: 'SMS',
               OptOut: 'NONE',
               Attributes: {
                   OptInTimestamp: [timestamp]
               },
           }
       };
   
       try {
           // Send the UpdateEndpointCommand to update the endpoint's opt-in status
           const updateEndpointResponse = await pinClient.send(new UpdateEndpointCommand(params));
           console.log(updateEndpointResponse);
           console.log(`Successfully changed the opt status of endpoint ID ${endpointId}`);
       } catch (error) {
           console.error('An error occurred while updating endpoint:', error);
           throw error; // Rethrow the error to handle it upstream
       }
   }
   ```

1. Under **Environment variables**, do the following:
   + In the first row, create a variable with a key of **projectId**. Next, set the value to the unique ID of the project that you created in [Create an Amazon Pinpoint project](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project).
   + In the second 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**.
   + In the third row, create a variable with a key of **confirmKeyword**. Next, set the value to the confirmation keyword that you created in [Enable two-way SMS](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel).
**Note**  
The keyword isn't case sensitive. This function converts the incoming message to lowercase letters.

   When you finish, the **Environment Variables** section should resemble the example shown in the following image.  
![\[The Environment Variables for projectId, region, and confirmKeyword.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step2.7.png)

1. At the top of the page, choose **Save**.

### Test the function
<a name="tutorials-two-way-sms-part-3-create-optin-function-test"></a>

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**.

1. On the **Configure test event** window, do the following:

   1. Choose **Create new test event**.

   1. For **Event name**, enter a name for the test event, such as **MyResponse**.

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

      ```
      {
        "Records":[
          {
            "Sns":{
              "Message":"{\"originationNumber\":\"+12065550142\",\"messageBody\":\"Yes\"}",
              "Timestamp":"2019-02-20T17:47:44.147Z"
            }
          }
        ]
      }
      ```

      In the preceding code example, replace the values of the `originationNumber` attribute with the phone number that you used when you tested the previous Lambda function. Replace the value of `messageBody` with the two-way SMS keyword that you specified in [Enable two-way SMS](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-enable-two-way). Optionally, you can replace the value of `Timestamp` with the current date and time.

   1. Choose **Create**.

1. Choose **Test** again.

1. 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.

1. Open the Amazon Pinpoint console at [https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/).

1. On the **All projects** page, choose the project that you created in [Create an Amazon Pinpoint project](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project).

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

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

1. 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 is one eligible endpoint, and one total endpoint.

**Next**: [Set up Amazon API Gateway](tutorials-two-way-sms-part-4.md)

# Set up Amazon API Gateway for SMS messaging in Amazon Pinpoint
<a name="tutorials-two-way-sms-part-4"></a>

In this section, you create a new API by using Amazon API Gateway as part of the SMS registration for Amazon Pinpoint. The registration form that you deploy in this solution calls this API. API Gateway then passes the information that's captured on the registration form to the Lambda function you created in [Create Lambda functions](tutorials-two-way-sms-part-3.md).

## Create the API
<a name="tutorials-two-way-sms-part-4-create-api"></a>

First, you have to create a new API in API Gateway. The following procedures show you how to create a new REST API.

**To create a new API**

1. Open the API Gateway console at [https://console.aws.amazon.com/apigateway/](https://console.aws.amazon.com/apigateway/). 

1. Choose **Create API**. Make the following selections:
   + Under **Choose the protocol**, choose **REST**.
   + Under **Create new API**, choose **New API**.
   + Under **Settings**, for **Name**, enter a name, such as **RegistrationForm**. For **Description**, optionally enter some text that describes the purpose of the API. For **Endpoint Type**, choose **Regional**. Then, choose **Create API**.

   An example of these settings is shown in the following image.  
![\[Protocol set to REST, Create new API set to New API, API name set to RegistrationForm, and Endpoint Type set to Regional.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step2.png)

## Create a resource
<a name="tutorials-two-way-sms-part-4-create-resource"></a>

Now that you've created an API, you can start to add resources to it. After that, you add a POST method to the resource, and tell API Gateway to pass the data that you receive from this method to your Lambda function.

1. On the **Actions** menu, choose **Create Resource**. In the **New Child Resource** pane, for **Resource Name**, enter **register**, as shown in the following image. Choose **Create Resource**.  
![\[The new child resource pane with resource name set to register.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step3.png)

1. On the **Actions** menu, choose **Create Method**. From the menu that appears, choose **POST**, as shown in the following image. Then choose the **check mark** button.  
![\[The create method pane with check mark selected.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step4.png)

1. In the **/register - POST - Setup** pane, make the following selections:
   + For **Integration type**, choose **Lambda Function**.
   + Choose **Use Lambda Proxy Integration**.
   + For **Lambda Region**, choose the Region that you created the Lambda function in.
   + For **Lambda Function**, choose the RegisterEndpoint function that you created in [Create Lambda functions](tutorials-two-way-sms-part-3.md).

   An example of these settings is shown in the following image.  
![\[The /register - POST - Setup pane with Lambda Function selected.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step5.png)

   Choose **Save**. On the window that appears, choose **OK** to give API Gateway permission to execute your Lambda function.

## Deploy the API
<a name="tutorials-two-way-sms-part-4-deploy-api"></a>

The API is now ready to use. At this point, you have to deploy it in order to create a publicly accessible endpoint.

1. On the **Actions** menu, choose **Deploy API**. On the **Deploy API** window, make the following selections:
   + For **Deployment stage**, choose **[New Stage]**.
   + For **Stage name**, enter **v1**.
   + Choose **Deploy**.

   An example of these selections is shown in the following image.  
![\[The deploy API windows with Stage name set to v1\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step6.png)

1. In the **v1 Stage Editor** pane, choose the **/register** resource, and then choose the **POST** method. Copy the address that's shown next to **Invoke URL**, as shown in the following image.  
![\[The v1 Stage Editor pane showing the Invoke URL to copy\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step7.png)

1. In the navigation pane, choose **Resources**. In the list of resources, choose the **/register** resource. Finally, on the **Actions** menu, choose **Enable CORS**, as shown in the following image.  
![\[The drop down menu for Actions, shows Enable CORS is selected\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_APIGW_Step8.png)

1. On the **Enable CORS** pane, choose **Enable CORS and replace existing CORS headers**.

**Next**: [Create and deploy the web form](tutorials-two-way-sms-part-5.md)

# Create and deploy the web form to use SMS messaging for Amazon Pinpoint
<a name="tutorials-two-way-sms-part-5"></a>

All of the components that use AWS services for SMS messaging using Amazon Pinpoint are now in place. The last step is to create and deploy the web form that captures customer's data.

## Create the JavaScript form handler
<a name="tutorials-two-way-sms-part-5-create-form-handler"></a>

In this section, you create a JavaScript function that parses the content of the web form that you create in the next section. After parsing the content, this function sends the data to the API that you created in [Set up Amazon API Gateway](tutorials-two-way-sms-part-4.md).

**To create the form handler**

1. In a text editor, create a new file.

1. In the editor, paste the following code.

   ```
   $(document).ready(function() {
   
     // Handle form submission.
     $("#submit").click(function(e) {
   
       var firstName = $("#firstName").val(),
           lastName = $("#lastName").val(),
           source = window.location.pathname,
           optTimestamp = undefined,
           utcSeconds = Date.now() / 1000,
           timestamp = new Date(0),
           phone = $("#areaCode").val()
                 + $("#phone1").val()
                 + $("#phone2").val();
   
       e.preventDefault();
   
       if (firstName == "") {
         $('#form-response').html('<div class="mt-3 alert alert-info" role="alert">Please enter your first name.</div>');
       } else if (lastName == "") {
         $('#form-response').html('<div class="mt-3 alert alert-info" role="alert">Please enter your last name.</div>');
       } else if (phone.match(/[^0-9]/gi)) {
         $('#form-response').html('<div class="mt-3 alert alert-info" role="alert">Your phone number contains invalid characters. Please check the phone number that you supplied.</div>');
       } else if (phone.length < 10) {
         $('#form-response').html('<div class="mt-3 alert alert-info" role="alert">Please enter your phone number.</div>');
       } else if (phone.length > 10) {
         $('#form-response').html('<div class="mt-3 alert alert-info" role="alert">Your phone number contains too many digits. Please check the phone number that you supplied.</div>');
       } else {
         $('#submit').prop('disabled', true);
         $('#submit').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>  Saving your preferences</button>');
   
         timestamp.setUTCSeconds(utcSeconds);
   
         var data = JSON.stringify({
           'destinationNumber': phone,
           'firstName': firstName,
           'lastName': lastName,
           'source': source,
           'optTimestamp': timestamp.toString()
         });
   
         $.ajax({
           type: 'POST',
           url: 'https://example.execute-api.us-east-1.amazonaws.com/v1/register',
           contentType: 'application/json',
           data: data,
           success: function(res) {
             $('#form-response').html('<div class="mt-3 alert alert-success" role="alert"><p>Congratulations! You&apos;ve successfully registered for SMS Alerts from ExampleCorp.</p><p>We just sent you a message. Follow the instructions in the message to confirm your subscription. We won&apos;t send any additional messages until we receive your confirmation.</p><p>If you decide you don&apos;t want to receive any additional messages from us, just reply to one of our messages with the keyword STOP.</p></div>');
             $('#submit').prop('hidden', true);
             $('#unsubAll').prop('hidden', true);
             $('#submit').text('Preferences saved!');
           },
           error: function(jqxhr, status, exception) {
             $('#form-response').html('<div class="mt-3 alert alert-danger" role="alert">An error occurred. Please try again later.</div>');
             $('#submit').text('Save preferences');
             $('#submit').prop('disabled', false);
           }
         });
       }
     });
   });
   ```

1. In the preceding example, replace *https://example.execute-api.us-east-1.amazonaws.com/v1/register* with the Invoke URL that you obtained in [Deploy the API](tutorials-two-way-sms-part-4.md#tutorials-two-way-sms-part-4-deploy-api).

1. Save the file.

## Create the form file
<a name="tutorials-two-way-sms-part-5-create-form"></a>

In this section, you create an HTML file that contains the form that customers use to register for your SMS program. This file uses the JavaScript form handler that you created in the previous section to transmit the form data to your Lambda function.

**Important**  
When a user submits this form, it triggers a Lambda function that calls several Amazon Pinpoint API operations. Malicious users could launch an attack on your form that could cause a large number of requests to be made. If you plan to use this solution for a production use case, you should secure it by using a system such as [Google reCAPTCHA](https://www.google.com/recaptcha/about/).

**To create the form**

1. In a text editor, create a new file.

1. In the editor, paste the following code.

   ```
   <!doctype html>
   <html lang="en">
   
   <head>
     <!-- Meta tags required by Bootstrap -->
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
     <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   
     <script type="text/javascript" src="SMSFormHandler.js"></script>
     <title>SMS Registration Form</title>
   </head>
   
   <body>
     <div class="container">
       <div class="row justify-content-center mt-3">
         <div class="col-md-6">
           <h1>Register for SMS Alerts</h1>
           <p>Enter your phone number below to sign up for PromotionName messages from ExampleCorp.</p>
           <p>We don't share your contact information with anyone else. For more information, see our <a href="http://example.com/privacy">Privacy Policy</a>.</p>
           <p>ExampleCorp alerts are only available to recipients in the United States.</p>
         </div>
       </div>
       <div class="row justify-content-center">
         <div class="col-md-6">
           <form>
             <div class="form-group">
               <label for="firstName" class="font-weight-bold">First name</label>
               <input type="text" class="form-control" id="firstName" placeholder="Your first name" required>
             </div>
             <div class="form-group">
               <label for="lastName" class="font-weight-bold">Last name</label>
               <input type="text" class="form-control" id="lastName" placeholder="Your last name" required>
             </div>
             <label for="areaCode" class="font-weight-bold">Phone number</label>
             <div class="input-group">
               <span class="h3">(&nbsp;</span>
               <input type="tel" class="form-control" id="areaCode" placeholder="Area code" required>
               <span class="h3">&nbsp;)&nbsp;</span>
               <input type="tel" class="form-control" id="phone1" placeholder="555" required>
               <span class="h3">&nbsp;-&nbsp;</span>
               <input type="tel" class="form-control" id="phone2" placeholder="0199" required>
             </div>
             <div id="form-response"></div>
             <button id="submit" type="submit" class="btn btn-primary btn-block mt-3">Submit</button>
           </form>
         </div>
       </div>
       <div class="row mt-3">
         <div class="col-md-12 text-center">
           <small class="text-muted">Copyright © 2019, ExampleCorp or its affiliates.</small>
         </div>
       </div>
     </div>
   </body>
   
   </html>
   ```

1. In the preceding example, replace *SMSFormHandler.js* with the full path to the form handler JavaScript file that you created in the previous section.

1. Save the file.

## Upload the form files
<a name="tutorials-two-way-sms-part-5-upload-form"></a>

Now that you've created the HTML form and the JavaScript form handler, the last step is to publish these files to the internet. This section assumes that you have an existing web hosting provider. If you don't have an existing hosting provider, you can launch a website by using Amazon Route 53, Amazon Simple Storage Service (Amazon S3), and Amazon CloudFront. For more information, see [Host a static website](https://aws.amazon.com/getting-started/hands-on/host-static-website/).

If you use another web hosting provider, consult the provider's documentation for more information about publishing webpages.

## Test the form
<a name="tutorials-two-way-sms-part-5-test-form"></a>

After you publish the form, you should submit some test events to make sure that it works as expected.

**To test the registration form**

1. In a web browser, go to the location where you uploaded the registration form. If you used the code example from [Create the JavaScript form handler](#tutorials-two-way-sms-part-5-create-form), you see a form that resembles the example in the following image.  
![\[The customer request form created in step 5.1.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_Form_Step5.3.1.png)

1. Enter your contact information in the **First name**, **Last name**, and **Phone number** fields.
**Note**  
When you submit the form, Amazon Pinpoint attempts to send a message to the phone number that you specified. Because of this functionality, you should use a real phone number to test the solution from beginning to end.  
If you tested the Lambda function in [Create Lambda functions](tutorials-two-way-sms-part-3.md), your Amazon Pinpoint project already contains at least one endpoint. When you test this form, you should either submit a different phone number on the form, or delete the existing endpoint by using the [DeleteEndpoint](https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-endpoints-endpoint-id.html#DeleteEndpoint) API operation.

1. Check the device that's associated with the phone number that you specified to make sure that it received the message.

1. Open the Amazon Pinpoint console at [https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/).

1. On the **All projects** page, choose the project that you created in [Create an Amazon Pinpoint project](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project).

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

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

1. For **Choose a user attribute**, choose **FirstName**. Then, for **Choose values**, choose the first name that you specified when you submitted the form.

   The **Segment estimate** section should show that there are zero eligible endpoints, and one endpoint (under Total endpoints), as shown in the following example. This result is expected. When the Lambda function creates a new endpoint, the endpoint is opted out by default.  
![\[A segment with zero opted in endpoints.\]](http://docs.aws.amazon.com/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step8.9.png)

1. On the device that received the message, reply to the message with the two-way SMS keyword that you specified in [Enable two-way SMS](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-enable-two-way). Amazon Pinpoint sends a response message immediately.

1. In the Amazon Pinpoint console, repeat steps 4 through 8. This time, when you create the segment, you see one eligible endpoint, and one total endpoint. This result is expected, because the endpoint is now opted in.

# Next steps
<a name="tutorials-two-way-sms-next-steps"></a>

By completing this tutorial, you've done the following:
+ Created an Amazon Pinpoint project, configured the SMS channel, and obtained a dedicated long code.
+ Created a IAM policy that uses the principal of least privilege to grant access rights, and associated that policy with a role.
+ Created two Lambda functions that use the PhoneNumberValidate, UpdateEndpoint, and SendMessages operations in the Amazon Pinpoint API.
+ Created a REST API using API Gateway.
+ Created and deployed a web-based form that collects customers' contact information.
+ Performed tests on the solution to make sure it works.

This section discusses a few ways that you can use the customer information that you collect by using this solution. It also includes some suggestions of ways that you can customize this solution to fit your unique use case.

## Create customer segments
<a name="tutorials-two-way-sms-next-steps-create-segments"></a>

All of the customer details that you collect through this form are stored as endpoints. This solution creates endpoints that contain several attributes that you can use for segmentation purposes.

For example, this solution captures an endpoint attribute called `Source`. This attribute contains the full path to the location where the form was hosted. When you create a segment, you can filter the segment by endpoint, and then further refine the filter by choosing a `Source` attribute.

Creating segments based on the `Source` attribute can be useful in several ways. First, it allows you to quickly create a segment of customers who signed up to receive SMS messages from you. Additionally, the segmentation tool in Amazon Pinpoint automatically excludes endpoints that aren't opted in to receive messages.

The `Source` attribute is also useful if you decide to host the registration form in several different locations. For example, your marketing material could refer to a form that's hosted in one location, while customers who encounter the form while browsing your website could see a version that's hosted somewhere else. When you do this, the Source attributes for customers who complete the form after seeing your marketing materials are different from those who complete the form after finding it on your website. You can use this difference to create distinct segments, and then send tailored communications to each of those audiences.

## Send personalized campaign messages
<a name="tutorials-two-way-sms-next-steps-send-campaigns"></a>

After you create segments, you can start sending campaigns to those segments. When you create campaign messages, you can personalize them by specifying which endpoint attributes you want to include in the message. For example, the web form used in this solution requires the customer to enter their first and last names. These values are stored in the user record that's associated with the endpoint.

For example, if you use the `GetEndpoint` API operation to retrieve information about an endpoint that was created using this solution, you see a section that resembles the following example:

```
  ...
  "User": {
    "UserAttributes": {
      "FirstName": [
        "Carlos"
      ],
      "LastName": [
        "Salazar"
      ]
    }
  }
  ...
```

If you want to include the values of these attributes in your campaign message, you can use dot notation to refer to the attribute. Then enclose the entire reference in double curly braces. For example, to include each recipient's first name in a campaign message, include the following string in the message: `{{User.UserAttributes.FirstName}}`. When Amazon Pinpoint sends the message, it replaces the string with the value of the `FirstName` attribute.

## Use the form to collect additional information
<a name="tutorials-two-way-sms-next-steps-collect-additional"></a>

You can modify this solution to collect additional information on the registration form. For example, you could ask the customer to provide their address, and then use the address data to populate the `Location.City`, `Location.Country`, `Location.Region`, and `Location.PostalCode` fields in the `Endpoint` resource. Collecting address information on the registration form might result in the endpoint containing more accurate information. To make this change, you need to add the appropriate fields to the web form. You also have to modify the JavaScript code for the form to pass the new values. Finally, you have to modify the Lambda function that creates the endpoint to handle the new incoming information.

You can also modify the form so that it collects contact information in other channels. For example, you could use the form to collect the customer's email address in addition to their phone number. To make this change, you need to modify the HTML and JavaScript for the web form. You also have to modify the Lambda function that creates the endpoint so that it creates two separate endpoints (one for the email endpoint, and one for the SMS endpoint). You should also modify the Lambda function so that it generates a unique value for the `User.UserId` attribute, and then associates that value with both endpoints.

## Record additional attributes for auditing purposes
<a name="tutorials-two-way-sms-next-steps-auditing"></a>

This solution records two valuable attributes when it creates and updates endpoints. First, when the first Lambda function initially creates the endpoint, it records the URL of the form itself in the `Attributes.Source` attribute. If the customer responds to the message, the second Lambda function creates an `Attributes.OptInTimestamp` attribute. This attribute contains the exact date and time when the customer provided their consent to receive messages from you.

Both of these fields can be useful if you're ever asked by a mobile carrier or regulatory agency to provide evidence of a customer's consent. You can retrieve this information at any time by using the [GetEndpoint](https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-endpoints-endpoint-id.html#GetEndpoint) API operation.

You can also modify the Lambda functions to record additional data that might be useful for auditing purposes, such as the IP address that the registration request was submitted from.