feat: qualidade MP - items/payer/statement_descriptor/deviceId/cancel + form CPF no portal
build-image / build-push (push) Successful in 1m36s

This commit is contained in:
jfeng committed 2026-10-21 21:47:16 -03:00
1 parent 67608421b4
commit 59d6aa0ed3
4 files changed
+250 -12

No files matched your search

+118 -2
View File
@@ -9,6 +9,9 @@
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <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"> <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 crossorigin="anonymous"></script>
<style> <style>
:root { :root {
--graphite: #101820; --graphite: #101820;
@@ -407,6 +410,50 @@
padding: 12px 0; 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 { .skel {
height: 68px; height: 68px;
border-radius: var(--radius-md); border-radius: var(--radius-md);
@@ -439,6 +486,29 @@
</div> </div>
</main> </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 nome e CPF</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>CPF</span>
<input id="payerCpf" type="text" inputmode="numeric" maxlength="14" placeholder="000.000.000-00">
</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 ===== --> <!-- ===== PAGAMENTO ===== -->
<section id="view-pay" class="card hidden" aria-labelledby="payTitle"> <section id="view-pay" class="card hidden" aria-labelledby="payTitle">
<div class="pay-head"> <div class="pay-head">
@@ -461,6 +531,14 @@
<span class="dot"></span><span id="payPillText">Aguardando pagamento…</span> <span class="dot"></span><span id="payPillText">Aguardando pagamento…</span>
</div> </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> <a class="back" href="#" id="backBtn">← Voltar aos planos</a>
</section> </section>
@@ -507,9 +585,38 @@
let currentPaymentId = null; let currentPaymentId = null;
let pollTimer = null; let pollTimer = null;
let toastTimer = null; let toastTimer = null;
let selectedPlanId = null;
let mpDevice = null;
const $ = (id) => document.getElementById(id); 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 maskCpf(v) {
const d = v.replace(/\D/g, '').slice(0, 11);
return d
.replace(/^(\d{3})(\d)/, '$1.$2')
.replace(/^(\d{3})\.(\d{3})(\d)/, '$1.$2.$3')
.replace(/\.(\d{3})(\d{1,2})$/, '.$1-$2');
}
function toast(msg) { function toast(msg) {
const t = $('toast'); const t = $('toast');
t.textContent = msg; t.textContent = msg;
@@ -535,6 +642,7 @@
function show(view) { function show(view) {
$('view-plans').classList.toggle('hidden', view !== 'plans'); $('view-plans').classList.toggle('hidden', view !== 'plans');
$('view-payer').classList.toggle('hidden', view !== 'payer');
$('view-pay').classList.toggle('hidden', view !== 'pay'); $('view-pay').classList.toggle('hidden', view !== 'pay');
$('view-voucher').classList.toggle('hidden', view !== 'voucher'); $('view-voucher').classList.toggle('hidden', view !== 'voucher');
if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; } if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; }
@@ -565,7 +673,7 @@
btn.querySelector('h3').textContent = p.name; btn.querySelector('h3').textContent = p.name;
btn.querySelector('.plan-meta').textContent = p.speed + ' · validade ' + p.uptime; btn.querySelector('.plan-meta').textContent = p.speed + ' · validade ' + p.uptime;
btn.querySelector('.plan-price').textContent = money(p.price); btn.querySelector('.plan-price').textContent = money(p.price);
btn.addEventListener('click', () => checkout(p.id)); btn.addEventListener('click', () => { selectedPlanId = p.id; show('payer'); });
box.appendChild(btn); box.appendChild(btn);
} }
} catch { } catch {
@@ -575,10 +683,15 @@
async function checkout(planId) { async function checkout(planId) {
try { try {
const payerName = $('payerName').value.trim();
const payerCpf = $('payerCpf').value.trim();
if (payerName.length < 3) { toast('Informe seu nome completo'); show('payer'); return; }
if (payerCpf.replace(/\D/g, '').length !== 11) { toast('Informe um CPF com 11 dígitos'); show('payer'); return; }
const res = await fetch('/api/checkout', { const res = await fetch('/api/checkout', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ planId, mac }), body: JSON.stringify({ planId, mac, payerName, payerCpf, deviceId: deviceId() }),
}); });
const data = await res.json(); const data = await res.json();
if (data.error) throw new Error(data.error); if (data.error) throw new Error(data.error);
@@ -638,6 +751,9 @@
); );
$('backBtn').addEventListener('click', (e) => { e.preventDefault(); show('plans'); }); $('backBtn').addEventListener('click', (e) => { e.preventDefault(); show('plans'); });
$('backBtn2').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));
$('payerCpf').addEventListener('input', (e) => { e.target.value = maskCpf(e.target.value); });
loadPlans(); loadPlans();
</script> </script>
+1
View File
@@ -6,6 +6,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const config = { const config = {
mpAccessToken: process.env.MP_ACCESS_TOKEN || '', mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox', mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
mpPublicKey: process.env.MP_PUBLIC_KEY || '',
mikrotik: { mikrotik: {
host: process.env.MIKROTIK_HOST || '192.168.3.81', host: process.env.MIKROTIK_HOST || '192.168.3.81',
port: parseInt(process.env.MIKROTIK_PORT || '8728', 10), port: parseInt(process.env.MIKROTIK_PORT || '8728', 10),
+42 -3
View File
@@ -3,7 +3,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import config from './config.js'; import config from './config.js';
import { initDb, getDb, saveDb, genCode } from './db.js'; import { initDb, getDb, saveDb, genCode } from './db.js';
import { initMp, createPixPayment, getPaymentStatus } from './mp.js'; import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
import { createHotspotUser } from './ros.js'; import { createHotspotUser } from './ros.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -51,9 +51,16 @@ app.get('/api/plans', (req, res) => {
app.post('/api/checkout', async (req, res) => { app.post('/api/checkout', async (req, res) => {
try { try {
const { planId, mac } = req.body || {}; const { planId, mac, payerName, payerCpf, deviceId } = req.body || {};
const plan = getDb().plans.find((p) => p.id === planId && p.active); const plan = getDb().plans.find((p) => p.id === planId && p.active);
if (!plan) return res.status(400).json({ error: 'plano invalido' }); if (!plan) return res.status(400).json({ error: 'plano invalido' });
if (payerCpf && !validCpf(payerCpf)) return res.status(400).json({ error: 'CPF invalido' });
// historico do comprador (primeira compra / ultima compra)
const hist = getDb().payments.filter((p) => p.mac && p.mac === mac && p.status === 'paid');
const firstPurchase = hist.length === 0;
const registrationDate = (hist[0] && hist[0].createdAt) || new Date().toISOString();
const lastPurchase = hist.length ? hist[hist.length - 1].paidAt || hist[hist.length - 1].createdAt : null;
const payment = { const payment = {
id: 'P' + Date.now() + genCode(4), id: 'P' + Date.now() + genCode(4),
@@ -67,7 +74,18 @@ app.post('/api/checkout', async (req, res) => {
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
}; };
const pix = await createPixPayment(plan.price, payment.id, `WiFi ${plan.name}`); const pix = await createPixPayment({
amount: plan.price,
reference: payment.id,
planId: plan.id,
planName: plan.name,
payerName,
payerCpf,
firstPurchase,
registrationDate,
lastPurchase,
deviceId,
});
payment.mpId = pix.mpId; payment.mpId = pix.mpId;
payment.qrCodeBase64 = pix.qrCodeBase64; payment.qrCodeBase64 = pix.qrCodeBase64;
payment.copiaCola = pix.copiaCola; payment.copiaCola = pix.copiaCola;
@@ -136,6 +154,27 @@ app.post('/api/admin/plans', adminAuth, (req, res) => {
res.json({ ok: true }); res.json({ ok: true });
}); });
app.get('/api/mp/public-key', (req, res) => {
res.json({ publicKey: config.mpPublicKey || '' });
});
app.post('/api/admin/payments/:id/cancel', adminAuth, async (req, res) => {
const payment = getDb().payments.find((p) => p.id === req.params.id);
if (!payment) return res.status(404).json({ error: 'nao encontrado' });
if (!payment.mpId || payment.status !== 'pending') {
return res.status(400).json({ error: 'apenas pendentes podem ser cancelados' });
}
try {
await cancelOrder(payment.mpId);
payment.status = 'cancelled';
saveDb();
console.log(`[CANCEL] order ${payment.mpId} cancelada`);
res.json({ ok: true, status: payment.status });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.get('/api/health', async (req, res) => { app.get('/api/health', async (req, res) => {
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() }); res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
}); });
+89 -7
View File
@@ -21,25 +21,96 @@ export function initMp() {
} }
} }
// quebra nome completo em primeiro/resto (sobrenome)
function splitName(full) {
const parts = String(full || '').trim().split(/\s+/).filter(Boolean);
if (!parts.length) return { first: 'Convidado', last: 'Wi-Fi' };
return { first: parts[0], last: parts.slice(1).join(' ') || parts[0] };
}
function validCpf(cpf) {
const c = String(cpf || '').replace(/\D/g, '');
if (c.length !== 11 || /^(\d)\1{10}$/.test(c)) return false;
let s = 0;
for (let i = 0; i < 9; i++) s += parseInt(c[i], 10) * (10 - i);
let d1 = (s * 10) % 11;
if (d1 === 10) d1 = 0;
if (d1 !== parseInt(c[9], 10)) return false;
s = 0;
for (let i = 0; i < 10; i++) s += parseInt(c[i], 10) * (11 - i);
let d2 = (s * 10) % 11;
if (d2 === 10) d2 = 0;
return d2 === parseInt(c[10], 10);
}
export { validCpf };
// Orders API (Checkout Transparente) - o app do MP esta marcado como API Orders, // Orders API (Checkout Transparente) - o app do MP esta marcado como API Orders,
// a legada /v1/payments retorna 401 "Unauthorized use of live credentials". // a legada /v1/payments retorna 401 "Unauthorized use of live credentials".
export async function createPixPayment(amount, reference, description) { export async function createPixPayment(opts) {
if (!ready()) throw new Error('Mercado Pago nao configurado'); if (!ready()) throw new Error('Mercado Pago nao configurado');
const {
amount,
reference,
planId,
planName,
payerName,
payerCpf,
firstPurchase,
registrationDate,
lastPurchase,
deviceId,
} = opts;
const name = splitName(payerName);
const payer = {
email: '[email protected]',
first_name: name.first,
last_name: name.last,
entity_type: 'individual',
};
const cpf = String(payerCpf || '').replace(/\D/g, '');
if (cpf && validCpf(cpf)) {
payer.identification = { type: 'CPF', number: cpf };
}
const headers = authHeaders({ 'X-Idempotency-Key': reference + '-' + Date.now() });
if (deviceId) headers['X-meli-session-id'] = deviceId;
const additionalInfo = {
'payer.registration_date': registrationDate || new Date().toISOString(),
'payer.authentication_type': 'WEB',
'payer.is_first_purchase_online': firstPurchase !== false,
};
if (lastPurchase) additionalInfo['payer.last_purchase'] = lastPurchase;
const res = await fetch(API + '/v1/orders', { const res = await fetch(API + '/v1/orders', {
method: 'POST', method: 'POST',
headers: authHeaders({ 'X-Idempotency-Key': reference + '-' + Date.now() }), headers,
body: JSON.stringify({ body: JSON.stringify({
type: 'online', type: 'online',
external_reference: reference, external_reference: reference,
description, description: 'WiFi ' + planName,
total_amount: amount.toFixed(2), total_amount: Number(amount).toFixed(2),
processing_mode: 'automatic', processing_mode: 'automatic',
payer: { email: '[email protected]' }, config: { statement_descriptor: 'INCTG WIFI' },
payer,
items: [
{
title: 'WiFi ' + planName,
description: 'Acesso a internet - ' + planName,
quantity: 1,
unit_price: Number(amount).toFixed(2),
category_id: 'services',
external_code: planId,
},
],
additional_info: additionalInfo,
transactions: { transactions: {
payments: [ payments: [
{ {
amount: amount.toFixed(2), amount: Number(amount).toFixed(2),
payment_method: { id: 'pix', type: 'bank_transfer' }, payment_method: { id: 'pix', type: 'bank_transfer' },
expiration_time: 'PT24H', expiration_time: 'PT24H',
}, },
@@ -50,7 +121,8 @@ export async function createPixPayment(amount, reference, description) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
if (!res.ok) { if (!res.ok) {
throw new Error(data.message || data.error || 'Mercado Pago HTTP ' + res.status); const detail = data.errors?.map((e) => e.message || e.code).join('; ');
throw new Error(detail || data.message || data.error || 'Mercado Pago HTTP ' + res.status);
} }
const pm = data.transactions?.payments?.[0]?.payment_method || {}; const pm = data.transactions?.payments?.[0]?.payment_method || {};
@@ -64,6 +136,16 @@ export async function createPixPayment(amount, reference, description) {
}; };
} }
export async function cancelOrder(mpId) {
if (!ready()) throw new Error('Mercado Pago nao configurado');
const res = await fetch(API + '/v1/orders/' + mpId + '/cancel', {
method: 'POST',
headers: authHeaders(),
});
if (!res.ok) throw new Error('Mercado Pago HTTP ' + res.status);
return res.json();
}
export async function getPaymentStatus(mpId) { export async function getPaymentStatus(mpId) {
if (!ready()) throw new Error('Mercado Pago nao configurado'); if (!ready()) throw new Error('Mercado Pago nao configurado');