From a8c513dc2c973dfede723947b6c3b722a51be72e Mon Sep 17 00:00:00 2001 From: Jorge Fernando Date: Wed, 21 Oct 2026 22:21:23 -0300 Subject: [PATCH] feat: SDK oficial mercadopago v2 no backend (Order/Payment) + device id via meliSessionId --- backend/package-lock.json | 2 +- backend/package.json | 2 +- backend/src/mp.js | 146 ++++++++++++++++++++------------------ 3 files changed, 77 insertions(+), 73 deletions(-) diff --git a/backend/package-lock.json b/backend/package-lock.json index fe1b79f..11c2bcc 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "dependencies": { "express": "^4.19.2", - "mercadopago": "^2.0.15" + "mercadopago": "^2.13.0" } }, "node_modules/accepts": { diff --git a/backend/package.json b/backend/package.json index 1636d3e..3d07b28 100644 --- a/backend/package.json +++ b/backend/package.json @@ -9,6 +9,6 @@ }, "dependencies": { "express": "^4.19.2", - "mercadopago": "^2.0.15" + "mercadopago": "^2.13.0" } } diff --git a/backend/src/mp.js b/backend/src/mp.js index 6f06e6b..355478e 100644 --- a/backend/src/mp.js +++ b/backend/src/mp.js @@ -1,20 +1,18 @@ +import { MercadoPagoConfig, Order, Payment } from 'mercadopago'; import config from './config.js'; -const API = 'https://api.mercadopago.com'; - -function authHeaders(extra = {}) { - const auth = ['Bearer', config.mpAccessToken].join(' '); - return { - Authorization: auth, - 'Content-Type': 'application/json', - ...extra, - }; -} +let client = null; function ready() { return config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'); } +function getClient() { + if (!ready()) throw new Error('Mercado Pago nao configurado'); + if (!client) client = new MercadoPagoConfig({ accessToken: config.mpAccessToken, options: { timeout: 15000 } }); + return client; +} + export function initMp() { if (!ready()) { console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao'); @@ -45,11 +43,20 @@ function validCpf(cpf) { export { validCpf }; -// Orders API (Checkout Transparente) - o app do MP esta marcado como API Orders, +function sdkError(e) { + const fromCause = Array.isArray(e?.cause) + ? e.cause.map((c) => c.message || c.code).filter(Boolean).join('; ') + : e?.cause?.message || ''; + const fromErrors = Array.isArray(e?.errors) + ? e.errors.map((c) => c.message || c.code).filter(Boolean).join('; ') + : ''; + const body = e?.message || ''; + return new Error(fromCause || fromErrors || body || 'Mercado Pago erro no SDK'); +} + +// Orders API via SDK oficial (backend) - o app esta marcado como API Orders, // a legada /v1/payments retorna 401 "Unauthorized use of live credentials". export async function createPixPayment(opts) { - if (!ready()) throw new Error('Mercado Pago nao configurado'); - const { amount, reference, @@ -75,9 +82,6 @@ export async function createPixPayment(opts) { 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', @@ -85,44 +89,47 @@ export async function createPixPayment(opts) { }; if (lastPurchase) additionalInfo['payer.last_purchase'] = lastPurchase; - const res = await fetch(API + '/v1/orders', { - method: 'POST', - headers, - body: JSON.stringify({ - type: 'online', - external_reference: reference, - description: 'WiFi ' + planName, - total_amount: Number(amount).toFixed(2), - processing_mode: 'automatic', - 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: [ + const order = new Order(getClient()); + + let data; + try { + data = await order.create({ + body: { + type: 'online', + external_reference: reference, + description: 'WiFi ' + planName, + total_amount: Number(amount).toFixed(2), + processing_mode: 'automatic', + config: { statement_descriptor: 'INCTG WIFI' }, + payer, + items: [ { - amount: Number(amount).toFixed(2), - payment_method: { id: 'pix', type: 'bank_transfer' }, - expiration_time: 'PT24H', + 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: Number(amount).toFixed(2), + payment_method: { id: 'pix', type: 'bank_transfer' }, + expiration_time: 'PT24H', + }, + ], + }, }, - }), - }); - - const data = await res.json().catch(() => ({})); - if (!res.ok) { - const detail = data.errors?.map((e) => e.message || e.code).join('; '); - throw new Error(detail || data.message || data.error || 'Mercado Pago HTTP ' + res.status); + requestOptions: { + idempotencyKey: reference + '-' + Date.now(), + ...(deviceId ? { meliSessionId: deviceId } : {}), + }, + }); + } catch (e) { + throw sdkError(e); } const pm = data.transactions?.payments?.[0]?.payment_method || {}; @@ -137,32 +144,29 @@ export async function createPixPayment(opts) { } 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(); + try { + return await new Order(getClient()).cancel({ id: mpId }); + } catch (e) { + throw sdkError(e); + } } export async function getPaymentStatus(mpId) { - 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'; + try { + if (isOrder) { + const data = await new Order(getClient()).get({ id: mpId }); + // 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'; + } + const data = await new Payment(getClient()).get({ id: mpId }); + // payment: pending | approved | rejected | cancelled | expired ... + return data.status; + } catch (e) { + throw sdkError(e); } - // payment: pending | approved | rejected | cancelled | expired ... - return data.status; }