Creating a AWS Lambda Serverless Functions to execute a SmartFlow

This tutorial will guide you through the creation of a serverless function using AWS Lambda that will allow you to execute a SmartFlow.

  1. Login/create an AWS account and select Lambda from the AWS Management Console.

2.  Click the Create a Lambda function.

3.  Choose Use a blueprint, type hello into the box and select the Hello-World example for the language of your choice.

4.  Give your Lambda a Name and Description. Select Create a new role with basic Lambda permissions.

5.  Click Create Function at the bottom of the page.

6. Replace the default code with the following:

const https = require('https');
exports.handler = async (event, context) => {
   return new Promise((resolve, reject) => {
       postSmartFlowsData(event.user_id, event.text)
           .then((response) => {
               const data = JSON.parse(response);
               context.succeed('Smartflows sent: ' +JSON.parse(response).msgBody);
           })

           .catch((err) => {
           //set an optional error message here
               context.fail( err.message);
           })
   });
};
const postSmartFlowsData = function(intent, msgText) {
   return new Promise((resolve, reject) => {
       var https = require('https');

       var data = JSON.stringify({
                   ANI: '<Enter A Source Identifier>',
                   msgIntent: intent,
                        msgBody: msgText,
                   DNIS: '<Enter A valid number from your account>',
                   flowId: '<Enter Your Flow ID>'

<<ADD ADDITIONAL PARAMETERS HERE>>

           });

       const options = {

           host : "smart-flows.intelepeer.com",
           protocol: "https:",
           method : "POST",
           port:443,
           path: "/v2/api/apitriggers",
           headers : {
               "Content-Type": "application/json",
               "Accept": "application/json",
                "Content-Length" : Buffer.byteLength(data)
           },
           body: data
       };

       console.log(options);
       const req = https.request(options,(response) => {
           if (response.statusCode < 200 || response.statusCode > 299) {
               reject(new Error('Failed with status code: ' + response.statusCode));
           }

           const body = [];

           response.on('data', (chunk) => body.push(chunk));
           response.on('end', () => resolve(body.join('')));
       });

       req.on('error', (err) => reject(err));

       req.write(data);
       req.end();
})
};
Enabling access to your function

Excerpts of this section of this section are taken from:  https://forums.aws.amazon.com/thread.jspa?messageID=673012&tstart=0#673012

  1. Now that we have the code setup we need a way to execute the code. Select Add Trigger.

2.  Select API Gateway , Set API to Create a new API, select the REST API Template, set Security to Open and click ADD.

3.  Select your API from the API Gateway settings.

4.  Click the Create method button in the top right, and select POST from the drop down on the left (and click the small tick).

5.  In the Integration type select Lambda function, and select the region your AWS account is set to and start typing for a list of your lambdas to appear.

6.  Click “Save”.

 

7.  On the following screen click the box Integration Request and scroll down to the Mapping Requests section.

8.  Click Add mapping templateand type application/x-www-form-urlencoded into the box and click the small tick. Click the pen icon next to the word Input passthrough and select Mapping template from the dropdown.

9. In the Template box put this code:

## convert HTML POST data or HTTP GET query string to JSON

## get the raw post data from the AWS built-in variable and give it a nicer name
#if ($context.httpMethod == "POST")
#set($rawAPIData = $input.path('$'))
#elseif ($context.httpMethod == "GET")
#set($rawAPIData = $input.params().querystring)
#set($rawAPIData = $rawAPIData.toString())
#set($rawAPIDataLength = $rawAPIData.length() - 1)
#set($rawAPIData = $rawAPIData.substring(1, $rawAPIDataLength))
#set($rawAPIData = $rawAPIData.replace(", ", "&"))
#else
#set($rawAPIData = "")
#end

## first we get the number of "&" in the string, this tells us if there is more than one key value pair
#set($countAmpersands = $rawAPIData.length() - $rawAPIData.replace("&", "").length())

## if there are no "&" at all then we have only one key value pair.
## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs.
## the "empty" kv pair to the right of the ampersand will be ignored anyway.
#if ($countAmpersands == 0)
#set($rawPostData = $rawAPIData + "&")
#end

## now we tokenise using the ampersand(s)
#set($tokenisedAmpersand = $rawAPIData.split("&"))

## we set up a variable to hold the valid key value pairs
#set($tokenisedEquals = [])

## now we set up a loop to find the valid key value pairs, which must contain only one "="
#foreach( $kvPair in $tokenisedAmpersand )
#set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length())
#if ($countEquals == 1)
#set($kvTokenised = $kvPair.split("="))
#if ($kvTokenised[0].length() > 0)
   ## we found a valid key value pair. add it to the list.
   #set($devNull = $tokenisedEquals.add($kvPair))
#end
#end
#end

## next we set up our loop inside the output structure "{" and "}"
{
#foreach( $kvPair in $tokenisedEquals )
## finally we output the JSON for this pair and append a comma if this isn't the last pair
#set($kvTokenised = $kvPair.split("="))
"$util.urlDecode($kvTokenised[0])" : #if($kvTokenised[1].length() > 0)"$util.urlDecode($kvTokenised[1])"#{else}""#end#if( $foreach.hasNext ),#end
#end
}

10.  Click the small tickto save these settings and select the Deploy API.

11.  In the popup box that follows select New stage and type prod into the Stage name Click Deploy to get your code live.

12.  At the top of the page you should now be given a HTTPS URL (similar to https://xyz.execute-api.zone-1.amazonaws.com/prod).