AWS Pinpoint with Lambda Function
Published: 2023-03-07 08:55:01

AWS Pinpoint is a cloud-based marketing automation service offered by Amazon Web Services (AWS). It enables businesses to engage with their customers across multiple channels including email, SMS, push notifications, and voice messages. With Pinpoint, businesses can create targeted campaigns, track user engagement, and analyze campaign performance.

Overall, AWS Pinpoint is a powerful marketing automation tool that can help businesses to engage with their customers effectively and drive business growth.

Pinpoint offers various features such as:

- **Audience segmentation:** Pinpoint enables businesses to segment their audience based on various criteria such as demographics, location, behavior, and user attributes. This helps businesses to create targeted campaigns that are personalized and relevant to their audience.
- **Multi-channel messaging:** Pinpoint supports multiple messaging channels such as email, SMS, push notifications, and voice messages. This allows businesses to reach their customers on their preferred channels.
- **Campaign management:** Pinpoint provides a user-friendly interface for creating, scheduling, and managing campaigns. It also offers A/B testing and analytics to help businesses optimize their campaigns.
- **Analytics and reporting:** Pinpoint provides detailed analytics and reporting on campaign performance, user engagement, and customer behavior. This helps businesses to understand their customers better and make data-driven decisions.
- **Integrations:** Pinpoint integrates with other AWS services such as Amazon S3, Amazon Kinesis, and Amazon Redshift. It also supports third-party integrations with popular marketing automation tools such as Salesforce, Marketo, and Hubspot.

**Set Up Email**
Type an email address that you will use to send email. For example, you can use your personal email address, or your work email address. Click the Verify button and keep this page open

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6haz888nk6kakcaolyru.png)

1. Ensure you have one verified email addresses by following the process in the Configure Email section
2. Download the [sample csv](https://static.us-east-1.prod.workshops.aws/public/fced5058-639b-4d68-97c5-e07ce1c5141e/static/import_customers/console_upload_segment_csv.csv) file and open it in a text editor on your computer.
3. Add/edit users using the wildcard local parts notation you saw when you sent a test message.

Edit the Address column in the CSV file to reflect one of the email addresses you verified in the Configure Email section. Example: If you verified abdullah.qadoos@systemsltd.com

**Import a Segment**
To import a segment, you define the endpoints or user IDs that belong to your segment in a comma-separated values (CSV) or JSON file. Then you import the file into Amazon Pinpoint to create the segment.

1. Choose Create a segment 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odl5r51g86ef9rjjg4vi.png)

2. Choose Import a segment
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4d2s5pppqyhx6sz8z8o.png)

3. Choose Upload files from your computer and drop the CSV file you just saved in the last step into the Drop files here area, or click Choose files and browse to your CSV import file.

4. Provide a descriptive name for your segment. Click Create segment to complete the import.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7z6ogyp2t4p7ji2kw1en.png)

5. After a couple of seconds your segment will be imported. Click on the segment name to view its details.

6. To view the new endpoint created, you can either [export the segment](https://docs.aws.amazon.com/pinpoint/latest/userguide/segments-exporting.html) or navigate to the AWS CloudShell console  and wait till the environment is created. Replace the Amazon Pinpoint application id from the command below then paste it in the AWS CloudShell terminal and press Enter. This should return you a response containing all the information about this endpoint

```
aws pinpoint get-endpoint --application-id <place Pinpoint application_id here> --endpoint-id 111
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yolr73f7s80xyqfqlp46.png)

**Create & execute an AWS Lambda Function**
You can create or update an Amazon Pinpoint endpoint via the Amazon Pinpoint REST API, Amplify or one of the AWS SDKs. For this example you will use the AWS Python SDK Boto3 and AWS Lambda function to host and execute the code.

1. Create a new AWS Lambda Function
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8vphg1e3om53dyqyxsq.png)

2. Select Author from scratch, give a Function name, for runtime select Python 3.8 and click on Create function
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gv81srio4vztwwt30v3.png)

3. Code Source 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ar2k8akfcblckweph7rq.png)

```
import boto3

client = boto3.client('pinpoint')

def lambda_handler(event, context):

	application_id = event['application_id']
	first_name = event['first_name']
	email_address = event['email_address']
	endpoint_id = event['endpoint_id']
	user_id = event['user_id']  
	age = event['age']
	interests = event['interests']
	
	response = client.update_endpoint(
	ApplicationId=application_id,
	EndpointId= endpoint_id,
	EndpointRequest={
		'Address': email_address,
		'ChannelType': 'EMAIL',
		'Metrics': {
			'age': age
		},
		'OptOut': 'NONE',
		'User': {
			'UserAttributes': {
				'FirstName': [
					first_name,
				],
				'interests': [
					interests
				]
			},
			'UserId': user_id
		}
	}
	)
	
	return response

```
4. Now that the code is ready, you need to allow AWS Lambda Function to perform the update_endpoint operation to your Amazon Pinpoint Project. To do this, you will add an [IAM policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)  to the AWS Lambda Function role. Navigate to the tab Configuration > Permissions and click on the Role name link. This will take you to the Identity and Access Management (IAM) console and specifically on the Summary page of that role
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9b61y6rle4ms6476tj44.png)

5. In the Permissions tab select Add permissions and Create inline policy
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02dn33rfw7hiejjulima.png)

6. Navigate to the JSON tab and paste the JSON seen below. Replace the values for AWS-REGION with the AWS region that you have created the Amazon Pinpoint project and AWS-ACCOUNT-ID and select Review policy. To find your AWS-ACCOUNT-ID [visit this page](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html)

```
{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "UpdateEndpoint",
			"Effect": "Allow",
			"Action": [
				"mobiletargeting:UpdateEndpoint*"
			 ],
			"Resource": "arn:aws:mobiletargeting:AWS-REGION:AWS-ACCOUNT-ID:*"
		}
		]
}

```
7. Paste workshop_lambda_policy as the policy name and click Create policy. Once the new policy is created, you should be able to see it under the Permissions policies list in the IAM role summary page
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygyh9g1pk9hmps2p5lfb.png)

8. Return to the AWS Lambda function Code tab select the dropwdown next to the orange Test button and choose Configure test event. Using this AWS Lambda feature you can create a dummy payload to test your Lambda function. Copy the JSON below and paste it under Event JSON section. Select hello-world as Event template and type test as Event name

- Replace the --- for application_id with your Amazon Pinpoint project id, which you can find by navigating to the Amazon Pinpoint console under the column Project ID
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/szpdeiqtwkm7hxwvyjnc.png)

- Replace the --- for email_address with the verfied email address from the lab Configure email channel. If you verified abdullah.qadoos@systemsltd.com

- Scroll down and select Save

```
{
    "application_id" : "---",
    "first_name" : "Jake",
    "email_address" : "---",
    "endpoint_id" : "222",
    "user_id" : "userid2",
	"age": 35,
	"interests": "shirts"
}

```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujvr28gsoudaer5825gt.png)

9. Return to the AWS Lambda function Code tab and select Deploy, which is located next to the Test button.
To execute the code, click on the Test button. Once the code is executed it will return the response from Amazon Pinpoint, which will contain information about the update_endpoint request.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1svgw0hetemh50j2ohz.png)

10. To view the new endpoint created, navigate to the AWS CloudShell console  and wait till the environment is created. Replace the Amazon Pinpoint application-id in the command below, copy & paste it in the AWS CloudShell terminal and press Enter using your keyboard. This should return you a response containing all the information about this endpoint

```
aws pinpoint get-endpoint --application-id <place Pinpoint application_id here> --endpoint-id 222

```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6h59jyagudusnetje67t.png)