||

CRM Google Sheet com WhatsApp Integrado de forma manual na loja da Tray

Nesse tutorial vamos mostrar como fizemos via código, um botão de whatsapp flutuante em uma loja tray, onde ao clicar no botão, abre um formulário com 3 campos para captação desse lead e como enviar esses dados diretamente para uma planilha Gooogle Sheet sem precisar de nenhuma outra plataforma.

Antes de continuar quero dizer que todo código foi fornecido pela IA Mônica, que tem sido fundamental no dia a dia do time de desenvolvimento aqui da agência.

Nesse tutorial você vai conseguir:

  • Coletar informações dos visitantes
  • Armazenar dados em uma planilha Google
  • Rastrear origem do tráfego e parâmetros UTM
  • Conectar diretamente com WhatsApp
  • Funcionar de forma responsiva em qualquer dispositivo

1. Preparando a Planilha Google

  1. Primeiro, crie uma nova planilha no Google Sheets
  2. Renomeie a primeira aba para “Leads”
  3. Na primeira linha, adicione as seguintes colunas. Opcional: Congele a primeira linha (View > Freeze > 1 row)
Data/Hora
Nome
Email
Telefone
Fonte de Tráfego
Parâmetros UTM
Tipo de Dispositivo
URL da Página
Referrer
Horário Primeiro Clique
Contagem de Cliques
ID Cliente GA

4. Para obter o ID da planilha, observe a URL quando estiver com ela aberta:

https://docs.google.com/spreadsheets/d/SEU_ID_DA_PLANILHA_AQUI/edit#gid=0

O texto entre /d/ e /edit é o ID da sua planilha. Você vai precisar desse ID para colocar no código dentro do Google Script

2. Configurando o Script do Google Apps

  1. Acesse Google Apps Script
  2. Crie um novo projeto
  3. Cole o código abaixo –
function doPost(e) {
  try {
    // Obtém a planilha e a aba ativa
    var spreadsheet = SpreadsheetApp.openById('COLE_SEU_ID_DA_PLANILHA');
    var sheet = spreadsheet.getActiveSheet();
    
    // Parse dos dados JSON recebidos
    var data = JSON.parse(e.postData.contents);
    
    // Formata a data/hora para o fuso horário de São Paulo
    var timestamp = new Date(data.timestamp);
    var timeZone = "America/Sao_Paulo";
    var formattedDate = Utilities.formatDate(timestamp, timeZone, "dd/MM/yyyy HH:mm:ss");
    
    // Formata os parâmetros UTM em uma string
    var utmString = Object.entries(data.utmParameters || {})
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ');
    
    // Prepara os dados para inserção
    var rowData = [
      formattedDate,              // Data e Hora
      data.name,                  // Nome
      data.email,                 // Email
      data.phone,                 // Telefone
      data.trafficSource,         // Fonte de Tráfego
      utmString,                  // Parâmetros UTM
      data.deviceInfo.type,       // Tipo de Dispositivo
      data.pageInfo.url,         // URL da página
      data.pageInfo.referrer,    // Referrer
      data.interactionData.firstClickTime,  // Horário do primeiro clique
      data.interactionData.clickCount,      // Contagem de cliques
      data.interactionData.clientId         // ID do cliente GA
    ];
    
    // Insere os dados na próxima linha
    sheet.appendRow(rowData);
    
    // Retorna sucesso
    return ContentService.createTextOutput(JSON.stringify({
      'status': 'success',
      'message': 'Dados inseridos com sucesso'
    })).setMimeType(ContentService.MimeType.JSON);
    
  } catch(error) {
    // Retorna erro
    return ContentService.createTextOutput(JSON.stringify({
      'status': 'error',
      'message': error.toString()
    })).setMimeType(ContentService.MimeType.JSON);
  }
}
  1. Clique em “Implantar” > “Novo deployment”
  2. Escolha “Novo deployment”
  3. Selecione “Web app”
  4. Configure:
    • Execute como: Sua conta
    • Quem pode acessar: Qualquer pessoa
  5. Clique em “Implantar”
  6. Autorize as permissões necessárias
  7. Copie a URL do Web App fornecida

4. Implementando via Google Tag Manager

  1. Acesse o Google Tag Manager
  2. Vá em “Tags” > “Nova”
  3. Escolha “HTML Personalizado”
  4. Cole o código abaixo:
// Inicialização do DataLayer
<script>
window.dataLayer = window.dataLayer || [];

// ===== FUNÇÕES AUXILIARES =====

