Pular para conteúdo

GET_TEMPLATES - Listar Templates

O que é este Node?

O GET_TEMPLATES é o node responsável por listar todos os templates de mensagem da conta via WhatsApp Business API.

Por que este Node existe?

Gestão de templates é essencial. O GET_TEMPLATES existe para:

  1. Consulta: Ver todos os templates criados
  2. Status: Verificar status de aprovação (PENDING, APPROVED, REJECTED)
  3. Sincronização: Manter sistema sincronizado com Meta
  4. Auditoria: Listar templates disponíveis
  5. Seleção: Escolher template correto para envio

Como funciona internamente?

Quando o GET_TEMPLATES é executado, o sistema:

  1. Valida businessAccountId: Requerido para listar templates
  2. Faz requisição GET: Busca todos os templates da conta
  3. Retorna lista: Array com todos os templates e seus detalhes
  4. Inclui status: PENDING, APPROVED, REJECTED, PAUSED, DISABLED
  5. Paginação opcional: Suporta paginação para muitos templates

Código interno (whatsapp-meta-executor.service.ts:672-687):

private async getTemplates(data: WhatsAppMetaNodeData): Promise<any> {
  if (!data.businessAccountId) {
    throw new Error('Business Account ID is required for getting templates');
  }

  const response: AxiosResponse = await axios.get(
    `${this.WHATSAPP_API_BASE}/${data.businessAccountId}/message_templates`,
    {
      headers: {
        'Authorization': `Bearer ${data.accessToken}`
      }
    }
  );

  return response.data;
}

Parâmetros

Campo Tipo Obrigatório Descrição
operation string Sim Deve ser "get_templates"
accessToken string Sim Token de acesso da WhatsApp Business API
businessAccountId string Sim ID da conta WhatsApp Business

Exemplo Completo: Listar Templates

{
  "name": "Listar Templates - GET_TEMPLATES",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "whatsapp_1",
      "type": "whatsapp_meta",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Listar Templates",
        "parameters": {
          "operation": "get_templates",
          "accessToken": "EAAxxxxxxxx",
          "businessAccountId": "123456789012345"
        }
      }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Processar Lista",
        "parameters": {
          "variableName": "templates",
          "value": "{{whatsapp_1.data}}"
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Exibir Total",
        "parameters": {
          "message": "📋 Total de templates: {{templates.data.length}}\n\nTemplates listados com sucesso!"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 900, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "whatsapp_1" },
    { "source": "whatsapp_1", "target": "variable_1" },
    { "source": "variable_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Exemplo 2: Filtrar Templates Aprovados

{
  "name": "Templates Aprovados - GET_TEMPLATES",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início" }
    },
    {
      "id": "whatsapp_1",
      "type": "whatsapp_meta",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Listar Templates",
        "parameters": {
          "operation": "get_templates",
          "accessToken": "EAAxxxxxxxx",
          "businessAccountId": "123456789012345"
        }
      }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Filtrar Aprovados",
        "parameters": {
          "variableName": "approved",
          "value": "{{whatsapp_1.data.filter(t => t.status === 'APPROVED')}}"
        }
      }
    },
    {
      "id": "message_1",
      "type": "message",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Exibir Resultado",
        "parameters": {
          "message": "✅ Templates Aprovados: {{approved.length}}\n⏳ Aguardando Aprovação: {{whatsapp_1.data.filter(t => t.status === 'PENDING').length}}\n❌ Rejeitados: {{whatsapp_1.data.filter(t => t.status === 'REJECTED').length}}"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 900, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "whatsapp_1" },
    { "source": "whatsapp_1", "target": "variable_1" },
    { "source": "variable_1", "target": "message_1" },
    { "source": "message_1", "target": "end_1" }
  ]
}

Resposta do Node

{
  "data": [
    {
      "id": "1234567890",
      "name": "order_confirmation",
      "language": "pt_BR",
      "status": "APPROVED",
      "category": "UTILITY",
      "components": [
        {
          "type": "HEADER",
          "format": "TEXT",
          "text": "Pedido Confirmado"
        },
        {
          "type": "BODY",
          "text": "Olá {{1}}, seu pedido {{2}} foi confirmado!"
        },
        {
          "type": "FOOTER",
          "text": "Obrigado pela preferência"
        }
      ]
    },
    {
      "id": "0987654321",
      "name": "welcome_message",
      "language": "pt_BR",
      "status": "PENDING",
      "category": "MARKETING",
      "components": [...]
    },
    {
      "id": "5555555555",
      "name": "payment_reminder",
      "language": "pt_BR",
      "status": "REJECTED",
      "category": "UTILITY",
      "rejected_reason": "INVALID_FORMAT",
      "components": [...]
    }
  ],
  "paging": {
    "cursors": {
      "before": "...",
      "after": "..."
    }
  }
}

