<?php
/**
* CCMBR - API CENTRALIZADA DE ATENDIMENTO DAS IAs
*
* Arquivo: /api/atendimento.php
* PHP: 7.4+
*
* Tabelas utilizadas:
• - visitante
• - atendente_ia
• - atendimento
*
* GET:
• ?fone_visitante=5517996355697&fone_ia=5517991117550
*
* POST JSON:
• {
• "fone_visitante": "5517996355697",
• "fone_ia": "5517991117550",
• "chamada": "Título do artigo",
• "id_artigo": 123,
• "titulo_referencia": "Título de referência"
• }
*
* Autenticação:
• Header: X-CCMBR-Token
*/
// ============================================================
// 1. CONFIGURAÇÃO
// ============================================================
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__. '/../config/databaseNexa.php';
$tokenEsperado = defined('CCMBR_API_TOKEN')
? CCMBR_API_TOKEN
: (getenv('CCMBR_API_TOKEN') ?: '');
// CORS restrito ao domínio CCMBR.
$origem = $_SERVER['HTTP_ORIGIN'] ?? '';
$origensPermitidas = array(
'https://ccmbr.com.br',
'https://www.ccmbr.com.br'
);
if (in_array($origem, $origensPermitidas, true)) {
header('Access-Control-Allow-Origin: ' . $origem);
header('Vary: Origin');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-CCMBR-Token');
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// ============================================================
// 2. FUNÇÕES
// ============================================================
function resposta($codigo, $dados)
{
http_response_code($codigo);
echo json_encode(
$dados,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
exit;
}
function normalizarTelefone($telefone)
{
return preg_replace('/\D+/', '', (string) $telefone);
}
function telefoneSql($campo)
{
return "REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
COALESCE($campo, ''),
'+', ''
),
'-', ''
),
' ', ''
),
'(', ''
),
')', ''
),
'.', ''
)";
}
// ============================================================
// 3. AUTENTICAÇÃO
// ============================================================
$tokenRecebido = $_SERVER['HTTP_X_CCMBR_TOKEN'] ?? '';
if ($tokenRecebido === '' && function_exists('getallheaders')) {
$headers = getallheaders();
foreach ($headers as $nome => $valor) {
if (strtolower($nome) === 'x-ccmbr-token') {
$tokenRecebido = $valor;
break;
}
}
}
if ($tokenEsperado === '') {
resposta(500, array(
'ok' => false,
'erro' => 'Token não configurado no servidor.'
));
}
if (!hash_equals($tokenEsperado, (string) $tokenRecebido)) {
resposta(401, array(
'ok' => false,
'erro' => 'Não autorizado. Token inválido.'
));
}
// ============================================================
// 4. CONEXÃO COM O BANCO
// ============================================================
try {
$pdo = Database::connect();
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$pdo->setAttribute(
PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC
);
} catch (Exception $e) {
error_log('API CCMBR - Conexão: ' . $e->getMessage());
resposta(500, array(
'ok' => false,
'erro' => 'Erro ao conectar ao banco de dados.'
));
}
// ============================================================
// 5. MÉTODO HTTP
// ============================================================
$metodo = $_SERVER['REQUEST_METHOD'];
// ============================================================
// 6. GET - CONSULTA DE ATENDIMENTO E HISTÓRICO
// ============================================================
if ($metodo === 'GET') {
$foneVisitante = trim($_GET['fone_visitante'] ?? '');
$foneIa = trim($_GET['fone_ia'] ?? '');
$telVisitante = normalizarTelefone($foneVisitante);
$telIa = normalizarTelefone($foneIa);
if ($telVisitante === '' && $telIa === '') {
resposta(400, array(
'ok' => false,
'erro' => 'Informe fone_visitante ou fone_ia.'
));
}
try {
$atendente = null;
$visitante = null;
$historico = array();
// ----------------------------------------------------
// 6.1 IDENTIFICA A IA
// ----------------------------------------------------
if ($telIa !== '') {
$sql = "
SELECT
id,
codigo,
nome,
nomeExibicao,
telefone,
telefoneAlternativo,
situacao,
ordem
FROM atendente_ia
WHERE " . telefoneSql('telefone') . " = :telefone
OR " . telefoneSql('telefoneAlternativo') . " = :telefoneAlternativo
LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telIa,
':telefoneAlternativo' => $telIa
));
$atendente = $stmt->fetch() ?: null;
}
// ----------------------------------------------------
// 6.2 IDENTIFICA O VISITANTE
// ----------------------------------------------------
if ($telVisitante !== '') {
$sql = "
SELECT
id,
nome,
telefone,
email,
id_usuario,
situacao,
dataCadastro,
atualizadoEm,
dataConversao
FROM visitante
WHERE " . telefoneSql('telefone') . " = :telefone
LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telVisitante
));
$visitante = $stmt->fetch() ?: null;
}
// ----------------------------------------------------
// 6.3 HISTÓRICO COMPARTILHADO DO VISITANTE
// ----------------------------------------------------
if ($telVisitante !== '') {
$sql = "
SELECT
a.id,
a.telefone_visitante,
a.telefone_ia,
a.id_artigo,
a.titulo_referencia,
a.chamada,
a.criadoEm,
a.atualizadoEm,
(
SELECT
COALESCE(
NULLIF(at.nomeExibicao, ''),
at.nome
)
FROM atendente_ia at
WHERE " . telefoneSql('at.telefone') . " =
" . telefoneSql('a.telefone_ia') . "
OR " . telefoneSql('at.telefoneAlternativo') . " =
" . telefoneSql('a.telefone_ia') . "
LIMIT 1
) AS atendente_nome,
(
SELECT at.codigo
FROM atendente_ia at
WHERE " . telefoneSql('at.telefone') . " =
" . telefoneSql('a.telefone_ia') . "
OR " . telefoneSql('at.telefoneAlternativo') . " =
" . telefoneSql('a.telefone_ia') . "
LIMIT 1
) AS atendente_codigo
FROM atendimento a
WHERE " . telefoneSql('a.telefone_visitante') . " = :telefone
ORDER BY a.criadoEm DESC
LIMIT 50
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telVisitante
));
$historico = $stmt->fetchAll();
}
resposta(200, array(
'ok' => true,
'atendente' => $atendente,
'visitante' => $visitante,
'total_historico' => count($historico),
'historico' => $historico
));
} catch (PDOException $e) {
error_log('API CCMBR GET: ' . $e->getMessage());
resposta(500, array(
'ok' => false,
'erro' => 'Erro ao consultar os atendimentos.'
));
}
}
// ============================================================
// 7. POST - REGISTRO DE NOVO ATENDIMENTO
// ============================================================
if ($metodo === 'POST') {
$entrada = json_decode(
file_get_contents('php://input'),
true
);
if (!is_array($entrada)) {
$entrada = $_POST;
}
$foneVisitante = trim($entrada['fone_visitante'] ?? '');
$foneIa = trim($entrada['fone_ia'] ?? '');
$chamada = trim($entrada['chamada'] ?? '');
$idArtigo = isset($entrada['id_artigo'])
&& $entrada['id_artigo'] !== ''
? (int) $entrada['id_artigo']
: null;
$tituloReferencia = trim(
$entrada['titulo_referencia'] ?? ''
);
if ($tituloReferencia === '') {
$tituloReferencia = null;
}
$telVisitante = normalizarTelefone($foneVisitante);
$telIa = normalizarTelefone($foneIa);
// --------------------------------------------------------
// 7.1 VALIDAÇÃO
// --------------------------------------------------------
if ($telVisitante === '' || $telIa === '') {
resposta(400, array(
'ok' => false,
'erro' => 'Telefone do visitante e telefone da IA são obrigatórios.'
));
}
if ($chamada === '') {
resposta(400, array(
'ok' => false,
'erro' => 'Informe o título da chamada.'
));
}
try {
$pdo->beginTransaction();
// ----------------------------------------------------
// 7.2 IDENTIFICA A ATENDENTE
// ----------------------------------------------------
$sql = "
SELECT
id,
codigo,
nome,
nomeExibicao,
telefone,
telefoneAlternativo,
situacao
FROM atendente_ia
WHERE " . telefoneSql('telefone') . " = :telefone
OR " . telefoneSql('telefoneAlternativo') . " = :telefoneAlternativo
LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telIa,
':telefoneAlternativo' => $telIa
));
$atendente = $stmt->fetch();
if (!$atendente) {
$pdo->rollBack();
resposta(404, array(
'ok' => false,
'erro' => 'Atendente não encontrada.'
));
}
// Situação 1 = ativa; 0 = inativa.
if ((int) $atendente['situacao'] !== 1) {
$pdo->rollBack();
resposta(403, array(
'ok' => false,
'erro' => 'Esta atendente está inativa.'
));
}
// ----------------------------------------------------
// 7.3 LOCALIZA O VISITANTE
// ----------------------------------------------------
$sql = "
SELECT id, nome, telefone
FROM visitante
WHERE " . telefoneSql('telefone') . " = :telefone
LIMIT 1
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telVisitante
));
$visitante = $stmt->fetch();
// ----------------------------------------------------
// 7.4 CADASTRA VISITANTE SE NÃO EXISTIR
// ----------------------------------------------------
if (!$visitante) {
$sql = "
INSERT INTO visitante (
nome,
telefone,
situacao,
dataCadastro
) VALUES (
NULL,
:telefone,
'ativo',
NOW()
)
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone' => $telVisitante
));
$visitanteId = (int) $pdo->lastInsertId();
} else {
$visitanteId = (int) $visitante['id'];
}
// ----------------------------------------------------
// 7.5 REGISTRA A CHAMADA
// ----------------------------------------------------
$sql = "
INSERT INTO atendimento (
telefone_visitante,
telefone_ia,
id_artigo,
titulo_referencia,
chamada
) VALUES (
:telefone_visitante,
:telefone_ia,
:id_artigo,
:titulo_referencia,
:chamada
)
";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':telefone_visitante' => $telVisitante,
':telefone_ia' => $telIa,
':id_artigo' => $idArtigo,
':titulo_referencia' => $tituloReferencia,
':chamada' => $chamada
));
$idAtendimento = (int) $pdo->lastInsertId();
// ----------------------------------------------------
// 7.6 FINALIZA
// ----------------------------------------------------
$pdo->commit();
resposta(201, array(
'ok' => true,
'mensagem' => 'Atendimento registrado com sucesso.',
'id_atendimento' => $idAtendimento,
'id_visitante' => $visitanteId,
'atendente' => array(
'id' => (int) $atendente['id'],
'codigo' => $atendente['codigo'],
'nome' => $atendente['nomeExibicao']
?: $atendente['nome']
),
'telefone_visitante' => $telVisitante,
'telefone_ia' => $telIa,
'chamada' => $chamada
));
} catch (PDOException $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log('API CCMBR POST: ' . $e->getMessage());
resposta(500, array(
'ok' => false,
'erro' => 'Erro ao registrar o atendimento.'
));
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log('API CCMBR POST: ' . $e->getMessage());
resposta(500, array(
'ok' => false,
'erro' => 'Erro interno ao processar o atendimento.'
));
}
}
// ============================================================
// 8. MÉTODO NÃO PERMITIDO
// ============================================================
resposta(405, array(
'ok' => false,
'erro' => 'Método não permitido. Utilize GET ou POST.'
));
Autor do blog:
Nilton Romani