feat: SDK oficial mercadopago v2 no backend (Order/Payment) + device id via meliSessionId
build-image / build-push (push) Successful in 1m39s
build-image / build-push (push) Successful in 1m39s
This commit is contained in:
1 parent
59d6aa0ed3
commit
a8c513dc2c
3 files changed
+77
-73
No files matched your search
Generated
+1
-1
@@ -9,7 +9,7 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"express": "^4.19.2",
|
||||
"mercadopago": "^2.0.15"
|
||||
"mercadopago": "^2.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
|
||||
@@ -9,6 +9,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.19.2",
|
||||
"mercadopago": "^2.0.15"
|
||||
"mercadopago": "^2.13.0"
|
||||
}
|
||||
}
|
||||
+75
-71
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user