<?php
require_once __DIR__ . '/../config/databaseNexa.php';
/**
* CCMBR - Webhook da WhatsApp Cloud API (Meta)
* Arquivo: /api/webhook_whatsapp.php
*
* GET → verificação do webhook (hub.challenge)
* POST → eventos (mensagens recebidas, status de entrega, etc.)
*
* Fluxo por mensagem de texto:
* 1. Identifica telefone do visitante (`from`)
* 2. Identifica telefone da IA (`display_phone_number`)
* 3. Extrai contexto (livro/capítulo) do texto
* 4. Chama atendimento.php acao=registrar_atendimento → grava linha em `atendimento`
* 5. Extrai nome/email do texto e chama acao=atualizar_visitante → enriquece `visitante`
* 6. Devolve 200 para a Meta (evita reenvios)
*
* Idempotência: usa o `msg.id` da Meta como idempotency_key.
*/
@ini_set('pcre.jit', '0');
header('Content-Type: application/json; charset=utf-8');
// ===================== CONFIG =====================
$verifyToken = defined('WHATSAPP_VERIFY_TOKEN')
? WHATSAPP_VERIFY_TOKEN
: (getenv('WHATSAPP_VERIFY_TOKEN') ?: '');
$apiToken = defined('CCMBR_API_TOKEN')
? CCMBR_API_TOKEN
: (getenv('CCMBR_API_TOKEN') ?: '');
$apiUrl = defined('CCMBR_API_URL')
? CCMBR_API_URL
: 'https://www.ccmbr.com.br/api/atendimento.php';
// ===================== HELPERS =====================
function normalizarTelefoneWpp($from) {
if (!is_string($from) || $from === '') return '';
$from = preg_replace('/@[a-z.]+$/i', '', $from);
$from = preg_replace('/\D+/', '', $from);
if ($from === '') return '';
if (strlen($from) >= 12 && $from[0] === '0') {
$from = ltrim($from, '0');
}
if (strlen($from) === 10 || strlen($from) === 11) {
$from = '55' . $from;
}
if (preg_match('/^55(0{8,9}|1{8,9})$/', $from)) return '';
if (strlen($from) < 12 || strlen($from) > 13) return '';
return $from;
}
function extrairContextoDaMensagem($texto) {
$idLivro = null;
$idArtigo = null;
$tituloRef = null;
if (preg_match('/livro\s+ID\s+(\d+)/i', $texto, $m)) {
$idLivro = (int)$m[1];
}
if (preg_match('/cap[íi]tulo\s+ID\s+(\d+)\s*\(([^)]+)\)/iu', $texto, $m)) {
$idArtigo = (int)$m[1];
$tituloRef = trim($m[2]);
}
return array(
'id_livro' => $idLivro,
'id_artigo' => $idArtigo,
'titulo_referencia' => $tituloRef,
);
}
// ⬅️ NOVO: extrai nome e email das mensagens do visitante
function extrairDadosPessoais($texto) {
$dados = array();
$texto = trim((string)$texto);
if ($texto === '') return $dados;
// Nome — após gatilhos claros ("meu nome é", "me chamo", "sou o", etc.)
if (preg_match(
'/(?:meu\s+nome\s+(?:é|e)|me\s+chamo|aqui\s+(?:é|e)\s+o?|'
. 'sou\s+(?:o|a)|pode\s+me\s+chamar\s+de)\s+'
. '([A-Za-zÁÀÂÃÉÊÍÓÔÕÚÇáàâãéêíóôõúç]+'
. '(?:\s+(?:d[aeo]s?\s+)?[A-Za-zÁÀÂÃÉÊÍÓÔÕÚÇáàâãéêíóôõúç]+){0,5})/iu',
$texto, $m
)) {
$nome = rtrim(trim($m[1]), ".,;:!?");
if (mb_strlen($nome) >= 2 && mb_strlen($nome) <= 80) {
$dados['nome'] = $nome;
}
}
// Email — primeiro válido
if (preg_match('/[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}/i', $texto, $m)) {
$dados['email'] = strtolower($m[0]);
}
return $dados;
}
/**
* Chama o atendimento.php via HTTP com o token.
* Retorna [statusHttp, array|null].
*/
function chamarApiAtendimento($apiUrl, $apiToken, $payload) {
if (!function_exists('curl_init')) {
error_log('Webhook: cURL indisponível.');
return array(0, null);
}
$ch = curl_init($apiUrl);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept: application/json',
'X-CCMBR-Token: ' . $apiToken,
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
));
$resp = curl_exec($ch);
$statusHttp = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($resp === false) {
error_log('Webhook: cURL erro → ' . $err);
return array(0, null);
}
return array($statusHttp, json_decode($resp, true));
}
// ===================== GET — verificação =====================
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$mode = $_GET['hub_mode'] ?? $_GET['hub.mode'] ?? '';
$token = $_GET['hub_verify_token'] ?? $_GET['hub.verify_token'] ?? '';
$challenge = $_GET['hub_challenge'] ?? $_GET['hub.challenge'] ?? '';
if ($mode === 'subscribe' && $verifyToken !== '' && hash_equals($verifyToken, (string)$token)) {
http_response_code(200);
echo $challenge;
exit;
}
http_response_code(403);
echo 'Forbidden';
exit;
}
// ===================== POST — eventos =====================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(array('ok' => false, 'erro' => 'Método não permitido.'));
exit;
}
$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);
if (!is_array($payload)) {
http_response_code(200);
echo json_encode(array('ok' => true, 'ignorado' => 'payload inválido'));
exit;
}
if ($apiToken === '') {
error_log('Webhook: CCMBR_API_TOKEN não configurado.');
http_response_code(200);
echo json_encode(array('ok' => true, 'ignorado' => 'token interno ausente'));
exit;
}
$processados = 0;
$ignorados = 0;
foreach (($payload['entry'] ?? array()) as $entry) {
foreach (($entry['changes'] ?? array()) as $change) {
$value = $change['value'] ?? array();
if (empty($value['messages']) || !is_array($value['messages'])) {
$ignorados++;
continue;
}
$msg = $value['messages'][0];
$tipo = $msg['type'] ?? '';
if ($tipo !== 'text') {
$ignorados++;
continue;
}
$from = $msg['from'] ?? '';
$texto = $msg['text']['body'] ?? '';
$msgId = $msg['id'] ?? '';
$foneIa = $value['metadata']['display_phone_number'] ?? '';
$telVisitante = normalizarTelefoneWpp($from);
$telIa = normalizarTelefoneWpp($foneIa);
// ⬅️ Log de diagnóstico
error_log(sprintf(
'[WPP] from=%s | display=%s | telVisitante=%s | telIa=%s | msgId=%s | texto=%s',
$from, $foneIa, $telVisitante, $telIa, $msgId, mb_substr($texto, 0, 80)
));
if ($telVisitante === '' || $telIa === '') {
error_log('Webhook: telefone inválido. from=' . var_export($from, true) . ' ia=' . var_export($foneIa, true));
$ignorados++;
continue;
}
if ($msgId === '') {
error_log('Webhook: msg.id ausente — impossível garantir idempotência.');
$ignorados++;
continue;
}
$ctx = extrairContextoDaMensagem($texto);
$payloadInterno = array(
'acao' => 'registrar_atendimento',
'fone_visitante' => $telVisitante,
'fone_ia' => $telIa,
'chamada' => $texto,
'id_artigo' => $ctx['id_artigo'],
'titulo_referencia' => $ctx['titulo_referencia'],
'idempotency_key' => 'wpp-' . $msgId,
);
list($status, $resultado) = chamarApiAtendimento($apiUrl, $apiToken, $payloadInterno);
if ($status >= 200 && $status < 300 && is_array($resultado) && !empty($resultado['ok'])) {
$processados++;
error_log(sprintf(
'[WPP] OK registrar: msgId=%s tel=%s visitante=%s (%s) atendimento=%s',
$msgId,
$telVisitante,
$resultado['id_visitante'] ?? '?',
!empty($resultado['visitante_criado']) ? 'criado' : 'existente',
$resultado['id_atendimento'] ?? '?'
));
// ⬅️ NOVO: enriquecer visitante com dados extraídos da mensagem
$dadosPessoais = extrairDadosPessoais($texto);
if (!empty($dadosPessoais)) {
list($sUp, $rUp) = chamarApiAtendimento($apiUrl, $apiToken, array(
'acao' => 'atualizar_visitante',
'telefone' => $telVisitante,
'campos' => $dadosPessoais,
));
error_log(sprintf(
'[WPP] atualizar_visitante tel=%s campos=%s status=%d resp=%s',
$telVisitante,
implode(',', array_keys($dadosPessoais)),
$sUp,
json_encode($rUp)
));
}
} else {
error_log(sprintf(
'[WPP] FALHA registrar: msgId=%s status=%s resp=%s',
$msgId, $status, json_encode($resultado)
));
}
}
}
http_response_code(200);
echo json_encode(array(
'ok' => true,
'processados' => $processados,
'ignorados' => $ignorados,
));
Nilton Romani