Pular para conteúdo

SEND_TEMPLATE - Enviar Template

O que é este Node?

O SEND_TEMPLATE é o node responsável por enviar mensagens template pré-aprovadas via WhatsApp Business API.

Por que este Node existe?

Templates são mensagens oficiais aprovadas. O SEND_TEMPLATE existe para:

  1. Mensagens fora da janela 24h: Enviar notificações após 24h da última mensagem do usuário
  2. Comunicação proativa: Iniciar conversas sem aguardar mensagem do usuário
  3. Marketing aprovado: Enviar promoções dentro das regras do WhatsApp
  4. Notificações: Alertas de pedidos, cobranças, compromissos
  5. Compliance: Seguir regras de uso do WhatsApp Business

Como funciona internamente?

Quando o SEND_TEMPLATE é executado, o sistema:

  1. Valida template: Verifica templateName e templateLanguage
  2. Prepara parâmetros: Substitui variáveis dinâmicas
  3. Constrói payload: Cria objeto tipo 'template'
  4. Envia para API: POST com template aprovado
  5. Retorna message_id: Confirma envio

Código interno (whatsapp-meta-executor.service.ts:546-593):

private async sendTemplate(data: WhatsAppMetaNodeData): Promise<any> {
  const template: any = {
    name: data.templateName,
    language: {
      code: data.templateLanguage
    }
  };

  if (data.templateParameters && data.templateParameters.length > 0) {
    template.components = [
      {
        type: 'body',
        parameters: data.templateParameters.map(param => {
          switch (param.type) {
            case 'text':
              return { type: 'text', text: param.text };
            case 'currency':
              return { type: 'currency', currency: param.currency };
            case 'date_time':
              return { type: 'date_time', date_time: param.date_time };
            default:
              return { type: 'text', text: param.text };
          }
        })
      }
    ];
  }

  const payload = {
    messaging_product: 'whatsapp',
    to: data.recipientPhone,
    type: 'template',
    template
  };

  const response: AxiosResponse = await axios.post(
    `${this.WHATSAPP_API_BASE}/${data.phoneNumberId}/messages`,
    payload,
    {
      headers: {
        'Authorization': `Bearer ${data.accessToken}`,
        'Content-Type': 'application/json'
      }
    }
  );

  return response.data;
}

Parâmetros

Campo Tipo Obrigatório Descrição
operation string Sim Deve ser "send_template"
accessToken string Sim Token de acesso da WhatsApp Business API
phoneNumberId string Sim ID do número WhatsApp Business
recipientPhone string Sim Número do destinatário
templateName string Sim Nome do template aprovado
templateLanguage string Sim Código do idioma (ex: pt_BR, en_US)
templateParameters array Não Parâmetros dinâmicos do template

Exemplo 1: Confirmação de Pedido

{
  "name": "Template Confirmação Pedido",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Dados do Pedido",
        "parameters": {
          "variableName": "order",
          "value": {
            "customerPhone": "5511999999999",
            "customerName": "Maria Silva",
            "orderId": "12345",
            "total": "R$ 299,90"
          }
        }
      }
    },
    {
      "id": "whatsapp_1",
      "type": "whatsapp_meta",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Enviar Template",
        "parameters": {
          "operation": "send_template",
          "accessToken": "EAAxxxxxxxx",
          "phoneNumberId": "123456789",
          "recipientPhone": "{{order.customerPhone}}",
          "templateName": "order_confirmation",
          "templateLanguage": "pt_BR",
          "templateParameters": [
            {
              "type": "text",
              "text": "{{order.customerName}}"
            },
            {
              "type": "text",
              "text": "{{order.orderId}}"
            },
            {
              "type": "text",
              "text": "{{order.total}}"
            }
          ]
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "variable_1" },
    { "source": "variable_1", "target": "whatsapp_1" },
    { "source": "whatsapp_1", "target": "end_1" }
  ]
}

Exemplo 2: Lembrete de Pagamento

{
  "name": "Template Lembrete Pagamento",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Dados Cobrança",
        "parameters": {
          "variableName": "billing",
          "value": {
            "customerPhone": "5511888888888",
            "customerName": "João Santos",
            "invoiceNumber": "FATURA-456",
            "dueDate": "31/01/2025",
            "amount": "R$ 150,00"
          }
        }
      }
    },
    {
      "id": "whatsapp_1",
      "type": "whatsapp_meta",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Enviar Template",
        "parameters": {
          "operation": "send_template",
          "accessToken": "EAAxxxxxxxx",
          "phoneNumberId": "123456789",
          "recipientPhone": "{{billing.customerPhone}}",
          "templateName": "payment_reminder",
          "templateLanguage": "pt_BR",
          "templateParameters": [
            {
              "type": "text",
              "text": "{{billing.customerName}}"
            },
            {
              "type": "text",
              "text": "{{billing.invoiceNumber}}"
            },
            {
              "type": "text",
              "text": "{{billing.dueDate}}"
            },
            {
              "type": "text",
              "text": "{{billing.amount}}"
            }
          ]
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 700, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "variable_1" },
    { "source": "variable_1", "target": "whatsapp_1" },
    { "source": "whatsapp_1", "target": "end_1" }
  ]
}

Tipos de Parâmetros

Text

{
  "type": "text",
  "text": "Valor do parâmetro"
}

Currency

{
  "type": "currency",
  "currency": {
    "fallback_value": "R$ 100,00",
    "code": "BRL",
    "amount_1000": 100000
  }
}

Date/Time

{
  "type": "date_time",
  "date_time": {
    "fallback_value": "31/01/2025"
  }
}

Resposta do Node

{
  "messaging_product": "whatsapp",
  "contacts": [
    {
      "input": "5511999999999",
      "wa_id": "5511999999999"
    }
  ],
  "messages": [
    {
      "id": "wamid.HBgNNTUxMTk5OTk5OTk5ORUCABIYFjNBMzYxNzQyQ0JGRjREMTU0QzFEAA=="
    }
  ]
}

Boas Práticas

SIM: - Crie templates claros e aprovados pelo WhatsApp - Use parâmetros dinâmicos para personalização - Respeite categorias (MARKETING, UTILITY, AUTHENTICATION) - Teste templates antes de usar em produção - Use templateLanguage correto (pt_BR, en_US, etc)

NÃO: - Não use templates não aprovados - Não envie marketing sem opt-in do usuário - Não abuse de templates promocionais - Não use template errado para categoria

Dicas

💡 Aprovação: Templates precisam ser aprovados pelo Meta (24-48h) 💡 Categorias: UTILITY tem menos restrições que MARKETING 💡 Variáveis: Use {{1}}, {{2}} no template e passe valores em ordem 💡 Idioma: templateLanguage deve corresponder ao idioma do template criado 💡 Janela 24h: Após template, você tem 24h para enviar mensagens livres

Próximo Node

SEND_INTERACTIVE - Enviar mensagens interativas → CREATE_TEMPLATE - Criar novos templates → GET_TEMPLATES - Listar templates aprovados