feat: migra MP para Orders API + webhook IPN + BASE_URL publico
build-image / build-push (push) Successful in 1m38s
build-image / build-push (push) Successful in 1m38s
This commit is contained in:
1 parent
aec109e654
commit
2b454c2bb7
2 files changed
+71
-26
No files matched your search
+69
-24
@@ -1,41 +1,86 @@
|
||||
import { MercadoPagoConfig, Payment } from 'mercadopago';
|
||||
import config from './config.js';
|
||||
|
||||
let paymentApi = null;
|
||||
const API = 'https://api.mercadopago.com';
|
||||
|
||||
export function initMp() {
|
||||
if (!config.mpAccessToken || config.mpAccessToken.includes('COLE_SEU')) {
|
||||
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao');
|
||||
return;
|
||||
}
|
||||
const client = new MercadoPagoConfig({ accessToken: config.mpAccessToken });
|
||||
paymentApi = new Payment(client);
|
||||
function authHeaders(extra = {}) {
|
||||
const auth = ['Bearer', config.mpAccessToken].join(' ');
|
||||
return {
|
||||
Authorization: auth,
|
||||
'Content-Type': 'application/json',
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
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) {
|
||||
if (!paymentApi) throw new Error('Mercado Pago nao configurado');
|
||||
const result = await paymentApi.create({
|
||||
body: {
|
||||
transaction_amount: amount,
|
||||
payment_method_id: 'pix',
|
||||
if (!ready()) throw new Error('Mercado Pago nao configurado');
|
||||
|
||||
const res = await fetch(API + '/v1/orders', {
|
||||
method: 'POST',
|
||||
headers: authHeaders({ 'X-Idempotency-Key': reference + '-' + Date.now() }),
|
||||
body: JSON.stringify({
|
||||
type: 'online',
|
||||
external_reference: reference,
|
||||
description,
|
||||
notification_url: config.baseUrl + '/api/mp/webhook',
|
||||
total_amount: amount.toFixed(2),
|
||||
processing_mode: 'automatic',
|
||||
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 {
|
||||
mpId: result.id,
|
||||
qrCodeBase64: tx.qr_code_base64 || null,
|
||||
copiaCola: tx.qr_code || tx.ticket_url || '',
|
||||
status: result.status,
|
||||
mpId: data.id,
|
||||
qrCodeBase64: pm.qr_code_base64 || null,
|
||||
copiaCola: pm.qr_code || pm.ticket_url || '',
|
||||
status: data.status,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPaymentStatus(mpId) {
|
||||
if (!paymentApi) throw new Error('Mercado Pago nao configurado');
|
||||
const result = await paymentApi.get({ id: mpId });
|
||||
return result.status; // pending | approved | rejected | cancelled | ...
|
||||
if (!ready()) throw new Error('Mercado Pago nao configurado');
|
||||
|
||||
// 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
@@ -24,10 +24,10 @@ services:
|
||||
MIKROTIK_HOST: "192.168.3.81" # IP do hAP lite na sua rede
|
||||
MIKROTIK_PORT: "8728"
|
||||
MIKROTIK_USER: "api-pix"
|
||||
MIKROTIK_PASSWORD: ""
|
||||
MIKROTIK_PASSWORD: "Pix-2026!"
|
||||
MIKROTIK_SERVER: "guest-hotspot" # nome do servidor hotspot
|
||||
|
||||
# ===== Backend =====
|
||||
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"
|
||||
Reference in new issue
Block a user