feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor solo para suscripciones nuevas; sync, cancel y webhook usan row.provider. - Migración add_billing_providers (provider, checkout_ref, ids genéricos). - fix: /authorized_payments/search respondía 400 "Invalid value for limit"; se pagina por offset sin limit. - fix: si falla la consulta de cobros, la sync guarda igual el estado de la suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import { logger } from '@/logger';
|
||||
import { MP_API_URL, MpApiError } from '@/modules/mp/lib';
|
||||
|
||||
// Mercado Pago Subscriptions (preapproval), called with Gruperly's own
|
||||
// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`.
|
||||
|
||||
export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled';
|
||||
|
||||
export type CreatePreapprovalInput = {
|
||||
reason: string;
|
||||
/** Our user id: the only thing that ties the subscription back to a professor. */
|
||||
externalReference: string;
|
||||
/** Mercado Pago requires the payer to log in with this exact email. */
|
||||
payerEmail: string;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
backUrl: string;
|
||||
/** First charge date; omitted means right after the professor authorizes. */
|
||||
startDate?: Date;
|
||||
};
|
||||
|
||||
export type MpPreapproval = {
|
||||
id: string;
|
||||
status: MpPreapprovalStatus | string;
|
||||
externalReference: string | null;
|
||||
initPoint: string | null;
|
||||
nextPaymentDate: string | null;
|
||||
};
|
||||
|
||||
export type MpAuthorizedPayment = {
|
||||
id: string;
|
||||
preapprovalId: string;
|
||||
/** Status of the invoice itself: scheduled, processed, recycling, cancelled. */
|
||||
status: string;
|
||||
/** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */
|
||||
paymentStatus: string | null;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
/** When the charge was debited (or attempted), ISO. */
|
||||
debitDate: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
async function request(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
init: { method?: string; body?: unknown } = {},
|
||||
): Promise<Record<string, unknown>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${MP_API_URL}${path}`, {
|
||||
method: init.method ?? 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: init.body === undefined ? undefined : JSON.stringify(init.body),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const reason = typeof payload?.message === 'string' ? payload.message : null;
|
||||
// The path carries ids, never tokens or emails; the body is not logged.
|
||||
logger.error(
|
||||
{ status: response.status, reason, path: path.split('?')[0] },
|
||||
'Mercado Pago subscriptions request failed',
|
||||
);
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function toPreapproval(payload: Record<string, unknown>): MpPreapproval {
|
||||
return {
|
||||
id: String(payload.id),
|
||||
status: String(payload.status),
|
||||
externalReference:
|
||||
typeof payload.external_reference === 'string' ? payload.external_reference : null,
|
||||
initPoint: typeof payload.init_point === 'string' ? payload.init_point : null,
|
||||
nextPaymentDate:
|
||||
typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a monthly subscription waiting for the professor's authorization.
|
||||
* Nothing is charged until they log in to Mercado Pago through `initPoint`.
|
||||
*/
|
||||
export async function createPreapproval(
|
||||
accessToken: string,
|
||||
input: CreatePreapprovalInput,
|
||||
): Promise<MpPreapproval> {
|
||||
const payload = await request(accessToken, '/preapproval', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
reason: input.reason,
|
||||
external_reference: input.externalReference,
|
||||
payer_email: input.payerEmail,
|
||||
back_url: input.backUrl,
|
||||
status: 'pending',
|
||||
auto_recurring: {
|
||||
frequency: 1,
|
||||
frequency_type: 'months',
|
||||
transaction_amount: input.amount,
|
||||
currency_id: input.currencyId,
|
||||
...(input.startDate ? { start_date: input.startDate.toISOString() } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toPreapproval(payload);
|
||||
}
|
||||
|
||||
export async function getPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
|
||||
}
|
||||
|
||||
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(
|
||||
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
body: { status: 'cancelled' },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
||||
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
||||
return {
|
||||
id: String(payload.id),
|
||||
preapprovalId: String(payload.preapproval_id),
|
||||
status: String(payload.status),
|
||||
paymentStatus: typeof payment?.status === 'string' ? payment.status : null,
|
||||
amount: Number(payload.transaction_amount ?? 0),
|
||||
currencyId: String(payload.currency_id ?? ''),
|
||||
debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null,
|
||||
createdAt: typeof payload.date_created === 'string' ? payload.date_created : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAuthorizedPayment(
|
||||
accessToken: string,
|
||||
id: string,
|
||||
): Promise<MpAuthorizedPayment> {
|
||||
return toAuthorizedPayment(
|
||||
await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** Safety net for the paging loop: one invoice a month, this is decades. */
|
||||
const MAX_INVOICE_PAGES = 20;
|
||||
|
||||
/**
|
||||
* The invoices of one subscription, newest first as Mercado Pago returns them.
|
||||
* No `limit`: Mercado Pago answers 400 "Invalid value for limit" to values it
|
||||
* accepts elsewhere, so it pages with its own default and we follow `offset`.
|
||||
*/
|
||||
export async function searchAuthorizedPayments(
|
||||
accessToken: string,
|
||||
preapprovalId: string,
|
||||
): Promise<MpAuthorizedPayment[]> {
|
||||
const invoices: MpAuthorizedPayment[] = [];
|
||||
for (let page = 0; page < MAX_INVOICE_PAGES; page++) {
|
||||
const query = new URLSearchParams({ preapproval_id: preapprovalId, offset: String(invoices.length) });
|
||||
const payload = await request(accessToken, `/authorized_payments/search?${query}`);
|
||||
const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
|
||||
invoices.push(...results.map(toAuthorizedPayment));
|
||||
|
||||
const total = Number((payload.paging as Record<string, unknown> | undefined)?.total);
|
||||
if (results.length === 0 || !Number.isFinite(total) || invoices.length >= total) break;
|
||||
}
|
||||
return invoices;
|
||||
}
|
||||
|
||||
export type PreapprovalClient = {
|
||||
createPreapproval: typeof createPreapproval;
|
||||
getPreapproval: typeof getPreapproval;
|
||||
cancelPreapproval: typeof cancelPreapproval;
|
||||
getAuthorizedPayment: typeof getAuthorizedPayment;
|
||||
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
||||
};
|
||||
|
||||
export const mpPreapprovalClient: PreapprovalClient = {
|
||||
createPreapproval,
|
||||
getPreapproval,
|
||||
cancelPreapproval,
|
||||
getAuthorizedPayment,
|
||||
searchAuthorizedPayments,
|
||||
};
|
||||
Reference in New Issue
Block a user