You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS SDK for PHP调用Lex postContent时会话属性解码失败问题

解决AWS Lex postContent接口的Session Attributes编码错误

你遇到的这个400错误核心原因是Lex的postContent接口要求sessionAttributes和requestAttributes必须是Base64编码后的JSON字符串,而且JSON结构必须是String到String的键值对映射。你之前直接传"{}"这种空JSON字符串是不符合要求的,得经过两步处理:先序列化为JSON,再做Base64编码。

正确的参数处理步骤

  • 第一步:定义一个空数组(或者包含字符串键值对的数组,比如['userRole' => 'admin'])
  • 第二步:将数组序列化为标准JSON字符串
  • 第三步:对JSON字符串进行Base64编码
  • 第四步:把编码后的结果传入参数

修改后的代码示例

$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); 

// 处理sessionAttributes和requestAttributes
$emptySessionAttrs = base64_encode(json_encode([]));
$emptyRequestAttrs = base64_encode(json_encode([]));

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

额外注意事项

  • 如果需要传递实际的会话属性,确保数组里的所有键和值都是字符串类型,比如:
    $sessionAttrs = base64_encode(json_encode([
        'username' => 'johndoe',
        'preferredLanguage' => 'en-US'
    ]));
    
  • 不要直接传递未编码的JSON字符串,哪怕是空对象也不行——Lex会把它当成普通字符串,无法解析成预期的映射结构。

内容的提问来源于stack exchange,提问作者Jay A. Little

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:58:05