Status de Templates

APPROVED ✅

Template aprovado e pronto para uso.

PENDING ⏳

Aguardando aprovação do Meta (24-48h).

REJECTED ❌

Rejeitado pelo Meta. Verifique rejected_reason e corrija.

PAUSED ⏸️

Pausado por baixa qualidade ou reclamações.

DISABLED 🚫

Desabilitado (violou políticas).

Motivos de Rejeição

  • INVALID_FORMAT: Formato incorreto
  • INCORRECT_CATEGORY: Categoria errada
  • PROHIBITED_CONTENT: Conteúdo proibido
  • INVALID_LANGUAGE: Idioma não corresponde ao texto
  • ABUSIVE_CONTENT: Conteúdo abusivo ou spam

Boas Práticas

SIM: - Liste templates periodicamente para verificar status - Filtre por status para encontrar aprovados/rejeitados - Armazene lista em cache para não consultar sempre - Monitore templates PAUSED (podem ter problema de qualidade) - Revise templates REJECTED e corrija antes de reenviar

NÃO: - Não consulte a cada envio (use cache) - Não ignore templates REJECTED (corrija o problema) - Não continue usando templates PAUSED sem investigar - Não assuma que template criado está aprovado

Caso de Uso: Dashboard de Templates

{
  "name": "Dashboard Templates",
  "nodes": [
    {
      "id": "start_1",
      "type": "start",
      "position": { "x": 100, "y": 100 },
      "data": { "label": "Início Cron Job" }
    },
    {
      "id": "whatsapp_1",
      "type": "whatsapp_meta",
      "position": { "x": 300, "y": 100 },
      "data": {
        "label": "Listar Templates",
        "parameters": {
          "operation": "get_templates",
          "accessToken": "EAAxxxxxxxx",
          "businessAccountId": "123456789012345"
        }
      }
    },
    {
      "id": "variable_1",
      "type": "variable",
      "position": { "x": 500, "y": 100 },
      "data": {
        "label": "Calcular Estatísticas",
        "parameters": {
          "variableName": "stats",
          "value": {
            "total": "{{whatsapp_1.data.length}}",
            "approved": "{{whatsapp_1.data.filter(t => t.status === 'APPROVED').length}}",
            "pending": "{{whatsapp_1.data.filter(t => t.status === 'PENDING').length}}",
            "rejected": "{{whatsapp_1.data.filter(t => t.status === 'REJECTED').length}}",
            "paused": "{{whatsapp_1.data.filter(t => t.status === 'PAUSED').length}}"
          }
        }
      }
    },
    {
      "id": "notification_1",
      "type": "message",
      "position": { "x": 700, "y": 100 },
      "data": {
        "label": "Enviar Relatório",
        "parameters": {
          "message": "📊 Relatório de Templates\n\n✅ Aprovados: {{stats.approved}}\n⏳ Pendentes: {{stats.pending}}\n❌ Rejeitados: {{stats.rejected}}\n⏸️ Pausados: {{stats.paused}}\n\n📈 Total: {{stats.total}}"
        }
      }
    },
    {
      "id": "end_1",
      "type": "end",
      "position": { "x": 900, "y": 100 },
      "data": { "label": "Fim" }
    }
  ],
  "edges": [
    { "source": "start_1", "target": "whatsapp_1" },
    { "source": "whatsapp_1", "target": "variable_1" },
    { "source": "variable_1", "target": "notification_1" },
    { "source": "notification_1", "target": "end_1" }
  ]
}

Dicas

💡 Cache: Armazene lista de templates em cache (Redis) por 1 hora 💡 Monitoramento: Configure alerta quando template for REJECTED 💡 Sincronização: Execute GET_TEMPLATES diariamente para manter sincronizado 💡 Filtros: Filtre por status, categoria ou idioma conforme necessidade 💡 Paginação: Use cursors para paginar se tiver muitos templates (> 100)

Próximo Node

CREATE_TEMPLATE - Criar novo template → SEND_TEMPLATE - Enviar template aprovado