twiliotwilio-studiotwilio-functions

Twilio Functions - Validate CPF and CNPJ and format them according to standard


I'm new here and I would like to ask a question regarding the creation of functions in Twilio. Just to understand the context of my situation, I'm developing an IVR (Interactive Voice Response), and at a certain point in the flow, the customer's document data is requested. I would like to format it according to standards: For example, 123.456.789-00 (CPF) and 12.345.678/0001-00 (CNPJ). In a specific part of my flow, I created a Widget that captures the customer's document and saves it in the variable widgets.Inicio.Digits. Then it goes through the Widget Run Function, but it doesn't recognize the value.

Flow Widget Run Function

In the Run Function widget I set a function parameter with key event and value {{widget.Inicio.Digits}}

Where could I be going wrong? How do I use the value returned by the function in other parts of my flow?

My function

exports.handler = function(context, event, callback) {
    
    const cpfOrCnpj = event.widgets.Inicio.Digits;

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

return

 "validateCPF": {
      "status_code": 500,
      "content_type": "text/plain",
      "body": "Data not received. Please check if the CPF or CNPJ value is being passed correctly"
    }

    

Solution

  • Since you set the function parameter to event in the Function widget, you can use that parameter name in the code as well. In your code above, you use a variable name that is only available within the Studio flow itself.

    Instead, if should be:

    exports.handler = function(context, event, callback) {
        
        const cpfOrCnpj = event.event;
    

    Hint: I'd recommend changing the function parameter name in both places since event.event might lead to confusion.