feat(access): libera 90s de internet para pagamento + reconcile e deteccao de pagamento pela transacao
build-image / build-push (push) Successful in 5m6s
build-image / build-push (push) Successful in 5m6s
This commit is contained in:
1 parent
9748c8e9e0
commit
49f4bb92bd
6 files changed
+131
-6
No files matched your search
@@ -783,7 +783,25 @@
|
|||||||
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ===== Internet temporaria para pagar (abre o app do banco) =====
|
||||||
|
async function startFreeAccess() {
|
||||||
|
if (!mac) return;
|
||||||
|
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 (d.ok) {
|
||||||
|
const mins = Math.round((d.seconds / 60) * 10) / 10;
|
||||||
|
toast('Internet liberada por ' + mins + ' min para pagar');
|
||||||
|
}
|
||||||
|
} catch { /* segue */ }
|
||||||
|
}
|
||||||
|
|
||||||
loadPlans();
|
loadPlans();
|
||||||
|
startFreeAccess();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -15,6 +15,7 @@ const config = {
|
|||||||
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
||||||
},
|
},
|
||||||
port: parseInt(process.env.PORT || '3000', 10),
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
|
freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 90),
|
||||||
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
||||||
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
||||||
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
||||||
|
|||||||
+3
-2
@@ -11,7 +11,7 @@ const DEFAULT_PLANS = [
|
|||||||
{ id: 'plano-7d', name: '7 Dias', price: 15.00, profile: 'pix-7d', uptime: '1w', speed: '10M/3M', active: true },
|
{ id: 'plano-7d', name: '7 Dias', price: 15.00, profile: 'pix-7d', uptime: '1w', speed: '10M/3M', active: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
let db = { plans: [], payments: [] };
|
let db = { plans: [], payments: [], tempAccess: [] };
|
||||||
|
|
||||||
export function initDb() {
|
export function initDb() {
|
||||||
fs.mkdirSync(config.dataDir, { recursive: true });
|
fs.mkdirSync(config.dataDir, { recursive: true });
|
||||||
@@ -19,8 +19,9 @@ export function initDb() {
|
|||||||
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
|
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
|
||||||
if (!db.plans?.length) db.plans = structuredClone(DEFAULT_PLANS);
|
if (!db.plans?.length) db.plans = structuredClone(DEFAULT_PLANS);
|
||||||
if (!db.payments) db.payments = [];
|
if (!db.payments) db.payments = [];
|
||||||
|
if (!db.tempAccess) db.tempAccess = [];
|
||||||
} else {
|
} else {
|
||||||
db = { plans: structuredClone(DEFAULT_PLANS), payments: [] };
|
db = { plans: structuredClone(DEFAULT_PLANS), payments: [], tempAccess: [] };
|
||||||
saveDb();
|
saveDb();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-2
@@ -4,7 +4,7 @@ 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, cancelOrder, validCpf } from './mp.js';
|
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
|
||||||
import { createHotspotUser } from './ros.js';
|
import { createHotspotUser, allowPaymentAccess, revokePaymentAccess } from './ros.js';
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -23,6 +23,9 @@ async function fulfill(payment) {
|
|||||||
payment.voucher = { user, pass };
|
payment.voucher = { user, pass };
|
||||||
payment.status = 'paid';
|
payment.status = 'paid';
|
||||||
payment.paidAt = new Date().toISOString();
|
payment.paidAt = new Date().toISOString();
|
||||||
|
const db = getDb();
|
||||||
|
db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== payment.mac);
|
||||||
|
if (payment.mac) revokePaymentAccess(payment.mac).catch(() => {});
|
||||||
saveDb();
|
saveDb();
|
||||||
console.log(`[PAGA] ${payment.planId} -> voucher ${user}`);
|
console.log(`[PAGA] ${payment.planId} -> voucher ${user}`);
|
||||||
return payment;
|
return payment;
|
||||||
@@ -45,6 +48,39 @@ async function checkPayment(payment) {
|
|||||||
|
|
||||||
// ===== Rotas =====
|
// ===== Rotas =====
|
||||||
|
|
||||||
|
// ===== Internet temporaria para pagar (bypass do hotspot) =====
|
||||||
|
app.post('/api/access/start', async (req, res) => {
|
||||||
|
const { mac } = req.body || {};
|
||||||
|
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
|
||||||
|
try {
|
||||||
|
const r = await allowPaymentAccess(mac);
|
||||||
|
const now = Date.now();
|
||||||
|
const db = getDb();
|
||||||
|
db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== mac);
|
||||||
|
db.tempAccess.push({
|
||||||
|
mac,
|
||||||
|
ip: r.ip,
|
||||||
|
createdAt: new Date(now).toISOString(),
|
||||||
|
expiresAt: now + config.freeAccessSeconds * 1000,
|
||||||
|
});
|
||||||
|
saveDb();
|
||||||
|
res.json({ ok: true, seconds: config.freeAccessSeconds, ip: r.ip });
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[ACESSO]', e.message);
|
||||||
|
res.status(500).json({ error: e.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== Reconciliacao manual (caso o webhook falhe) =====
|
||||||
|
app.post('/api/reconcile', async (req, res) => {
|
||||||
|
const { orderId } = req.body || {};
|
||||||
|
if (!orderId) return res.status(400).json({ error: 'orderId obrigatorio' });
|
||||||
|
const payment = getDb().payments.find((p) => String(p.mpId) === String(orderId));
|
||||||
|
if (!payment) return res.status(404).json({ error: 'pedido nao encontrado' });
|
||||||
|
await checkPayment(payment);
|
||||||
|
res.json({ status: payment.status, voucher: payment.voucher, orderId: payment.mpId });
|
||||||
|
});
|
||||||
|
|
||||||
app.get('/api/plans', (req, res) => {
|
app.get('/api/plans', (req, res) => {
|
||||||
res.json(getDb().plans.filter((p) => p.active));
|
res.json(getDb().plans.filter((p) => p.active));
|
||||||
});
|
});
|
||||||
@@ -115,7 +151,7 @@ app.post('/api/checkout', async (req, res) => {
|
|||||||
app.post('/api/mp/webhook', async (req, res) => {
|
app.post('/api/mp/webhook', async (req, res) => {
|
||||||
res.sendStatus(200); // responde rápido para o MP não reenviar
|
res.sendStatus(200); // responde rápido para o MP não reenviar
|
||||||
try {
|
try {
|
||||||
const mpId = req.body?.data?.id || req.query?.['data.id'];
|
const mpId = req.body?.data?.id || req.body?.id || req.query?.['data.id'] || req.query?.id;
|
||||||
if (!mpId) return;
|
if (!mpId) return;
|
||||||
const payment = getDb().payments.find((p) => String(p.mpId) === String(mpId));
|
const payment = getDb().payments.find((p) => String(p.mpId) === String(mpId));
|
||||||
if (!payment) {
|
if (!payment) {
|
||||||
@@ -190,6 +226,18 @@ setInterval(async () => {
|
|||||||
for (const p of pendings) await checkPayment(p);
|
for (const p of pendings) await checkPayment(p);
|
||||||
}, 15000);
|
}, 15000);
|
||||||
|
|
||||||
|
// ===== Expira acessos temporarios de pagamento =====
|
||||||
|
setInterval(async () => {
|
||||||
|
const db = getDb();
|
||||||
|
const now = Date.now();
|
||||||
|
const expired = (db.tempAccess || []).filter((t) => t.expiresAt <= now);
|
||||||
|
if (!expired.length) return;
|
||||||
|
for (const t of expired) await revokePaymentAccess(t.mac).catch(() => {});
|
||||||
|
db.tempAccess = (db.tempAccess || []).filter((t) => t.expiresAt > now);
|
||||||
|
saveDb();
|
||||||
|
console.log(`[ACESSO] ${expired.length} liberacao(oes) temporaria(s) expirada(s)`);
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
app.listen(config.port, '0.0.0.0', () => {
|
app.listen(config.port, '0.0.0.0', () => {
|
||||||
console.log(`pix-hotspot rodando em ${config.baseUrl} (porta ${config.port})`);
|
console.log(`pix-hotspot rodando em ${config.baseUrl} (porta ${config.port})`);
|
||||||
console.log(`MikroTik: ${config.mikrotik.host}:${config.mikrotik.port}`);
|
console.log(`MikroTik: ${config.mikrotik.host}:${config.mikrotik.port}`);
|
||||||
|
|||||||
+4
-2
@@ -159,9 +159,11 @@ export async function getPaymentStatus(mpId) {
|
|||||||
try {
|
try {
|
||||||
if (isOrder) {
|
if (isOrder) {
|
||||||
const data = await new Order(getClient()).get({ id: mpId });
|
const data = await new Order(getClient()).get({ id: mpId });
|
||||||
|
const pay = data.transactions?.payments?.[0] || {};
|
||||||
// order: action_required (waiting_transfer) = pendente | processed = pago
|
// order: action_required (waiting_transfer) = pendente | processed = pago
|
||||||
if (data.status === 'processed') return 'approved';
|
if (data.status === 'processed' || pay.status === 'approved') return 'approved';
|
||||||
if (data.status === 'cancelled' || data.status === 'rejected') return data.status;
|
if (['cancelled', 'rejected', 'expired', 'refunded'].includes(data.status)) return data.status;
|
||||||
|
if (['cancelled', 'rejected', 'refunded'].includes(pay.status)) return pay.status;
|
||||||
return 'pending';
|
return 'pending';
|
||||||
}
|
}
|
||||||
const data = await new Payment(getClient()).get({ id: mpId });
|
const data = await new Payment(getClient()).get({ id: mpId });
|
||||||
|
|||||||
@@ -133,6 +133,61 @@ export async function createHotspotUser(name, password, profile, uptime) {
|
|||||||
await rosCommand(words);
|
await rosCommand(words);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== Acesso temporario para pagamento =====
|
||||||
|
// Libera internet (bypass do hotspot) por alguns minutos, com limite de banda,
|
||||||
|
// para o convidado abrir o app do banco e pagar o PIX.
|
||||||
|
|
||||||
|
async function hostAddressByMac(mac) {
|
||||||
|
try {
|
||||||
|
const replies = await rosCommand(['/ip/hotspot/host/print', `?mac-address=${mac}`]);
|
||||||
|
const row = (replies || [])[0] || [];
|
||||||
|
const addr = row.find((w) => w.startsWith('=address='));
|
||||||
|
return addr ? addr.slice(9) : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function allowPaymentAccess(mac, speed = '3M/3M') {
|
||||||
|
if (!mac) throw new Error('mac obrigatorio');
|
||||||
|
const ip = await hostAddressByMac(mac);
|
||||||
|
|
||||||
|
// bypass do hotspot por MAC (funciona mesmo antes do login)
|
||||||
|
try {
|
||||||
|
await rosCommand(['/ip/hotspot/ip-binding/add', `=mac-address=${mac}`, '=type=bypassed', '=comment=pix-pagando']);
|
||||||
|
} catch (e) {
|
||||||
|
if (!/already|duplicate/i.test(e.message)) throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
// limite de banda para essa liberacao temporaria
|
||||||
|
if (ip) {
|
||||||
|
try {
|
||||||
|
await rosCommand(['/queue/simple/add', `=name=pixpagando-${mac}`, `=target=${ip}/32`, `=max-limit=${speed}`]);
|
||||||
|
} catch (e) {
|
||||||
|
if (!/already|duplicate/i.test(e.message)) throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ip, mac };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokePaymentAccess(mac) {
|
||||||
|
if (!mac) return;
|
||||||
|
try {
|
||||||
|
const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);
|
||||||
|
for (const row of bindings || []) {
|
||||||
|
const id = row.find((w) => w.startsWith('=.id='));
|
||||||
|
if (id) await rosCommand(['/ip/hotspot/ip-binding/remove', `=numbers=${id.slice(5)}`]);
|
||||||
|
}
|
||||||
|
} catch { /* ignora */ }
|
||||||
|
try {
|
||||||
|
const queues = await rosCommand(['/queue/simple/print', `?name=pixpagando-${mac}`]);
|
||||||
|
for (const row of queues || []) {
|
||||||
|
const id = row.find((w) => w.startsWith('=.id='));
|
||||||
|
if (id) await rosCommand(['/queue/simple/remove', `=numbers=${id.slice(5)}`]);
|
||||||
|
}
|
||||||
|
} catch { /* ignora */ }
|
||||||
|
}
|
||||||
|
|
||||||
export async function mikrotikPing() {
|
export async function mikrotikPing() {
|
||||||
const replies = await rosCommand(['/system/identity/print']);
|
const replies = await rosCommand(['/system/identity/print']);
|
||||||
return replies?.[0]?.find((w) => w.startsWith('=name='))?.slice(6) || 'ok';
|
return replies?.[0]?.find((w) => w.startsWith('=name='))?.slice(6) || 'ok';
|
||||||
|
|||||||
Reference in new issue
Block a user