Search code examples
phpamazon-lex

Amazon Lex postContent error "Failed to decode Session attributes."


I am attempting to connect my webpage to my Lex bot using postContent from the AWS SDK for PHP.

I set the credentials and arguments then attempt postContent. Here is the relevant code:

$credentials = new \Aws\Credentials\Credentials('XXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXXXX');

$args = array(
    'region' => 'us-east-1',
    'version' => 'latest',
    'debug' => true,
    'credentials' => $credentials
);

$lex_client = new Aws\LexRuntimeService\LexRuntimeServiceClient($args);

$lex_response = $lex_client->postContent([
    'accept' => 'text/plain; charset=utf-8',
    'botAlias' => 'XXXX',
    'botName' => 'XXXX',
    'contentType' => 'text/plain; charset=utf-8',
    'inputStream' => $userInput,
    'requestAttributes' => "{}",
    'sessionAttributes' => "{}",
    'userId' => 'XXXXXXXXXXXX',
]);

This errors with:

'Error executing "PostContent" on "https://runtime.lex.us-east-1.amazonaws.com/bot/XXXX/alias/XXXX/user/XXXXXXXXXX/content";

AWS HTTP error: Client error: POST https://runtime.lex.us-east-1.amazonaws.com/bot/XXXX/alias/XXXX/user/XXXXXXXXXX/content resulted in a 400 Bad Request response: {"message":"Invalid Request: Failed to decode Session attributes. Session Attributes should be a Base64 encoded json map of String to String"}' (length=142)

I have attempted using all kinds of JSON strings, JSON encoded strings, and Base64 encoded strings in the sessionAttributes but I continue to get this same error.


Solution

  • The LexRuntimeService in the AWS SDK automatically JSON encodes and Base64 encodes the postContent array. By passing it a JSON string, the json encoding in the SDK will place double quotes around the {} making it "{}" and that causes the error.

    So simply pass the sessionAttributes and requestAttributes as PHP arrays.

    $lex_response = $lex_client->postContent([
        'accept' => 'text/plain; charset=utf-8',
        'botAlias' => 'XXXX',
        'botName' => 'XXXX',
        'contentType' => 'text/plain; charset=utf-8',
        'inputStream' => $userInput,
        'requestAttributes' => array(),
        'sessionAttributes' => array(),            // <---- PHP Array not JSON
        'userId' => 'XXXXXXXXXXXX',
    ]);