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

WhatsApp模板参数传递格式问题:to_number类型不符报错

问题排查与解决方案

问题定位

核心问题是**to_number参数在Flow端点接收时类型不匹配**:

  • 聊天机器人日志显示发送的payload中to_number是字符串"27815492711",但Flow端点收到的data要么为空对象,要么报错提示data.to_number应为字符串类型,且日志显示Handling INIT for user number: None,说明data.get("to_number")未取到有效值,后续返回时将None传入response_dict的data.to_number,触发类型校验失败。

原因分析

  1. Flow按钮参数结构错误:WhatsApp Flow要求按钮payload的业务参数必须包裹在data字段内,当前代码直接把action和to_number放在顶层,不符合Flow的参数传递规范。
  2. 参数读取路径不匹配:Flow端点期望从请求体的data字段中获取to_number,但发送的payload未按要求嵌套,导致端点无法拿到有效值,最终返回None(非字符串类型)触发schema错误。

修复步骤

1. 修正聊天机器人的payload结构

将to_number放入data字段内,同时确保参数为字符串类型,调整后的按钮参数代码如下:

{
    'type': 'button',
    'sub_type': 'flow',
    'index': '0',
    'parameters': [
        {
            'type': 'payload',
            'payload': json.dumps({
                'action': 'INIT',
                # 关键:将to_number嵌套在data字段下
                'data': {
                    'to_number': str(to_number)  # 强制转为字符串,避免类型隐性问题
                }
            })
        }
    ]
}

2. 确保Flow端点的参数读取逻辑正确

确认端点从请求体的顶层data字段中读取参数,示例代码如下:

# 先解析请求体
request_body = json.loads(request.get_data())
action = request_body.get("action")
# 从顶层获取data字段,默认空对象避免KeyError
data = request_body.get("data", {})
user_number = data.get("to_number")

3. 增加类型校验(可选但推荐)

在Flow端点中添加user_number的类型校验,提前拦截非法参数:

elif action == "INIT":
    try:
        request_body = json.loads(request.get_data())
        data = request_body.get("data", {})
        user_number = data.get("to_number")
        
        # 校验参数是否为非空字符串
        if not isinstance(user_number, str) or not user_number.strip():
            return https_fn.Response(
                json.dumps({"error": "to_number must be a non-empty string"}),
                status=400,
                mimetype="application/json"
            )
            
        options = [
            {
                "id": name.replace(" ", "_"),
                "title": name
            }
            for name in client_names
        ]
        response_dict = {
            "screen": "DETAILS",
            "data": {
                "to_number": user_number
            }
        }
        return https_fn.Response(json.dumps(response_dict), mimetype="application/json")
    except Exception as e:
        logger.exception("Error in INIT action")
        return https_fn.Response(json.dumps({"error": str(e)}), status=500, mimetype="application/json")

验证方法

修复后重新发送模板,检查Flow端点日志:

  • 确认Decrypted Body中的data字段包含to_number字符串值
  • 日志不再出现payload-schema-error,且Handling INIT for user number: 27815492711显示正确号码

内容的提问来源于stack exchange,提问作者Pieter le Roux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:55:15