41 lines
1.3 KiB
JavaScript
41 lines
1.3 KiB
JavaScript
import { MercadoPagoConfig, Payment } from 'mercadopago';
|
|
import config from './config.js';
|
|
|
|
let paymentApi = null;
|
|
|
|
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);
|
|
}
|
|
|
|
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',
|
|
external_reference: reference,
|
|
description,
|
|
payer: { email: '[email protected]' },
|
|
},
|
|
});
|
|
const tx = result.point_of_interaction?.transaction_data;
|
|
if (!tx) 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,
|
|
};
|
|
}
|
|
|
|
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 | ...
|
|
}
|