Skip to content

Commit df55763

Browse files
authored
Merge pull request aws-samples#1666 from smalhotraa/smalhotraa-pinpointsmssvls-pinpointvalidateandsendmsg
New serverless pattern - apigw-lambda-pinpoint
2 parents a67fff3 + 9977dd5 commit df55763

4 files changed

Lines changed: 287 additions & 0 deletions

File tree

apigw-lambda-pinpoint/README.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Pinpoint SMS using API Gateway and Lambda
2+
3+
This pattern shows an example how a phone number can be validated and how a SMS message can be send using Pinpoint APIs which via API Gateway and Lambda deployed using SAM.
4+
5+
As a pre-requisite, a Pinpoint Application has to be created and its SMS channel should be enabled. Subsequently, this stack can be deployed with pinpoint application id, destination phone number, message that has to be sent, origination number and message type. Please read more about the Pinpoint API calls utilised here:
6+
https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-messages.html#apps-application-id-messagespost
7+
8+
https://docs.aws.amazon.com/pinpoint/latest/apireference/phone-number-validate.html
9+
10+
Learn more about this pattern at Serverless Land Patterns: << Add the live URL here >>
11+
12+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
13+
14+
## Requirements
15+
16+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
17+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
18+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
19+
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
20+
21+
## Deployment Instructions
22+
23+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
24+
```
25+
git clone https://github.com/aws-samples/serverless-patterns
26+
```
27+
1. Change directory to the pattern directory:
28+
```
29+
cd serverless-patterns/apigw-lambda-pinpoint
30+
```
31+
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
32+
```
33+
sam deploy --guided
34+
```
35+
1. During the prompts:
36+
* Enter a stack name
37+
* Enter the desired AWS Region
38+
* Allow SAM CLI to create IAM roles with the required permissions.
39+
40+
Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.
41+
42+
1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.
43+
44+
## How it works
45+
46+
1. Depending on the country to which SMS messages has to be sent, an [origination number](https://docs.aws.amazon.com/pinpoint/latest/userguide/settings-sms-request-number.html) can be requested accordingly.
47+
48+
2. Next, the SMS message can be sent using the API Gateway deployed via stack.
49+
50+
3. The lambda function's code firstly verify the phone number by using the [phone number validate](https://docs.aws.amazon.com/pinpoint/latest/apireference/phone-number-validate.html) API call.
51+
52+
## Testing
53+
54+
1. You can make a request to API Gateway with the following payload:
55+
56+
```
57+
{
58+
"destination_number": "",
59+
"message": "",
60+
"pinpoint_app_id": "",
61+
"origination_number": "",
62+
"message_type": ""
63+
}
64+
```
65+
2. If the message is sent successfully, then you will receive the following response:
66+
67+
```
68+
Message sent! Message ID: <random message id>
69+
```
70+
71+
## Cleanup
72+
73+
1. Delete the stack
74+
```bash
75+
aws cloudformation delete-stack --stack-name STACK_NAME
76+
```
77+
1. Confirm the stack has been deleted
78+
```bash
79+
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
80+
```
81+
----
82+
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
83+
84+
SPDX-License-Identifier: MIT-0
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"title": "Pinpoint SMS via API Gateway and Lambda",
3+
"description": "Validate phone number and send SMS from Pinpoint via API Gateway and Lambda",
4+
"language": "Python",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This pattern shows an example how a phone number can be validated and how a SMS message can be send using Pinpoint APIs which via API Gateway and Lambda deployed using SAM."
11+
]
12+
},
13+
"gitHub": {
14+
"template": {
15+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-pinpoint",
16+
"templateURL": "serverless-patterns/apigw-lambda-pinpoint",
17+
"projectFolder": "apigw-lambda-pinpoint",
18+
"templateFile": "template.py"
19+
}
20+
},
21+
"resources": {
22+
"bullets": [
23+
{
24+
"text": "Send Messages Pinpoint",
25+
"link": "https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-messages.html#apps-application-id-messagespost"
26+
},
27+
{
28+
"text": "Phone number validate",
29+
"link": "https://docs.aws.amazon.com/pinpoint/latest/apireference/phone-number-validate.html"
30+
}
31+
]
32+
},
33+
"deploy": {
34+
"text": [
35+
"sam deploy"
36+
]
37+
},
38+
"testing": {
39+
"text": [
40+
"See the GitHub repo for detailed testing instructions."
41+
]
42+
},
43+
"cleanup": {
44+
"text": [
45+
"Delete the stack: <code>sam delete --stack-name STACK_NAME</code>."
46+
]
47+
},
48+
"authors": [
49+
{
50+
"name": "Sahil Malhotra",
51+
"image": "link-to-your-photo.jpg",
52+
"bio": "Serverless enthusiast",
53+
"linkedin": "https://www.linkedin.com/in/smalhotraa/",
54+
"twitter": "twitter-handle"
55+
}
56+
]
57+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import logging
2+
import boto3
3+
import json
4+
import os
5+
6+
# Initialize Pinpoint client
7+
pinpoint_client = boto3.client('pinpoint')
8+
9+
def lambda_handler(event, context):
10+
11+
print(event)
12+
event_body = json.loads(event['body'])
13+
14+
15+
app_id = event_body["pinpoint_app_id"]
16+
17+
destination_number = event_body["destination_number"]
18+
print(destination_number)
19+
20+
message = event_body["message"]
21+
print(message)
22+
23+
origination_number = event_body["origination_number"]
24+
print(origination_number)
25+
26+
message_type = event_body["message_type"]
27+
print(message_type)
28+
29+
30+
response = dict()
31+
try:
32+
response_number_validation = pinpoint_client.phone_number_validate(NumberValidateRequest={'PhoneNumber':destination_number})
33+
34+
if response_number_validation["NumberValidateResponse"]["PhoneType"] != "INVALID":
35+
36+
print("Sending SMS message.")
37+
38+
response_send_message = pinpoint_client.send_messages(
39+
ApplicationId=app_id,
40+
MessageRequest={
41+
'Addresses': {destination_number: {'ChannelType': 'SMS'}},
42+
'MessageConfiguration': {
43+
'SMSMessage': {
44+
'Body': message,
45+
'MessageType': message_type,
46+
'OriginationNumber': origination_number}}})
47+
48+
49+
message_id = response_send_message['MessageResponse']['Result'][destination_number]['MessageId']
50+
51+
if message_id:
52+
53+
print(f"Message sent! Message ID: {message_id}.")
54+
response = dict()
55+
response['statusCode'] = 200
56+
response['body'] = f"Message sent! Message ID: {message_id}."
57+
return response
58+
59+
else:
60+
61+
print(f"Unable to send message")
62+
response = dict()
63+
response['statusCode'] = 500
64+
response['body'] = response_send_message
65+
return response
66+
67+
68+
except Exception as e:
69+
70+
print("Couldn't send message!")
71+
response['statusCode'] = 500
72+
response['body'] = "Couldn't send message!\n" + str(e)
73+
return response
74+
75+
76+
77+
78+
79+
80+
81+
82+
83+
84+
85+
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: AWS::Serverless-2016-10-31
3+
Resources:
4+
Api:
5+
Type: AWS::Serverless::Api
6+
Properties:
7+
Name: !Sub
8+
- ${ResourceName} From Stack ${AWS::StackName}
9+
- ResourceName: PinpointSMSApigw
10+
StageName: Prod
11+
DefinitionBody:
12+
openapi: '3.0'
13+
info: {}
14+
paths:
15+
/send_message:
16+
post:
17+
x-amazon-apigateway-integration:
18+
httpMethod: POST
19+
type: aws_proxy
20+
uri: !Sub arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PinpointFunction.Arn}/invocations
21+
responses: {}
22+
EndpointConfiguration: REGIONAL
23+
TracingEnabled: true
24+
PinpointFunction:
25+
Type: AWS::Serverless::Function
26+
Properties:
27+
Description: !Sub
28+
- Stack ${AWS::StackName} Function ${ResourceName}
29+
- ResourceName: PinpointFunction
30+
CodeUri: src/
31+
Handler: lambda_function.lambda_handler
32+
Runtime: python3.9
33+
MemorySize: 3008
34+
Timeout: 30
35+
Tracing: Active
36+
Events:
37+
ApiPOSTsendmessage:
38+
Type: Api
39+
Properties:
40+
Path: /send_message
41+
Method: POST
42+
RestApiId: !Ref Api
43+
Policies:
44+
- Statement:
45+
- Effect: Allow
46+
Action:
47+
- "mobiletargeting:PhoneNumberValidate"
48+
Resource: !Join
49+
- ""
50+
- - "arn:aws:mobiletargeting:*:"
51+
- !Ref AWS::AccountId
52+
- ":phone/number/validate"
53+
- Effect: Allow
54+
Action:
55+
- "mobiletargeting:SendMessages"
56+
Resource: !Join
57+
- ""
58+
- - "arn:aws:mobiletargeting:*:"
59+
- !Ref AWS::AccountId
60+
- ":apps/*/messages"
61+

0 commit comments

Comments
 (0)