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",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.19.2",
|
"express": "^4.19.2",
|
||||||
"mercadopago": "^2.0.15"
|
"mercadopago": "^2.13.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/accepts": {
|
"node_modules/accepts": {
|
||||||
|
|||||||
@@ -9,6 +9,6 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.19.2",
|
"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';
|
import config from './config.js';
|
||||||
|
|
||||||
const API = 'https://api.mercadopago.com';
|
let client = null;
|
||||||
|
|
||||||
function authHeaders(extra = {}) {
|
|
||||||
const auth = ['Bearer', config.mpAccessToken].join(' ');
|
|
||||||
return {
|
|
||||||
Authorization: auth,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...extra,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function ready() {
|
function ready() {
|
||||||
return config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU');
|
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() {
|
export function initMp() {
|
||||||
if (!ready()) {
|
if (!ready()) {
|
||||||
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao');
|
console.warn('[MP] MP_ACCESS_TOKEN nao configurado - pagamentos nao funcionarao');
|
||||||
@@ -45,11 +43,20 @@ function validCpf(cpf) {
|
|||||||
|
|
||||||
export { validCpf };
|
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".
|
// a legada /v1/payments retorna 401 "Unauthorized use of live credentials".
|
||||||
export async function createPixPayment(opts) {
|
export async function createPixPayment(opts) {
|
||||||
if (!ready()) throw new Error('Mercado Pago nao configurado');
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
amount,
|
amount,
|
||||||
reference,
|
reference,
|
||||||
@@ -75,9 +82,6 @@ export async function createPixPayment(opts) {
|
|||||||
payer.identification = { type: 'CPF', number: cpf };
|
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 = {
|
const additionalInfo = {
|
||||||
'payer.registration_date': registrationDate || new Date().toISOString(),
|
'payer.registration_date': registrationDate || new Date().toISOString(),
|
||||||
'payer.authentication_type': 'WEB',
|
'payer.authentication_type': 'WEB',
|
||||||
@@ -85,44 +89,47 @@ export async function createPixPayment(opts) {
|
|||||||
};
|
};
|
||||||
if (lastPurchase) additionalInfo['payer.last_purchase'] = lastPurchase;
|
if (lastPurchase) additionalInfo['payer.last_purchase'] = lastPurchase;
|
||||||
|
|
||||||
const res = await fetch(API + '/v1/orders', {
|
const order = new Order(getClient());
|
||||||
method: 'POST',
|
|
||||||
headers,
|
let data;
|
||||||
body: JSON.stringify({
|
try {
|
||||||
type: 'online',
|
data = await order.create({
|
||||||
external_reference: reference,
|
body: {
|
||||||
description: 'WiFi ' + planName,
|
type: 'online',
|
||||||
total_amount: Number(amount).toFixed(2),
|
external_reference: reference,
|
||||||
processing_mode: 'automatic',
|
description: 'WiFi ' + planName,
|
||||||
config: { statement_descriptor: 'INCTG WIFI' },
|
total_amount: Number(amount).toFixed(2),
|
||||||
payer,
|
processing_mode: 'automatic',
|
||||||
items: [
|
config: { statement_descriptor: 'INCTG WIFI' },
|
||||||
{
|
payer,
|
||||||
title: 'WiFi ' + planName,
|
items: [
|
||||||
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),
|
title: 'WiFi ' + planName,
|
||||||
payment_method: { id: 'pix', type: 'bank_transfer' },
|
description: 'Acesso a internet - ' + planName,
|
||||||
expiration_time: 'PT24H',
|
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',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}),
|
requestOptions: {
|
||||||
});
|
idempotencyKey: reference + '-' + Date.now(),
|
||||||
|
...(deviceId ? { meliSessionId: deviceId } : {}),
|
||||||
const data = await res.json().catch(() => ({}));
|
},
|
||||||
if (!res.ok) {
|
});
|
||||||
const detail = data.errors?.map((e) => e.message || e.code).join('; ');
|
} catch (e) {
|
||||||
throw new Error(detail || data.message || data.error || 'Mercado Pago HTTP ' + res.status);
|
throw sdkError(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pm = data.transactions?.payments?.[0]?.payment_method || {};
|
const pm = data.transactions?.payments?.[0]?.payment_method || {};
|
||||||
@@ -137,32 +144,29 @@ export async function createPixPayment(opts) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function cancelOrder(mpId) {
|
export async function cancelOrder(mpId) {
|
||||||
if (!ready()) throw new Error('Mercado Pago nao configurado');
|
try {
|
||||||
const res = await fetch(API + '/v1/orders/' + mpId + '/cancel', {
|
return await new Order(getClient()).cancel({ id: mpId });
|
||||||
method: 'POST',
|
} catch (e) {
|
||||||
headers: authHeaders(),
|
throw sdkError(e);
|
||||||
});
|
}
|
||||||
if (!res.ok) throw new Error('Mercado Pago HTTP ' + res.status);
|
|
||||||
return res.json();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPaymentStatus(mpId) {
|
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...)
|
// webhook pode notificar tanto a order (ORD...) quanto o pagamento (PAY...)
|
||||||
const isOrder = String(mpId).startsWith('ORD');
|
const isOrder = String(mpId).startsWith('ORD');
|
||||||
const url = isOrder ? API + '/v1/orders/' + mpId : API + '/v1/payments/' + mpId;
|
|
||||||
|
|
||||||
const res = await fetch(url, { headers: authHeaders() });
|
try {
|
||||||
if (!res.ok) throw new Error('Mercado Pago HTTP ' + res.status);
|
if (isOrder) {
|
||||||
const data = await res.json();
|
const data = await new Order(getClient()).get({ id: mpId });
|
||||||
|
// order: action_required (waiting_transfer) = pendente | processed = pago
|
||||||
if (isOrder) {
|
if (data.status === 'processed') return 'approved';
|
||||||
// order: action_required (waiting_transfer) = pendente | processed = pago
|
if (data.status === 'cancelled' || data.status === 'rejected') return data.status;
|
||||||
if (data.status === 'processed') return 'approved';
|
return 'pending';
|
||||||
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