Canal de WhatsApp: Configuração e Templates
💬 Comunicação instantânea: Integre WhatsApp Business API para notificações de alta abertura
WhatsApp tem taxa de abertura de ~98%. Este guia cobre:
- Configurar 360dialog como BSP
- Criar e aprovar templates
- Enviar mensagens de sessão e template
- Configurar webhooks para receber respostas
O que é um BSP?
BSP (Business Solution Provider) é um parceiro da Meta que fornece acesso à API oficial do WhatsApp Business.
A Notifica integra com 360dialog — BSP líder no Brasil com preços competitivos.
Configurando 360dialog
Passo 1: Criar conta 360dialog
- Acesse 360dialog.com
- Crie sua conta e faça verificação business
- Adicione número de telefone (pode ser fixo ou móvel)
- Obtenha sua API Key do 360dialog
Passo 2: Configurar na Notifica
curl -X POST https://app.usenotifica.com.br/v1/channels \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"channel": "whatsapp",
"provider": "360dialog",
"config": {
"api_key": "sua_api_key_360dialog",
"phone_number": "5511999999999",
"business_name": "Minha Empresa"
}
}'
Resposta:
{
"id": "ch_whatsapp_001",
"channel": "whatsapp",
"provider": "360dialog",
"status": "active",
"phone_number": "5511999999999",
"quality_rating": "GREEN",
"created_at": "2024-01-15T10:00:00Z"
}
Testar configuração
curl -X POST https://app.usenotifica.com.br/v1/channels/whatsapp/test \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"to": "5511987654321",
"type": "text",
"content": "Teste de configuração WhatsApp! ✅"
}'
Templates do WhatsApp
WhatsApp Business API exige templates pré-aprovados para iniciar conversas. Existem dois tipos:
| Tipo | Quando usar | Precisa aprovação? |
|---|---|---|
| Template | Iniciar conversa (24h desde última mensagem) | Sim |
| Session | Responder dentro da janela de 24h | Não |
Criando templates
Via Dashboard (recomendado)
- Vá em Canais → WhatsApp → Templates
- Clique em Novo Template
- Preencha:
- Nome:
order_confirmation(sem espaços) - Categoria:
TRANSACTIONALouMARKETING - Idioma:
pt_BR - Conteúdo: Veja exemplos abaixo
- Nome:
Via API
curl -X POST https://app.usenotifica.com.br/v1/templates \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"name": "order_confirmation",
"category": "TRANSACTIONAL",
"language": "pt_BR",
"channel": "whatsapp",
"components": [
{
"type": "HEADER",
"format": "TEXT",
"text": "Pedido #{{1}} Confirmado! 🎉"
},
{
"type": "BODY",
"text": "Olá {{1}}, seu pedido foi confirmado!\n\n📦 Produtos:\n{{2}}\n\n💰 Total: R$ {{3}}\n\n🚚 Entrega prevista: {{4}}"
},
{
"type": "FOOTER",
"text": "Dúvidas? Responda esta mensagem"
},
{
"type": "BUTTONS",
"buttons": [
{
"type": "URL",
"text": "Acompanhar Pedido",
"url": "https://loja.com.br/pedidos/{{1}}"
}
]
}
]
}'
Resposta:
{
"id": "tmpl_wa_001",
"name": "order_confirmation",
"status": "PENDING",
"whatsapp_template_id": "123456789",
"approval_status": "pending_review"
}
⚠️ Aprovação: Pode levar de minutos a 24 horas. Status será APPROVED ou REJECTED.
Exemplos de templates úteis
Código de verificação (OTP)
Nome: verification_code
Categoria: AUTHENTICATION
Conteúdo:
Seu código de verificação é: *{{1}}*
Válido por 5 minutos.
Não compartilhe com ninguém.
Confirmação de agendamento
Nome: appointment_confirmation
Categoria: TRANSACTIONAL
Header: 📅 Lembrete de Consulta
Body: Olá {{1}}, sua consulta com {{2}} está confirmada.
📅 Data: {{3}}
🕐 Horário: {{4}}
📍 Local: {{5}}
Botões: [Confirmar Presença] [Remarcar]
Alerta de pagamento
Nome: payment_reminder
Categoria: TRANSACTIONAL
Header: 💳 Pagamento Pendente
Body: Olá {{1}}, seu pagamento de *R$ {{2}}* vence amanhã.
Evite juros pagando até {{3}}.
Botões: [Pagar Agora] [Ver Fatura]
Enviando mensagens
Com template aprovado
curl -X POST https://app.usenotifica.com.br/v1/notifications \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"to": {
"phone": "+5511987654321"
},
"channel": "whatsapp",
"template": "order_confirmation",
"data": {
"order_id": "12345",
"customer_name": "Fernanda",
"items": "1x Tênis Nike\n2x Meia Adidas",
"total": "299,90",
"delivery_date": "20/01"
}
}'
Mensagem de sessão (resposta rápida)
Se o usuário enviou mensagem nos últimos 24h:
curl -X POST https://app.usenotifica.com.br/v1/notifications \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"to": {
"phone": "+5511987654321"
},
"channel": "whatsapp",
"content": "Claro! Seu pedido está a caminho. Código de rastreio: BR123456789"
}'
Código Node.js
class WhatsAppService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://app.usenotifica.com.br/v1';
}
async sendTemplate(phone, template, data) {
const response = await fetch(`${this.baseUrl}/notifications`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
to: { phone },
channel: 'whatsapp',
template,
data
})
});
return response.json();
}
async sendText(phone, content) {
// Só funciona dentro da janela de 24h
const response = await fetch(`${this.baseUrl}/notifications`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
to: { phone },
channel: 'whatsapp',
content
})
});
return response.json();
}
async sendOTP(phone, code) {
return this.sendTemplate(phone, 'verification_code', { code });
}
async sendOrderConfirmation(phone, orderData) {
return this.sendTemplate(phone, 'order_confirmation', {
order_id: orderData.id,
customer_name: orderData.customerName,
items: orderData.items.map(i => `${i.qty}x ${i.name}`).join('\n'),
total: orderData.total.toFixed(2).replace('.', ','),
delivery_date: orderData.deliveryDate
});
}
}
// Uso
const wa = new WhatsAppService(process.env.NOTIFICA_API_KEY);
// Enviar OTP
await wa.sendOTP('+5511987654321', '583921');
// Confirmar pedido
await wa.sendOrderConfirmation('+5511987654321', {
id: '12345',
customerName: 'Roberto',
items: [{ qty: 1, name: 'Tênis Nike' }],
total: 299.90,
deliveryDate: '20/01'
});
Código Python
class WhatsAppService:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = 'https://app.usenotifica.com.br/v1'
def send_template(self, phone: str, template: str, data: dict):
response = requests.post(
f'{self.base_url}/notifications',
headers={'Authorization': f'Bearer {self.api_key}'},
json={
'to': {'phone': phone},
'channel': 'whatsapp',
'template': template,
'data': data
}
)
response.raise_for_status()
return response.json()
def send_otp(self, phone: str, code: str):
return self.send_template(phone, 'verification_code', {'1': code})
def send_order_confirmation(self, phone: str, order: dict):
items_text = '\n'.join([f"{i['qty']}x {i['name']}" for i in order['items']])
return self.send_template(phone, 'order_confirmation', {
'1': order['customer_name'],
'2': items_text,
'3': f"{order['total']:.2f}".replace('.', ','),
'4': order['delivery_date']
})
# Uso
wa = WhatsAppService(os.getenv('NOTIFICA_API_KEY'))
wa.send_otp('+5511987654321', '583921')
Configurando webhooks (receber mensagens)
Para receber respostas dos usuários:
1. Configurar endpoint de webhook
curl -X POST https://app.usenotifica.com.br/v1/webhooks \
-H "Authorization: Bearer nk_live_sua_chave" \
-H "Content-Type: application/json" \
-d '{
"url": "https://api.empresa.com.br/webhooks/whatsapp",
"events": ["whatsapp.message.received", "whatsapp.message.status"],
"secret": "whsec_seu_secret_aqui"
}'
2. Receber e processar mensagens
// Express.js
const crypto = require('crypto');
app.post('/webhooks/whatsapp', express.json(), (req, res) => {
// Verificar assinatura
const signature = req.headers['x-notifica-signature'];
const payload = JSON.stringify(req.body);
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== `sha256=${expected}`) {
return res.status(401).send('Unauthorized');
}
const event = req.body;
switch (event.type) {
case 'whatsapp.message.received':
handleIncomingMessage(event.data);
break;
case 'whatsapp.message.status':
handleStatusUpdate(event.data);
break;
}
res.status(200).send('OK');
});
async function handleIncomingMessage(data) {
const { from, text, timestamp } = data;
console.log(`Mensagem de ${from}: ${text}`);
// Salvar no banco
await db.messages.create({
phone: from,
content: text,
direction: 'inbound',
timestamp
});
// Processar com IA ou bot
const reply = await generateReply(text);
// Responder (se dentro da janela de 24h)
await wa.sendText(from, reply);
}
Métricas e Quality Rating
Ver qualidade do número
curl https://app.usenotifica.com.br/v1/channels/whatsapp \
-H "Authorization: Bearer nk_live_sua_chave"
Quality Rating:
- 🟢 GREEN — Bom, mantenha assim
- 🟡 YELLOW — Atenção, taxa de bloqueio alta
- 🔴 RED — Crítico, risco de suspensão
Melhorar qualidade
- Use double opt-in — só envie para quem permitiu
- Templates claros — usuários devem saber quem é você
- Facilite opt-out — inclua opção de parar de receber
- Evite spam — não envie muitas mensagens seguidas
FAQ
Q: Posso usar meu número pessoal?
A: Não recomendado. Use número business dedicado.
Q: Quanto custa?
A: 360dialog cobra ~R$150/mês + custo por conversação. Veja preços atualizados no site deles.
Q: Posso enviar imagens/vídeos?
A: Sim! Templates suportam HEADER com imagem, vídeo ou documento.
Q: Template foi rejeitado, o que fazer?
A: Leia o motivo na resposta. Comum: linguagem promocional em template transacional, ou falta de clareza.
Q: Quantos templates posso ter?
A: Limitado pela Meta, geralmente 100-250 por conta.
Q: Posso usar outro BSP além de 360dialog?
A: Atualmente só 360dialog é suportado nativamente. Para outros, use SMTP relay ou API direta.
Próximo passo
Para envios em massa e marketing, configure o canal de SMS:
- Twilio — Cobertura global
- Zenvia — Especialista em Brasil
- Provedor Customizado — Qualquer provedor HTTP
- Compliance SMS — LGPD e boas práticas