

# Learn about the telephony events that invoke AWS Lambda functions for the Amazon Chime SDK PSTN audio service
<a name="invoking-Lambda"></a>

The Audio Service invokes AWS Lambda functions in response to different events. Each invocation specifies an invocation event type and provides the call details, including its participants, if applicable. The following topics describe the Audio Service events that invoke AWS Lambda functions. 

# Making an outbound call for using Amazon Chime SDK PSTN audio service
<a name="use-create-call-api"></a>

To create an outbound call, you use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API. The API invokes the endpoint of a specified `SIP media application ID`. Customers can control the flow of the call by giving different signaling and [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_SipMediaApplication.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_SipMediaApplication.html) actions from the endpoint. 

In the event of a successful response, the API returns a 202 http status code along with a transactionId, which you can use with the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API to update an in-progress call.

The following diagram shows the invocations made to the AWS Lambda function endpoint for an outbound call.

![\[Diagram showing the programming flow for invocations made to the AWS Lambda endpoint.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sip-api-1.png)


The endpoint configured for the SIP media application is invoked for different statuses of the outbound call. When a customer initiates a call, The Amazon Chime SDK invokes the endpoint with a `NEW_OUTBOUND_CALL` invocation event type. 

This example shows a typical invocation event for a `NEW_OUTBOUND_CALL`.

```
{
    "SchemaVersion": "1.0",
        "Sequence": 1,
        "InvocationEventType": "NEW_OUTBOUND_CALL",
        "CallDetails": {
            "TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234"
                }
            ]
    }
}
```

Any response for an event related AWS Lambda invocation is ignored.

When we receive a `RINGING` notification from the receiver, the Amazon Chime SDK invokes the configured endpoint again. 

This example shows a typical invocation event for `RINGING`.

```
{
    "SchemaVersion": "1.0",
        "Sequence": 1,
        "InvocationEventType": "RINGING",
        "CallDetails": {
            "TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234"
                }
           ]
    }
}
```

Any response for an event related AWS Lambda invocation is ignored.

If the receiver doesn't answer the call, or the call fails due to an error, Chime disconnects the call and invokes the endpoint with the `Hangup` event type. For more information about the `Hangup` event type, refer to [Ending a call using the Amazon Chime SDK PSTN audio service](case-5.md). 

If the call is answered, Chime invokes the endpoint with the `CALL_ANSWERED` action. This example shows a typical invocation event.

```
{
  "SchemaVersion": "1.0",
    "Sequence": 1,
    "InvocationEventType": "CALL_ANSWERED",
    "CallDetails": {
        ""TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

At this point, you can return actions by responding to the invocation with an action list. If you don’t want to run any actions, respond with an empty list. You can respond with a maximum of 10 actions for each AWS Lambda invocation, and you can invoke a Lambda function 1,000 times per call. For more information about responding with sets of actions, refer to [Responding to invocations with action lists using the Amazon Chime SDK PSTN audio service](invoke-on-call-leg.md).

# Receiving an inbound call using the Amazon Chime SDK PSTN audio service
<a name="case-1"></a>

When a `NEW_INCOMING_CALL` event occurs, the Audio Service creates a unique `TransactionID` and unique `CallID` that persist until the `HANGUP` event occurs.

You can respond in several ways to a `NEW_INCOMING_CALL` event. For example:
+ Send `PlayAudio` or `RecordAudio` actions and automatically answer the call. 
+ Send a `Pause` action.
+ Send a `Hangup` action, in which case the call isn’t answered and the customer isn’t charged.
+ Send a `CallAndBridge` action and add another user to the call.
+ Do nothing, the call attempt times out after 30 seconds.

When a new inbound call is received, the SIP media application invokes an AWS Lambda function with this payload.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 2,
    "InvocationEventType": "NEW_INBOUND_CALL"
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

# Specifying actions in response to telephony events for the Amazon Chime SDK PSTN audio service
<a name="use-case-2"></a>

In the Audio Service, SIP media applications invoke AWS Lambda functions. In turn, a Lambda function can return a list of instructions known as *actions*. An action is an item that you want to run on a leg of a phone call, such as sending or receiving digits, joining a meeting, and so on. For more information about the actions invoked by the PSTN audio service, see [Understanding telephony events for Amazon Chime SDK PSTN audio service](pstn-invocations.md).

When a SIP media application successfully runs a list of actions, the application calls the AWS Lambda function with an invocation event type of `ACTION_SUCCESSFUL`. If any of the actions fail to complete, the SIP media application calls the AWS Lambda function with the `ACTION_FAILED` event.

The SIP media application only returns `ACTION_SUCCESSFUL` if all the actions on the list succeed. If any of the actions in the list fail, the SIP media application invokes the AWS Lambda function with the `ACTION_FAILED` event and clears the remaining actions in the list after the failed one. Then the SIP media application runs the next action returned by the AWS Lambda function. You use the `ActionData` key to identify which call invoked the function.

The following event shows a sample payload for the `ACTION_SUCCESSFUL` invocation event type after a `PlayAudioAndGetDigits` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "failure-audio-file.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "failure-audio-file.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ReceivedDigits": "123"
    }
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
                }
            ]
        }
    }
}
```

When any action in a list fails to complete successfully, the SIP media application invokes the AWS Lambda function to notify you of the failure, and to get a new set of actions to run on that call. The following event shows the sample payload for the `ACTION_FAILED` invocation event type after a `PlayAudio` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type": "PlayAudio",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file.wav"            
            }
        },
        "ErrorType": "InvalidAudioSource",
        "ErrorMessage": "Audio Source parameter value is invalid."
    }
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
}
```

# Receiving caller input for the Amazon Chime SDK PSTN audio service
<a name="case-4"></a>

You use the `ReceiveDigits` action to collect inbound DTMF digits and match them against a regular expression. When the SIP media application receives digits that match the regular expression, it invokes a AWS Lambda function with an `ACTION_SUCCESSFUL` event. The collected digits appear in the `ReceivedDigits` value in the `ActionData` object.

For example:

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "ReceivedDigits": "",
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-1",
            "InputDigitsRegex": "^\d{2}#$",
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "FlushDigitsDurationInMilliseconds": 10000
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

Once the caller enters digits that match your regular expression pattern, the SIP media application invokes an AWS Lambda function that returns the following type of payload:

```
{
    "SchemaVersion": "1.0",
    "Sequence": 5,
    "InvocationEventType": "DIGITS_RECEIVED",
    "ActionData": {
        "ReceivedDigits": "11#",
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-1",
            "InputDigitsRegex": "^\d{2}#$",
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "FlushDigitsDurationInMilliseconds": 10000
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# Updating in-progress calls for Amazon Chime SDK PTSN audio
<a name="update-sip-call"></a>

As part of the PSTN audio service, SIP media applications allow you to set actions that are run on a call by invoking user-defined Lambda functions based on the call events, such as an incoming call or DTMF digits. The [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API allows you to trigger a Lambda function at any time while a call is active, replacing the current actions with new actions returned by the invocation.

**Workflow**  
You use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API in variety of cases, such as adding participants to a meeting, muting and unmuting user, disconnecting them, and so on. The following use case describes a typical workflow.

A user calls and listens to music while Amazon Chime SDK sets up the meeting. Once setup completes, Amazon Chime SDK stops the audio and admits the caller into the meeting. Next, assume the use of a separate system, `MyMeetingService`, that manages meetings. Every incoming call should be put on hold. Chime notifies MyMeetingService about incoming calls, and MyMeetingService then creates an attendee for each call, and when the MyMeetingService is ready to start the meeting, it notifies the SIP media application and provides a token for joining the meeting.

To handle this case, the Lambda function has to implement the following logic. 
+ When a new incoming call arrives, the Lambda is invoked with a `NEW_INBOUND_CALL` event. The Lambda calls the `MyMeetingService` and passes the `transactionId` that identifies the current call, and returns the `PlayAudio` action.
+ When the `MyMeetingService` is ready to add the caller to the meeting, the service calls the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API and passes the call's `transactionId` and `JoinToken` as part of its arguments. This API call triggers the Lambda function again, now with the `CALL_UPDATE_REQUESTED` event. The MyMeetingService passes the `JoinToken` to the Lambda function as part of the event, and the token is used to return the `JoinChimeMeeting` action to the SIP media application, which interrupts the `PlayAudio` action and connects the caller to the meeting.

![\[Diagram showing the flow of data in the UpdateSipMediaApplicationCall API.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/update-sip-call-flow3.png)


**Note**  
The [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API returns HTTP 202 (Accepted). The SIP media application confirms that the call is in progress and can be updated, so it attempts to invoke the Lambda function. The invocation is performed asynchronously, so a successful response from the API doesn’t guarantee that the Lambda function has started or completed.

The following example shows the request syntax.

```
{
    "SipMediaApplicationId": "string",
    "TransactionId": "string",
    "Arguments": {
        "string": "string"
    } 
}
```

**Request parameters**
+ `SipMediaApplicationId` – The ID of the SIP media application that handles the call. 
+ `TransactionId` – The ID of the call transaction. For inbound calls, the `TransactionId` can be obtained from the `NEW_INCOMING_CALL` event passed to the Lambda function on its first invocation. For outbound calls, `TransactionId` is returned in the response of [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html). 
+ **Arguments** – Custom arguments made available to the Lambda function as part of the `CallUpdateRequest` action data. Can contain 0 to 20 key-value pairs.

The following example shows a typical request.

```
aws chime update-sip-media-application-call --sip-media-application-id feb37a7e-2b66-49fb-b2dd-30f4780dc36d --transaction-id 1322a4e7-c106-4e70-aaaf-a8fa4c77c0cb --arguments '{"JoinToken": "abc123"}'
```

**Response syntax**

```
{
  "SipMediaApplicationCall": {
  "TransactionId": "string"
  }
}
```

**Response elements**
+ **TransactionId** – The ID of the call transaction, the same ID as the request.

The following example shows a `CALL_UPDATE_REQUESTED` invocation event.

```
{
  "SchemaVersion": "1.0",
  "Sequence": 2,
  "InvocationEventType": "CALL_UPDATE_REQUESTED",
  "ActionData": {
    "Type": "CallUpdateRequest",
    "Parameters": {
      "Arguments": {
        "string": "string"
      }
    }
  },
  "CallDetails": {
    ...
  }
}
```

**Event elements**
+ **SchemaVersion** – The version of the JSON schema (1.0)
+ **Sequence** – The sequence number of the event in the call
+ **InvocationEventType** – The type of Lambda invocation event, in this case, `CALL_UPDATE_REQUESTED`
+ **ActionData** – The data associated with the `CallUpdateRequest` action.
  + **Type** – The type of action, in this case, `CallUpdateRequest`
  + **Parameters** – The parameters of the action
    + **Arguments** – The arguments passed as part of the `UpdateSipMediaApplicationCall` API request
+ **CallDetails** – The information about the current call state

**Understanding interruptible and non-interruptable actions**  
When a Lambda function returns a new list of actions while existing actions run, all actions that follow the in-progress action are replaced with the new actions. In some cases, the Lambda function interrupts in-progress actions in order to run new actions immediately.

The following diagram shows a typical example. Text below the digram explains the logic.

![\[Diagram showing how actions can be replaced during an ongoing SIP media application call.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/update-sip-actions.png)


If Action 2 is interruptible, we stop it and run new Action 1 instead.

If Action 2 is not interruptible, it completes before the new Action 1 starts.

In both cases, Action 3 isn't run.

If something interrupts an action, the Lambda function is invoked with an `ACTION_INTERRUPTED` event. This event is used for informational purpose only. The SIP media application ignores all actions returned by this invocation.

Types of interruptible actions:
+ `PlayAudio`
+ `RecordAudio`
+ `Pause`

**Sample Lambda function**  
This example shows a typical Lambda function that plays an audio file, passes a join token, and updates the call.

```
const MMS = require('my-meeting-service');
const myMeetingServiceClient = new MMS.Client();

exports.handler = async (event) => {
    console.log('Request: ' + JSON.stringify(event));
    
    const playAudio = () => {
      return {
        Type: 'PlayAudio',
        Parameters: {
          ParticipantTag: 'LEG-A',
          AudioSource: {
            Type: 'S3',
            BucketName: 'chime-meetings-audio-files-bucket-name',
            Key: 'welcome.wav'
          }
        }
      }
    }
    
    const joinChimeMeeting = (joinToken) => {
      return {
        Type: 'JoinChimeMeeting',
        Parameters: {
          JoinToken: joinToken
        }
      }
    }
    
    const response = (...actions) => {
      const r = {
        SchemaVersion: '1.0',
        Actions: actions
      };
      console.log('Response: ' + JSON.stringify(r));
      return r;
    };
    
    switch (event.InvocationEventType) {
      case 'NEW_INBOUND_CALL': 
        myMeetingServiceClient.addPendingCall(event.CallDetails.TransactionId);         
        return response(playAudio());      
      case 'CALL_UPDATE_REQUESTED':
        const joinToken = event.ActionData.Parameters.Arguments['JoinToken']
        return response(joinChimeMeeting(joinToken));
      default:
        return response();
    }
}
```

# Ending a call using the Amazon Chime SDK PSTN audio service
<a name="case-5"></a>

You can use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API to end an outbound call. The API invokes the endpoint of a specified **SIP media application ID**. Customers can control the flow of the call by returning actions to the SIP media application.

In the event of a successful response, the API returns a 202 http status code along with the `transactionId`, which you can use with the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API to update an in-progress call.

The following diagram shows the invocations made to the AWS Lambda function endpoint for an outbound call.

![\[The flow of data when you invoke the CreateSipMediaApplicationCall API. The API invokes a different endpoint when the status of an outbound call changes.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sip-api-1.png)


The endpoint configured for the SIP media application is invoked for different statuses of the outbound call. When a customer ands a call, the Amazon Chime SDK invokes the endpoint with a `HANGUP` invocation event type. 

This example shows a typical invocation event for a `HANGUP`.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 6,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "Hangup",
        "Parameters": {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "Direction": "Inbound",
                 "To": "+12065551212",
                "From": "+15105550101",
                "StartTimeInMilliseconds": "1597009588",
                "Status": "Disconnected"
            }
        ]
    }
}

// if LEG-B receives a hangup in a bridged call, such as a meeting ending
{
    "SchemaVersion": "1.0",
    "Sequence": 6,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-2",
            "ParticipantTag": "LEG-B"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "Leg-A",
                 "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "1597009588",
                "Status": "Connected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "Leg-B",
                "To": "+17035550122",
                "From": "SMA",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "15010595",
                "Status": "Disconnected"
            }
        ]
    }
}
```

# Understanding end-to-end calls for the Amazon Chime SDK PSTN audio service
<a name="use-cases"></a>

This use case provides example code for receiving a phone call from a PSTN caller, greeting the caller with an audio message, getting the meeting PIN from the caller, playing audio, and joining the caller to the meeting.

**Invocation events and actions**  
The Audio Service passes invocation events to AWS Lambda functions as JSON objects. The objects include the invocation event type and any relevant metatdata. The AWS Lambda function also returns SIP media application actions as JSON objects, and those objects include an action type and any relevant metadata.

The following table lists the invocation events, and the possible `ActionData.Type`, when you receive an invocation event.


|  Invocation event  |  ActionData.Type  | 
| --- | --- | 
|  ACTION\$1SUCCESSFUL  |  CallAndBridge ReceiveDigits PlayAudio PlayAudioAndGetDigits  JoinChimeMeeting ModifyChimeMeetingAttendees RecordMeeting  | 
|  ACTION\$1FAILED  |  CallAndBridge PlayAudio PlayAudioAndGetDigits ModifyChimeMeetingAttendees RecordMeeting  | 
| HANGUP |  HangUp  | 
|  DIGITS\$1RECEIVED  | ReceiveDigits | 

**Note**  
To implement the following use case, you need at least one phone number in your Amazon Chime SDK inventory, a SIP media application managed object that uses a AWS Lambda function with an Amazon Resource Name (ARN), and a SIP rule that uses the phone number as its trigger.

When Amazon Chime SDK receives a call to the phone number specified in the rule, the PSTN audio service invokes a AWS Lambda function with the `NEW_INBOUND_CALL` invocation event type.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 1,
    "InvocationEventType": "NEW_INBOUND_CALL",
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

You can program the AWS Lambda function to validate call details and store them for future use. For a `NEW_INBOUND_CALL` event, the AWS Lambda function responds with a set of actions that play a welcome prompt and ask for the meeting PIN.

Audio files have the following requirements:
+ You must play audio files from an Amazon Simple Storage Service (S3) bucket. The S3 bucket must belong to the same AWS account as the SIP media application. In addition, you must give the `s3:GetObject` permission to the Amazon Chime SDK Voice Connector service principal—`voiceconnector.chime.amazonaws.com`. You can use the S3 console or the command-line interface (CLI) to do that.
+ You must use PCM WAV files of no more than 50 MB in size. The Amazon Chime SDK recommends 8 KHz mono.
+ The S3 metadata for each WAV file must contain `{'ContentType': 'audio/wav'}`.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type" : "PlayAudio",    
            "Parameters" : {
                "CallId": "call-id-1",
                
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "welcome-to-meetings.wav"
                }
            }
        },
        {
            "Type": "PlayAudioAndGetDigits",
            "Parameters" : {
                "ParticipantTag": "LEG-A",
                
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "enter-meeting-pin.wav"
                },
                "FailureAudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "invalid-meeting-pin.wav"
                },
                "MinNumberOfDigits": 3,
                "MaxNumberOfDigits": 5,
                "TerminatorDigits": ["#"],
                "InBetweenDigitsDurationInMilliseconds": 5000,
                "Repeat": 3,
                "RepeatDurationInMilliseconds": 10000
            }
        }
    ]
}
```

The SIP media application runs these actions on call leg A. Assuming the `PlayAudioAndGetDigits` action receives the digits, the SIP media application invokes the AWS Lambda function with the `ACTION_SUCCESSFUL` event type.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 2,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "ParticipantTag": "LEG-A",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "chime-meetings-audio-files-bucket-name",
                "Key": "enter-meeting-pin.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "chime-meetings-audio-files-bucket-name",
                "Key": "invalid-meeting-pin.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ReceivedDigits": "12345" // meeting PIN
    },
    "CallDetails": {
        ... // same as in previous event
    }
}
}
```

You can program an AWS Lambda function to identify the caller based on the `CallDetails` data. You can also validate the meeting PIN received earlier. Assuming a correct PIN, you then use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html) and [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html) APIs to create the Amazon Chime SDK meeting and generate the join token used by the meeting attendee. The AWS Lambda function responds with the action to join the Amazon Chime SDK meeting.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "JoinChimeMeeting",
            "Parameters": {
                "JoinToken": "meeting-attendee-join-token"
            }
        }
    ]
}
```

Assuming the `JoinToken` is valid, the SIP media application joins the Amazon Chime SDK meeting and invokes a AWS Lambda function with the `ACTION_SUCCESSFUL` event, where `CallDetails` contains the data from the SIP media application and the Chime Media service (`LEG-B`) 

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type" : "JoinChimeMeeting",
        "Parameters" : {
            "JoinToken": "meeting-attendee-join-token"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id", 
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "LEG-B",
                "To": "SMA",
                "From": "+17035550122",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

If you want to stop running actions on the call or call leg at this point, you can respond with an empty set of actions.

```
{
    "SchemaVersion": "1.0"
    "Actions": []
}
```

After the caller hangs up, the SIP media application invokes the AWS Lambda function with the `HANGUP` event. 

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "Hangup",
        "Parameters": {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id", 
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Disconnected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "LEG-B",
                "To": "SMA",
                "From": "+17035550122",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Disconnected"
            }
        ]
    }
}
```

If you respond to a `Hangup` event with an action, the SIP media application ignores the action if no other `Participants` show a `Status` of `Connected`.