function getUTMParameters() {
    var utmParams = {};
    var urlParams = new URLSearchParams(window.location.search);
    ['source', 'medium', 'campaign', 'term', 'content'].forEach(function(param) {
        var value = urlParams.get('utm_' + param);
        if (value) utmParams['utm_' + param] = value;
    });
    return utmParams;
}

function getCookieValue(name) {
    var value = '; ' + document.cookie;
    var parts = value.split('; ' + name + '=');
    if (parts.length === 2) return parts.pop().split(';').shift();
    return '';
}

function getTrafficSource() {
    var referrer = document.referrer;
    if (!referrer) return 'Direct';
    
    var referrerDomain = new URL(referrer).hostname;
    if (referrerDomain.includes('google')) return 'Google';
    if (referrerDomain.includes('facebook')) return 'Facebook';
    if (referrerDomain.includes('instagram')) return 'Instagram';
    if (referrerDomain.includes('linkedin')) return 'LinkedIn';
    return referrerDomain;
}

// ===== INSERÇÃO DO HTML =====

document.body.insertAdjacentHTML('beforeend', 
    '<div id="whatsapp-button" style="position: fixed; bottom: 0; right: 0; z-index: 9999; cursor: pointer;">' +
        '<img src="https://i.imgur.com/JM1r0nW.png" alt="WhatsApp" style="width: 220px; height: auto;">' +
    '</div>' +
    '<div id="whatsapp-modal" style="display: none; position: fixed; bottom: 120px; right: 20px; z-index: 10000;">' +
        '<div style="position: relative; background: white; width: 300px; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">' +
            '<span id="close-modal" style="position: absolute; right: 15px; top: 10px; cursor: pointer; font-size: 24px; color: #666;">×</span>' +
            '<h3 style="margin-bottom: 20px; color: #333; text-align: center;">Iniciar conversa no WhatsApp</h3>' +
            '<form id="whatsapp-form">' +
                '<div style="margin-bottom: 15px;">' +
                    '<input type="text" id="whats-name" placeholder="Seu nome" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box;">' +
                '</div>' +
                '<div style="margin-bottom: 15px;">' +
                    '<input type="email" id="whats-email" placeholder="Seu e-mail" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box;">' +
                '</div>' +
                '<div style="margin-bottom: 20px; position: relative;">' +
                    '<input type="tel" id="whats-phone" placeholder="(XX) XXXXX-XXXX" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box;">' +
                    '<small style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></small>' +
                '</div>' +
                '<button type="submit" id="whatsapp-submit-btn" style="background: #25D366; color: white; border: none; padding: 12px 20px; width: 100%; border-radius: 5px; font-size: 16px; cursor: pointer; transition: background 0.3s;">Iniciar Conversa</button>' +
            '</form>' +
        '</div>' +
    '</div>'
);

// ===== ESTILOS RESPONSIVOS =====

var style = document.createElement('style');
style.textContent = 
    '@media screen and (max-width: 768px) {' +
    '    #whatsapp-button img { width: 200px !important; }' +
    '    #whatsapp-modal { width: 90% !important; right: 5% !important; bottom: 100px !important; }' +
    '}';
document.head.appendChild(style);

// ===== FUNCIONALIDADE PRINCIPAL =====

