feat: qualidade MP - items/payer/statement_descriptor/deviceId/cancel + form CPF no portal
build-image / build-push (push) Successful in 1m36s
build-image / build-push (push) Successful in 1m36s
This commit is contained in:
1 parent
67608421b4
commit
59d6aa0ed3
4 files changed
+250
-12
No files matched your search
@@ -6,6 +6,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const config = {
|
||||
mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
|
||||
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
|
||||
mpPublicKey: process.env.MP_PUBLIC_KEY || '',
|
||||
mikrotik: {
|
||||
host: process.env.MIKROTIK_HOST || '192.168.3.81',
|
||||
port: parseInt(process.env.MIKROTIK_PORT || '8728', 10),
|
||||
|
||||
+42
-3
@@ -3,7 +3,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import config from './config.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';
|
||||
|
||||
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) => {
|
||||
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);
|
||||
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 = {
|
||||
id: 'P' + Date.now() + genCode(4),
|
||||
@@ -67,7 +74,18 @@ app.post('/api/checkout', async (req, res) => {
|
||||
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.qrCodeBase64 = pix.qrCodeBase64;
|
||||
payment.copiaCola = pix.copiaCola;
|
||||
@@ -136,6 +154,27 @@ app.post('/api/admin/plans', adminAuth, (req, res) => {
|
||||
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) => {
|
||||
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
|
||||
});
|
||||
|
||||
+89
-7
@@ -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,
|
||||
// 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');
|
||||
|
||||
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', {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'X-Idempotency-Key': reference + '-' + Date.now() }),
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
type: 'online',
|
||||
external_reference: reference,
|
||||
description,
|
||||
total_amount: amount.toFixed(2),
|
||||
description: 'WiFi ' + planName,
|
||||
total_amount: Number(amount).toFixed(2),
|
||||
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: {
|
||||
payments: [
|
||||
{
|
||||
amount: amount.toFixed(2),
|
||||
amount: Number(amount).toFixed(2),
|
||||
payment_method: { id: 'pix', type: 'bank_transfer' },
|
||||
expiration_time: 'PT24H',
|
||||
},
|
||||
@@ -50,7 +121,8 @@ export async function createPixPayment(amount, reference, description) {
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
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 || {};
|
||||
@@ -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) {
|
||||
if (!ready()) throw new Error('Mercado Pago nao configurado');
|
||||
|
||||
|
||||
Reference in new issue
Block a user