Files
HotSpot/backend/public/index.html
T
2026-10-22 17:23:16 +00:00

944 lines
32 KiB
HTML

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="theme-color" content="#101820">
<title>INCTG Wi-Fi Convidados</title>
<link rel="icon" type="image/png" href="logo.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500;600;700;800&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<!-- Mercado Pago: SDK JS V2 + Device ID (gera MP_DEVICE_SESSION_ID) -->
<script src="https://sdk.mercadopago.com/js/v2" defer></script>
<script src="https://www.mercadopago.com.br/integrations/v1/security-code.js" async view="checkout"></script>
<style>
:root {
--graphite: #101820;
--graphite-2: #151f2b;
--graphite-3: #1c2836;
--blue: #246BFD;
--blue-hover: #3d7cff;
--blue-soft: rgba(36, 107, 253, 0.14);
--white: #F4F6F8;
--gray: #7C8A9A;
--gray-2: #9aa7b5;
--line: rgba(124, 138, 154, 0.18);
--success: #12B886;
--success-soft: rgba(18, 184, 134, 0.12);
--danger: #E5484D;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--font-heading: "Manrope", system-ui, sans-serif;
--font-body: "Inter", system-ui, sans-serif;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
font-family: var(--font-body);
background: var(--graphite);
color: var(--white);
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
padding: 24px 16px calc(24px + env(safe-area-inset-bottom));
position: relative;
overflow-x: hidden;
}
body::before {
content: "";
position: fixed;
inset: 0;
background:
radial-gradient(720px 420px at 85% -10%, rgba(36, 107, 253, 0.18), transparent 60%),
radial-gradient(520px 320px at -10% 110%, rgba(36, 107, 253, 0.08), transparent 60%);
pointer-events: none;
z-index: 0;
}
.wrap {
width: 100%;
max-width: 440px;
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
gap: 20px;
}
/* ---------- Header ---------- */
.brand {
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
text-align: center;
padding-top: 8px;
}
.brand-logo {
width: 108px;
height: auto;
border-radius: 14px;
display: block;
}
.brand h1 {
font-family: var(--font-heading);
font-weight: 700;
font-size: 1.45rem;
letter-spacing: -0.02em;
line-height: 1.2;
}
.brand .tagline {
color: var(--gray);
font-size: 0.86rem;
font-weight: 500;
}
.brand .tagline strong { color: var(--blue); font-weight: 600; }
/* ---------- Cards ---------- */
.card {
background: linear-gradient(180deg, rgba(28, 40, 54, 0.9), rgba(21, 31, 43, 0.9));
border: 1px solid var(--line);
border-radius: var(--radius-lg);
padding: 20px;
backdrop-filter: blur(6px);
}
.section-label {
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--gray);
margin-bottom: 12px;
}
/* ---------- Planos ---------- */
.plan {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
width: 100%;
background: var(--graphite-2);
border: 1px solid var(--line);
border-radius: var(--radius-md);
padding: 16px;
cursor: pointer;
text-align: left;
color: inherit;
font: inherit;
transition: border-color 0.18s, transform 0.18s, background 0.18s;
margin-bottom: 10px;
}
.plan:last-child { margin-bottom: 0; }
.plan:hover { border-color: rgba(36, 107, 253, 0.55); transform: translateY(-1px); }
.plan:active { transform: translateY(0); }
.plan:focus-visible,
button:focus-visible,
a:focus-visible {
outline: 2px solid var(--blue);
outline-offset: 2px;
}
.plan-info h3 {
font-family: var(--font-heading);
font-size: 1rem;
font-weight: 700;
}
.plan-meta {
margin-top: 4px;
color: var(--gray);
font-size: 0.78rem;
line-height: 1.4;
}
.plan-price {
font-family: var(--font-heading);
font-weight: 800;
font-size: 1.05rem;
color: var(--blue);
background: var(--blue-soft);
border-radius: var(--radius-sm);
padding: 8px 12px;
white-space: nowrap;
}
/* ---------- Checkout ---------- */
.pay-head { text-align: center; margin-bottom: 6px; }
.pay-head h2 {
font-family: var(--font-heading);
font-size: 1.15rem;
font-weight: 700;
}
.pay-head p { color: var(--gray); font-size: 0.84rem; margin-top: 4px; }
.qr-panel {
background: #fff;
border-radius: var(--radius-md);
padding: 14px;
width: 232px;
height: 232px;
margin: 18px auto 14px;
display: flex;
align-items: center;
justify-content: center;
}
.qr-panel img { width: 100%; height: 100%; object-fit: contain; }
.copia {
background: var(--graphite);
border: 1px dashed rgba(124, 138, 154, 0.35);
border-radius: var(--radius-sm);
padding: 12px;
font-size: 0.68rem;
line-height: 1.5;
word-break: break-all;
color: var(--gray-2);
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
max-height: 84px;
overflow: hidden;
position: relative;
}
.row { display: flex; gap: 10px; margin-top: 12px; }
/* ---------- Botões ---------- */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
border: 0;
border-radius: var(--radius-md);
padding: 14px 18px;
font-family: var(--font-heading);
font-size: 0.95rem;
font-weight: 700;
cursor: pointer;
transition: background 0.18s, opacity 0.18s, transform 0.15s;
text-decoration: none;
color: #fff;
}
.btn:active { transform: scale(0.985); }
.btn:disabled { opacity: 0.55; cursor: wait; }
.btn-primary { background: var(--blue); }
.btn-primary:hover:not(:disabled) { background: var(--blue-hover); }
.btn-ghost {
background: transparent;
border: 1px solid var(--line);
color: var(--white);
font-weight: 600;
}
.btn-ghost:hover { border-color: var(--gray); }
.btn-success { background: var(--success); }
.btn-success:hover:not(:disabled) { background: #16c996; }
/* ---------- Status pill ---------- */
.pill {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
color: var(--gray);
font-size: 0.82rem;
margin-top: 14px;
min-height: 22px;
}
.pill .dot {
width: 8px; height: 8px; border-radius: 50%;
background: var(--gray);
flex: none;
}
.pill.waiting .dot {
background: var(--blue);
animation: pulse 1.4s ease-in-out infinite;
}
.pill.ok { color: var(--success); }
.pill.ok .dot { background: var(--success); animation: none; }
.pill.err { color: var(--danger); }
.pill.err .dot { background: var(--danger); animation: none; }
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.35; transform: scale(0.75); }
}
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}
/* ---------- Voucher ---------- */
.voucher-view { text-align: center; }
.check {
width: 56px; height: 56px;
margin: 6px auto 14px;
border-radius: 50%;
background: var(--success-soft);
display: flex; align-items: center; justify-content: center;
}
.check svg { width: 28px; height: 28px; }
.voucher-view h2 {
font-family: var(--font-heading);
font-size: 1.2rem;
font-weight: 700;
}
.voucher-view .hint {
color: var(--gray);
font-size: 0.85rem;
margin: 6px 0 18px;
line-height: 1.5;
}
.code-box {
background: var(--graphite);
border: 1px solid var(--line);
border-radius: var(--radius-md);
padding: 14px;
margin-bottom: 10px;
}
.code-box .lbl {
font-size: 0.68rem;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--gray);
font-weight: 600;
}
.code-box .val {
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
font-size: 1.45rem;
font-weight: 700;
color: var(--success);
letter-spacing: 0.08em;
margin-top: 4px;
user-select: all;
}
.steps {
margin: 16px 0 4px;
text-align: left;
color: var(--gray);
font-size: 0.8rem;
line-height: 1.7;
padding-left: 4px;
}
.steps li { margin-left: 18px; }
/* ---------- Footer / toast ---------- */
footer {
margin-top: 8px;
text-align: center;
color: var(--gray);
font-size: 0.72rem;
line-height: 1.6;
}
footer strong { color: var(--white); font-weight: 600; }
.toast {
position: fixed;
bottom: calc(20px + env(safe-area-inset-bottom));
left: 50%;
transform: translateX(-50%) translateY(80px);
background: var(--graphite-3);
border: 1px solid var(--line);
color: var(--white);
padding: 10px 18px;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
opacity: 0;
transition: transform 0.25s, opacity 0.25s;
z-index: 10;
pointer-events: none;
white-space: nowrap;
}
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
.hidden { display: none !important; }
.back {
display: block;
text-align: center;
margin-top: 16px;
color: var(--gray);
font-size: 0.85rem;
text-decoration: none;
font-weight: 500;
}
.back:hover { color: var(--white); }
.empty {
text-align: center;
color: var(--gray);
font-size: 0.88rem;
padding: 12px 0;
}
.field {
display: block;
margin-bottom: 14px;
}
.field span {
display: block;
font-size: 0.8rem;
font-weight: 600;
color: var(--gray-2);
margin-bottom: 6px;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.field input {
width: 100%;
padding: 12px 14px;
font-family: var(--font-body);
font-size: 0.95rem;
color: var(--white);
background: var(--graphite-2);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
outline: none;
transition: border-color 0.15s ease;
}
.field input:focus { border-color: var(--blue); }
.field input::placeholder { color: var(--gray); }
.mp-badge {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
margin-top: 14px;
font-size: 0.78rem;
color: var(--gray-2);
}
.mp-badge svg { flex: 0 0 auto; }
.skel {
height: 68px;
border-radius: var(--radius-md);
background: linear-gradient(90deg, var(--graphite-2) 25%, var(--graphite-3) 50%, var(--graphite-2) 75%);
background-size: 200% 100%;
animation: sk 1.2s infinite linear;
margin-bottom: 10px;
}
@keyframes sk { to { background-position: -200% 0; } }
</style>
</head>
<body>
<div class="wrap">
<header class="brand">
<img class="brand-logo" src="logo.png" alt="INCTG — Incorpore Technology Group" width="108" height="108">
<div>
<h1>Wi-Fi Convidados</h1>
<p class="tagline">Escolha seu plano · <strong>Pague com PIX</strong> · Conecte em segundos</p>
</div>
</header>
<!-- ===== PLANOS ===== -->
<div class="card" style="margin-bottom:14px" role="status" aria-live="polite">
<p id="freeAccessMessage">Verificando acesso temporário para pagamento…</p>
<p id="freeAccessProbe" hidden></p>
<button class="btn btn-ghost" id="retryFreeAccess" type="button" hidden>Tentar liberar acesso</button>
</div>
<main id="view-plans">
<div class="card">
<div class="section-label">Planos disponíveis</div>
<div id="plans">
<div class="skel"></div><div class="skel"></div><div class="skel"></div>
</div>
</div>
<div class="card" style="margin-top:14px">
<button class="btn btn-ghost" id="showLogin" type="button">Já tenho usuário e senha</button>
<div id="loginBox" class="hidden" style="margin-top:14px">
<label class="field">
<span>Usuário</span>
<input id="hsUser" type="text" autocomplete="username" autocapitalize="off" placeholder="Ex.: GAB12CD">
</label>
<label class="field">
<span>Senha</span>
<input id="hsPass" type="password" autocomplete="current-password" placeholder="Sua senha">
</label>
<button class="btn btn-primary" id="hsConnect" type="button">Conectar ao Wi-Fi</button>
</div>
</div>
</main>
<!-- ===== DADOS DO PAGADOR ===== -->
<section id="view-payer" class="card hidden" aria-labelledby="payerTitle">
<div class="pay-head">
<h2 id="payerTitle">Seus dados</h2>
<p>Para emissão do PIX, informe seu nome e e-mail</p>
</div>
<label class="field">
<span>Nome completo</span>
<input id="payerName" type="text" autocomplete="name" maxlength="80" placeholder="Ex.: João da Silva">
</label>
<label class="field">
<span>E-mail</span>
<input id="payerEmail" type="email" autocomplete="email" inputmode="email" maxlength="120" placeholder="[email protected]">
</label>
<div class="row">
<button class="btn btn-ghost" id="payerBack" type="button">← Voltar</button>
<button class="btn btn-primary" id="payerNext" type="button">Gerar PIX</button>
</div>
</section>
<!-- ===== PAGAMENTO ===== -->
<section id="view-pay" class="card hidden" aria-labelledby="payTitle">
<div class="pay-head">
<h2 id="payTitle">PIX</h2>
<p>Escaneie o QR Code no app do seu banco</p>
</div>
<div class="qr-panel">
<img id="qrImg" alt="QR Code do pagamento PIX">
</div>
<div class="copia" id="copiaCola" title="Código copia e cola"></div>
<div class="row">
<button class="btn btn-ghost" id="copyBtn" type="button">Copiar código</button>
<button class="btn btn-primary" id="checkBtn" type="button">Já paguei</button>
</div>
<div class="pill waiting" id="payPill" role="status" aria-live="polite">
<span class="dot"></span><span id="payPillText">Aguardando pagamento…</span>
</div>
<div class="mp-badge">
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
<path fill="#009EE3" d="M12 2L3 6v6c0 5 3.8 9.4 9 10 5.2-.6 9-5 9-10V6l-9-4z"/>
<path fill="#00B1EA" d="M12 4.2L5 7.3v4.7c0 3.9 2.9 7.4 7 8 4.1-.6 7-4.1 7-8V7.3l-7-3.1z" opacity=".5"/>
</svg>
<span>Pagamento processado com segurança por <strong>Mercado Pago</strong></span>
</div>
<a class="back" href="#" id="backBtn">← Voltar aos planos</a>
</section>
<!-- ===== VOUCHER ===== -->
<section id="view-voucher" class="card voucher-view hidden" aria-labelledby="vTitle">
<div class="check" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="#12B886" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
</div>
<h2 id="vTitle">Pagamento confirmado</h2>
<p class="hint">Use os dados abaixo na tela de login do Wi-Fi.</p>
<div class="code-box">
<div class="lbl">Usuário</div>
<div class="val" id="vUser">—</div>
</div>
<div class="code-box">
<div class="lbl">Senha</div>
<div class="val" id="vPass">—</div>
</div>
<ol class="steps">
<li>Toque no botão <strong>Conectar agora</strong> abaixo</li>
<li>Se pedir, conecte na rede <strong id="ssidLabel">Wi-Fi</strong></li>
<li>Pronto: seu acesso já estará liberado</li>
</ol>
<button class="btn btn-success" id="hsAutoLogin" type="button" style="margin-top:14px">Conectar agora</button>
<button class="btn btn-ghost" id="copyVoucher" type="button" style="margin-top:10px">Copiar usuário e senha</button>
<a class="back" href="#" id="backBtn2">← Voltar aos planos</a>
</section>
<footer>
<strong>INCTG</strong> — Incorpore Technology Group<br>
Tecnologia que resolve.
</footer>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script>
const mac = new URLSearchParams(location.search).get('mac') || '';
let currentPaymentId = null;
let pollTimer = null;
let toastTimer = null;
let selectedPlanId = null;
let mpDevice = null;
let checkoutBusy = false;
const $ = (id) => document.getElementById(id);
// ===== Mercado Pago SDK V2 + Device ID =====
async function initMpSdk() {
try {
const res = await fetch('/api/mp/public-key');
const { publicKey } = await res.json();
if (publicKey && window.MercadoPago) {
const mp = new window.MercadoPago(publicKey);
if (typeof mp.getId === 'function') {
mpDevice = await Promise.resolve(mp.getId()).catch(() => null);
}
}
} catch { /* segue sem device id */ }
}
window.addEventListener('load', initMpSdk);
function deviceId() {
return mpDevice || window.MP_DEVICE_SESSION_ID || null;
}
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => t.classList.remove('show'), 2200);
}
async function copy(text, msg) {
try {
await navigator.clipboard.writeText(text);
toast(msg || 'Copiado!');
} catch {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
toast(msg || 'Copiado!');
}
}
function show(view) {
$('view-plans').classList.toggle('hidden', view !== 'plans');
$('view-payer').classList.toggle('hidden', view !== 'payer');
$('view-pay').classList.toggle('hidden', view !== 'pay');
$('view-voucher').classList.toggle('hidden', view !== 'voucher');
if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; }
window.scrollTo({ top: 0, behavior: 'instant' in window ? 'auto' : 'auto' });
}
function money(v) {
return 'R$ ' + v.toFixed(2).replace('.', ',');
}
async function loadPlans() {
try {
const res = await fetch('/api/plans');
const plans = await res.json();
const box = $('plans');
if (!plans.length) {
box.innerHTML = '<div class="empty">Nenhum plano disponível no momento.</div>';
return;
}
box.innerHTML = '';
for (const p of plans) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'plan';
btn.innerHTML =
'<div class="plan-info"><h3></h3><div class="plan-meta"></div></div>' +
'<div class="plan-price"></div>';
btn.querySelector('h3').textContent = p.name;
btn.querySelector('.plan-meta').textContent = p.speed + ' · validade ' + p.uptime;
btn.querySelector('.plan-price').textContent = money(p.price);
btn.addEventListener('click', () => { selectedPlanId = p.id; show('payer'); });
box.appendChild(btn);
}
} catch {
$('plans').innerHTML = '<div class="empty">Não foi possível carregar os planos. Recarregue a página.</div>';
}
}
async function checkout(planId) {
if (checkoutBusy) return;
checkoutBusy = true;
$('payerNext').disabled = true;
try {
const payerName = $('payerName').value.trim();
const payerEmail = $('payerEmail').value.trim();
if (payerName.length < 3) { toast('Informe seu nome completo'); show('payer'); return; }
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(payerEmail)) { toast('Informe um e-mail válido'); show('payer'); return; }
const res = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ planId, mac, payerName, payerEmail, deviceId: deviceId() }),
});
const data = await res.json();
if (data.error) throw new Error(data.error);
currentPaymentId = data.paymentId;
sessionStorage.setItem('paymentId', currentPaymentId);
sessionStorage.setItem('pendingPix', JSON.stringify(data));
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
$('copiaCola').textContent = data.copiaCola || '';
setPill('waiting', 'Aguardando pagamento…');
show('pay');
clearInterval(pollTimer);
pollTimer = setInterval(verify, 6000);
startFreeAccess();
} catch (e) {
toast('Erro: ' + e.message);
} finally {
checkoutBusy = false;
$('payerNext').disabled = false;
}
}
function setPill(state, text) {
const pill = $('payPill');
pill.className = 'pill ' + state;
$('payPillText').textContent = text;
}
async function verify() {
if (!currentPaymentId) return;
const btn = $('checkBtn');
btn.disabled = true;
try {
const res = await fetch('/api/status/' + encodeURIComponent(currentPaymentId));
if (!res.ok) throw new Error('Falha na consulta');
const data = await res.json();
if (data.status === 'paid' && data.voucher) {
sessionStorage.removeItem('pendingPix');
clearInterval(window.freeAccessTimer);
$('freeAccessMessage').textContent = 'Pagamento confirmado. Use seu voucher para conectar ao Wi-Fi.';
$('retryFreeAccess').hidden = true;
clearInterval(pollTimer); pollTimer = null;
$('vUser').textContent = data.voucher.user;
$('vPass').textContent = data.voucher.pass;
setPill('ok', 'Pagamento aprovado');
show('voucher');
return;
}
if (['rejected', 'cancelled', 'expired'].includes(data.status)) {
setPill('err', 'Pagamento não aprovado. Tente novamente.');
clearInterval(pollTimer); pollTimer = null;
} else {
setPill('waiting', 'Aguardando pagamento…');
}
} catch {
setPill('err', 'Falha ao verificar. Toque em "Já paguei".');
} finally {
btn.disabled = false;
}
}
$('checkBtn').addEventListener('click', verify);
$('copyBtn').addEventListener('click', () => copy($('copiaCola').textContent, 'Código PIX copiado'));
$('copyVoucher').addEventListener('click', () =>
copy('Usuário: ' + $('vUser').textContent + '\nSenha: ' + $('vPass').textContent, 'Credenciais copiadas')
);
$('backBtn').addEventListener('click', (e) => { e.preventDefault(); show('plans'); });
$('backBtn2').addEventListener('click', (e) => { e.preventDefault(); show('plans'); });
$('payerBack').addEventListener('click', () => show('plans'));
$('payerNext').addEventListener('click', () => checkout(selectedPlanId));
// ===== Login no hotspot (voucher) =====
let HS_LOGIN = 'http://10.10.10.1/login';
function hsUrl(user, pass) {
return HS_LOGIN + '?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass);
}
$('showLogin').addEventListener('click', () => {
$('loginBox').classList.toggle('hidden');
});
$('hsConnect').addEventListener('click', () => {
const u = $('hsUser').value.trim();
const p = $('hsPass').value;
if (!u || !p) { toast('Informe usuário e senha'); return; }
hotspotLogin(u, p);
});
$('hsAutoLogin').addEventListener('click', () => {
hotspotLogin($('vUser').textContent, $('vPass').textContent);
});
function hotspotLogin(user, pass, destination) {
const form = document.createElement('form');
form.method = 'POST'; form.action = HS_LOGIN;
for (const [name, value] of Object.entries({ username: user, password: pass, ...(destination ? { dst: destination } : {}) })) {
const field = document.createElement('input'); field.type = 'hidden'; field.name = name; field.value = value; form.append(field);
}
document.body.append(form); form.submit();
}
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
async function startFreeAccess() {
const message = $('freeAccessMessage');
const retry = $('retryFreeAccess');
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac)) {
message.textContent = 'Para liberar internet temporária, conecte ao Wi-Fi de convidados e abra o portal pela tela de entrada da rede.';
retry.textContent = 'Abrir entrada do Wi-Fi';
retry.hidden = false;
return;
}
retry.hidden = true;
message.textContent = 'Preparando acesso temporário para abrir o aplicativo do banco…';
try {
const res = await fetch('/api/access/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mac }),
});
const d = await res.json();
if (!res.ok) {
message.textContent = res.status === 429 ? d.error + (d.retryAfterSeconds ? ' Tente em ' + d.retryAfterSeconds + ' segundos.' : '') : 'Não foi possível liberar a internet temporária. Tente novamente ou consulte o responsável pela rede.';
retry.hidden = false;
return;
}
if (d.authenticated) {
// Captive-portal assistants re-evaluate the network on top-level navigation.
// An API login plus a DOM update leaves some phones using the captive state.
// Navigate once per server window; reloading must never extend its deadline.
if (Number.isFinite(d.expiresAt) && d.expiresAt > Date.now() &&
sessionStorage.getItem('freeAccessConfirmedUntil') !== String(d.expiresAt)) {
sessionStorage.setItem('freeAccessConfirmedUntil', String(d.expiresAt));
const target = new URL(location.href);
target.searchParams.set('mac', mac);
target.searchParams.set('free', '1');
target.searchParams.set('access', String(d.expiresAt));
message.textContent = 'Acesso autorizado. Atualizando a conexão deste aparelho…';
window.location.replace(target.href);
return;
}
if (d.probeToken) verifyClientInternet(d.probeToken);
sessionStorage.removeItem('freeLoginAttemptUntil');
clearInterval(window.freeAccessTimer);
const deadline = Date.now() + d.seconds * 1000;
const update = () => {
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
message.textContent = seconds ? 'Sessão temporária confirmada: ' + seconds + ' segundos para efetuar o pagamento.' : 'O acesso temporário terminou. Se já pagou, toque em “Já paguei”.';
if (!seconds) { clearInterval(window.freeAccessTimer); retry.hidden = false; }
};
update(); window.freeAccessTimer = setInterval(update, 1000);
return;
}
message.textContent = 'O MikroTik ainda não confirmou o acesso. Tentando autenticar pela tela do hotspot…';
retry.hidden = false;
if (d.loginUrl && Number(sessionStorage.getItem('freeLoginAttemptUntil') || 0) < Date.now()) {
sessionStorage.setItem('freeLoginAttemptUntil', String(Date.now() + d.seconds * 1000));
const target = new URL(d.loginUrl);
hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst'));
}
} catch {
message.textContent = 'Falha ao verificar o acesso temporário. Toque em tentar liberar acesso.';
retry.hidden = false;
}
}
async function verifyClientInternet(token) {
const label = $('freeAccessProbe');
label.hidden = false;
label.textContent = 'Verificando o acesso a serviços externos neste aparelho…';
const results = await Promise.all([
['google', 'https://www.gstatic.com/generate_204'],
['apple', 'https://www.apple.com/library/test/success.html'],
].map(async ([provider, url]) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 6000);
try {
const response = await fetch(url + '?_=' + Date.now(), { mode: 'no-cors', cache: 'no-store', redirect: 'follow', credentials: 'omit', signal: controller.signal });
return { provider, ok: response.type === 'opaque' || response.ok };
} catch { return { provider, ok: false }; }
finally { clearTimeout(timer); }
}));
label.textContent = results.some(r => r.ok) ? 'Este aparelho alcançou um serviço externo. Você pode abrir o aplicativo do banco.' : 'A sessão está ativa, mas não foi possível confirmar o acesso externo. Verifique se o aplicativo do banco abre.';
try { await fetch('/api/access/report', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mac, token, results }) }); } catch { /* report is optional */ }
}
$('retryFreeAccess').addEventListener('click', () => {
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac)) {
window.location.href = HS_LOGIN;
return;
}
sessionStorage.removeItem('freeLoginAttemptUntil');
startFreeAccess();
});
async function loadSiteConfig() {
try {
const res = await fetch('/api/config');
const d = await res.json();
if (d.ssid) $('ssidLabel').textContent = d.ssid;
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
} catch { /* usa padrao */ }
}
loadSiteConfig().then(() => {
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac) || new URLSearchParams(location.search).get('free') === '1' || sessionStorage.getItem('pendingPix')) startFreeAccess();
else {
$('freeAccessMessage').textContent = 'O acesso temporário para abrir o aplicativo do banco começa após gerar o PIX. Se precisar antes, toque em liberar acesso.';
$('retryFreeAccess').textContent = 'Liberar acesso para pagamento';
$('retryFreeAccess').hidden = false;
}
});
loadPlans();
if (sessionStorage.getItem('paymentId')) {
currentPaymentId = sessionStorage.getItem('paymentId');
try {
const pending = JSON.parse(sessionStorage.getItem('pendingPix') || 'null');
if (pending?.paymentId === currentPaymentId) {
$('payTitle').textContent = pending.planName + ' · ' + money(pending.price);
$('qrImg').src = pending.qrCodeBase64 ? 'data:image/png;base64,' + pending.qrCodeBase64 : '';
$('copiaCola').textContent = pending.copiaCola || '';
show('pay');
pollTimer = setInterval(verify, 6000);
}
} catch { sessionStorage.removeItem('pendingPix'); }
verify();
}
</script>
</body>
</html>