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

Twilio Functions问题:CPF/CNPJ验证格式化及传值异常排查

问题分析与解决方案:Twilio IVR中CPF/CNPJ格式化函数报错及返回值使用

问题根源

  1. 参数传递路径错误:你在Run Function Widget里将参数key设为event,值为{{widget.Inicio.Digits}},这意味着函数接收的event对象里并没有widgets.Inicio.Digits这个嵌套结构——实际传入的是把Digits的值直接绑定到了event.event字段,而非你代码中期望的嵌套路径。
  2. 未处理空值情况:当代码尝试访问不存在的event.widgets.Inicio.Digits时,cpfOrCnpj会变为undefined,调用replace方法直接抛出未捕获错误,触发500状态码,而非走到你写的格式校验分支。

修复步骤

1. 调整Run Function Widget的参数配置

将参数的key从event改为明确的名称(比如cpfCnpj),值保持{{widget.Inicio.Digits}}。这样函数就能直接通过event.cpfCnpj获取用户输入的数值。

2. 修正函数代码

调整取值逻辑,同时增加空值判断避免报错:

exports.handler = function(context, event, callback) {
    // 直接获取传入的参数
    const cpfOrCnpj = event.cpfCnpj;
    
    // 先检查是否接收到有效数据
    if (!cpfOrCnpj) {
        return callback("Data not received. Please check if the CPF or CNPJ value is being passed correctly");
    }
    
    const cleanedCpfOrCnpj = cpfOrCnpj.replace(/[^\d]/g, '');
    let formatted;
    
    if (cleanedCpfOrCnpj.length === 11) {
        formatted = cleanedCpfOrCnpj.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
    } else if (cleanedCpfOrCnpj.length === 14) {
        formatted = cleanedCpfOrCnpj.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
    } else {
        return callback("Formato inválido. O valor inserido deve ser CPF (11 dígitos) ou CNPJ (14 dígitos).");
    }
    
    callback(null, { formattedValue: formatted });
};

在流程其他环节使用函数返回值

Run Function Widget执行成功后,返回的formattedValue会存入流程变量,引用路径为:
{{widgets.<你的RunFunctionWidget名称>.formattedValue}}

比如你的Run Function Widget名为validateCPF,后续的Say或其他Widget中,就可以通过{{widgets.validateCPF.formattedValue}}调用格式化后的CPF/CNPJ值。

内容的提问来源于stack exchange,提问作者Leonardo Rubio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:05:13