(function() {
    var whatsappNumber = 'SEUNUMEROAQUI'; // Seu número formatado
    var webhookUrl = 'URL DO SCRIPT GOOGLE AQUI';

    var modal = document.getElementById('whatsapp-modal');
    var button = document.getElementById('whatsapp-button');
    var closeBtn = document.getElementById('close-modal');
    var form = document.getElementById('whatsapp-form');
    var phoneInput = document.getElementById('whats-phone');

    var clickTimestamp;
    var buttonClickCount = 0;

    function setLoadingState(button, isLoading) {
        if (isLoading) {
            button.disabled = true;
            button.style.backgroundColor = '#1a9547';
            button.innerHTML = 'Abrindo WhatsApp...';
            button.style.cursor = 'wait';
        } else {
            button.disabled = false;
            button.style.backgroundColor = '#25D366';
            button.innerHTML = 'Iniciar Conversa';
            button.style.cursor = 'pointer';
        }
    }

    function resetForm(form, button) {
        setTimeout(function() {
            form.reset();
            setLoadingState(button, false);
        }, 3000);
    }

    function maskPhone(event) {
        var value = event.target.value;
        value = value.replace(/\D/g, '');
        value = value.replace(/^(\d{2})(\d)/g, '($1) $2');
        value = value.replace(/(\d)(\d{4})$/, '$1-$2');
        event.target.value = value;
    }

    function validatePhone(phone) {
        var regex = /^\([1-9]{2}\) (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$/;
        return regex.test(phone);
    }

    phoneInput.addEventListener('input', maskPhone);
    phoneInput.addEventListener('focus', function() {
        if (!this.value) {
            this.value = '(';
        }
    });

    button.addEventListener('click', function() {
        buttonClickCount++;
        clickTimestamp = new Date().toISOString();
        modal.style.display = 'block';
        
        // Evento de clique no botão do WhatsApp
        dataLayer.push({
            'event': 'whatsapp_button_click'
        });
    });

    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
        
        // Evento de fechamento do modal
        dataLayer.push({
            'event': 'whatsapp_modal_close'
        });
    });

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        var submitButton = document.getElementById('whatsapp-submit-btn');
        
        // Previne múltiplos envios
        if (submitButton.disabled) {
            return;
        }

        var name = document.getElementById('whats-name').value;
        var email = document.getElementById('whats-email').value;
        var phone = phoneInput.value;

        if (!validatePhone(phone)) {
            alert('Por favor, insira um número de telefone válido no formato (XX) XXXXX-XXXX');
            return;
        }

        // Ativa o estado de loading
        setLoadingState(submitButton, true);

        var enrichedData = {
            name: name,
            email: email,
            phone: phone,
            timestamp: new Date().toISOString(),
            trafficSource: getTrafficSource(),
            utmParameters: getUTMParameters(),
            deviceInfo: {
                type: /Mobile|Android|iPhone/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop',
                userAgent: navigator.userAgent
            },
            pageInfo: {
                url: window.location.href,
                referrer: document.referrer
            },
            interactionData: {
                firstClickTime: clickTimestamp,
                clickCount: buttonClickCount,
                clientId: getCookieValue('_ga') || 'no-ga'
            }
        };

        fetch(webhookUrl, {
            method: 'POST',
            mode: 'no-cors',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(enrichedData)
        }).then(function() {
            // Evento de envio do formulário bem-sucedido
            dataLayer.push({
                'event': 'whatsapp_crm',
                'whatsapp_name': name,
                'whatsapp_email': email,
                'whatsapp_phone': phone,
                'whatsapp_source': getTrafficSource(),
                'whatsapp_utm': getUTMParameters(),
                'whatsapp_url': window.location.href
            });

            var message = 'Olá! Me chamo ' + name + ' e gostaria de mais informações.';
            var whatsappUrl = 'https://wa.me/' + whatsappNumber + '?text=' + encodeURIComponent(message);
            window.open(whatsappUrl, '_blank');

            modal.style.display = 'none';
            // Reset do formulário e do botão após 3 segundos
            resetForm(form, submitButton);
        }).catch(function(error) {
            console.error('Erro ao enviar dados:', error);
            alert('Ocorreu um erro. Por favor, tente novamente.');
            
            // Reset do estado do botão em caso de erro
            setLoadingState(submitButton, false);
            
            // Evento de erro no envio do formulário
            dataLayer.push({
                'event': 'whatsapp_crm_error',
                'error_message': error.toString()
            });
        });
    });
})();
</script>
  1. Configure o acionamento:
    • Clique em “Acionamento”
    • Escolha “All Pages” ou crie um acionador específico
    • Selecione “DOM Ready” como tipo de acionamento
  2. Salve a tag e publique as alterações no GTM

Substitua no código:

  • XXXXX_SEU_NUMERO_WHATSAPP_XXXXX: seu número no formato internacional (ex: 5511999999999)
  • XXXXX_URL_DO_SEU_SCRIPT_GOOGLE_XXXXX: URL do Web App do Google Script que você criou

Pronto! O botão do WhatsApp estará funcionando em seu site após a publicação do GTM.

Obviamente que uma planilha não substitui uma plataforma completa de CRM, porém em alguns casos, os clientes não conseguem fazer a contratação imediata. Desta forma fizemos essa solução temporária para captação de todos os leads que chegam por whatsapp.

Fizemos manualmente algumas colunas com dados dos produtos, valores, qual foi o vendedor, qual status do atendimento. Esse fluxo é um exemplo. Vai depender do planejamento de pipeline comercial de cada empresa.

Compartilhe
Facebook
Twitter
LinkedIn

Categorias

Alguma
Dúvida?

let’s get to work