feat: migra MP para Orders API + webhook IPN + BASE_URL publico
build-image / build-push (push) Successful in 1m38s

This commit is contained in:
jfeng committed 2026-10-21 21:14:38 -03:00
1 parent aec109e654
commit 2b454c2bb7
2 files changed
+71 -26

No files matched your search

+69 -24
View File
@@ -1,41 +1,86 @@
import { MercadoPagoConfig, Payment } from 'mercadopago';
import config from './config.js'; import config from './config.js';
let paymentApi = null; const API = 'https://api.mercadopago.com';
export function initMp() { function authHeaders(extra = {}) {
if (!config.mpAccessToken || config.mpAccessToken.includes('COLE_SEU')) { const auth = ['Bearer', config.mpAccessToken].join(' ');
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao'); return {
return; Authorization: auth,
} 'Content-Type': 'application/json',
const client = new MercadoPagoConfig({ accessToken: config.mpAccessToken }); ...extra,
paymentApi = new Payment(client); };
} }
function ready() {
return config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU');
}
export function initMp() {
if (!ready()) {
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao');
}
}
// 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(amount, reference, description) {
if (!paymentApi) throw new Error('Mercado Pago nao configurado'); if (!ready()) throw new Error('Mercado Pago nao configurado');
const result = await paymentApi.create({
body: { const res = await fetch(API + '/v1/orders', {
transaction_amount: amount, method: 'POST',
payment_method_id: 'pix', headers: authHeaders({ 'X-Idempotency-Key': reference + '-' + Date.now() }),
body: JSON.stringify({
type: 'online',
external_reference: reference, external_reference: reference,
description, description,
notification_url: config.baseUrl + '/api/mp/webhook', total_amount: amount.toFixed(2),
processing_mode: 'automatic',
payer: { email: '[email protected]' }, payer: { email: '[email protected]' },
transactions: {
payments: [
{
amount: amount.toFixed(2),
payment_method: { id: 'pix', type: 'bank_transfer' },
expiration_time: 'PT24H',
}, },
],
},
}),
}); });
const tx = result.point_of_interaction?.transaction_data;
if (!tx) throw new Error('Resposta do MP sem dados PIX'); const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data.message || data.error || 'Mercado Pago HTTP ' + res.status);
}
const pm = data.transactions?.payments?.[0]?.payment_method || {};
if (!pm.qr_code && !pm.ticket_url) throw new Error('Resposta do MP sem dados PIX');
return { return {
mpId: result.id, mpId: data.id,
qrCodeBase64: tx.qr_code_base64 || null, qrCodeBase64: pm.qr_code_base64 || null,
copiaCola: tx.qr_code || tx.ticket_url || '', copiaCola: pm.qr_code || pm.ticket_url || '',
status: result.status, status: data.status,
}; };
} }
export async function getPaymentStatus(mpId) { export async function getPaymentStatus(mpId) {
if (!paymentApi) throw new Error('Mercado Pago nao configurado'); if (!ready()) throw new Error('Mercado Pago nao configurado');
const result = await paymentApi.get({ id: mpId });
return result.status; // pending | approved | rejected | cancelled | ... // webhook pode notificar tanto a order (ORD...) quanto o pagamento (PAY...)
const isOrder = String(mpId).startsWith('ORD');
const url = isOrder ? API + '/v1/orders/' + mpId : API + '/v1/payments/' + mpId;
const res = await fetch(url, { headers: authHeaders() });
if (!res.ok) throw new Error('Mercado Pago HTTP ' + res.status);
const data = await res.json();
if (isOrder) {
// order: action_required (waiting_transfer) = pendente | processed = pago
if (data.status === 'processed') return 'approved';
if (data.status === 'cancelled' || data.status === 'rejected') return data.status;
return 'pending';
}
// payment: pending | approved | rejected | cancelled | expired ...
return data.status;
} }
+2 -2
View File
@@ -24,10 +24,10 @@ services:
MIKROTIK_HOST: "192.168.3.81" # IP do hAP lite na sua rede MIKROTIK_HOST: "192.168.3.81" # IP do hAP lite na sua rede
MIKROTIK_PORT: "8728" MIKROTIK_PORT: "8728"
MIKROTIK_USER: "api-pix" MIKROTIK_USER: "api-pix"
MIKROTIK_PASSWORD: "" MIKROTIK_PASSWORD: "Pix-2026!"
MIKROTIK_SERVER: "guest-hotspot" # nome do servidor hotspot MIKROTIK_SERVER: "guest-hotspot" # nome do servidor hotspot
# ===== Backend ===== # ===== Backend =====
PORT: "3000" PORT: "3000"
BASE_URL: "http://192.168.3.100:3000" # IP do ZimaOS (portal de pagamento) BASE_URL: "https://hotspot.jf.eng.br"
ADMIN_TOKEN: "troque-este-token-aleatorio-grande" ADMIN_TOKEN: "troque-este-token-aleatorio-grande"