Plans: - Plan limits and Pro prices per country live in the database (plan_configs, plan_prices, seeded with the previous constants) and are read through PlanCatalog (30 s cache, defaults as fallback). - /admin/plans edits limits (with the count of accounts that would become read-only) and prices, optionally pushing the new price to live subscriptions from their next charge (MP preapproval amount, Stripe item without proration) via the ApplyPriceChanges job, with an email and a notice on /billing. - GET /billing/plans feeds the onboarding and the billing screen. Mercado Pago: - The Pro checkout returns through GET /billing/return on API_PUBLIC_URL, since MP refuses a back_url on localhost. - The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the session, requires the session to own the state, and redirects instead of answering JSON on unexpected errors. - Checkout Pro links skip auto_return off public HTTPS and carry a notification_url to POST /payments/webhooks/mp/:paymentId, which confirms the payment with the owner's token (same rule as the polling job, which stays as fallback). The search now prefers the approved attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
214 lines
7.4 KiB
TypeScript
214 lines
7.4 KiB
TypeScript
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' },
|
|
}),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Changes the monthly amount of a live preapproval. Mercado Pago applies it to
|
|
* the debits that follow; the ones already made are untouched.
|
|
*/
|
|
export async function updatePreapprovalAmount(
|
|
accessToken: string,
|
|
id: string,
|
|
input: { amount: number; currencyId: string },
|
|
): Promise<MpPreapproval> {
|
|
return toPreapproval(
|
|
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
|
method: 'PUT',
|
|
body: { auto_recurring: { transaction_amount: input.amount, currency_id: input.currencyId } },
|
|
}),
|
|
);
|
|
}
|
|
|
|
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;
|
|
updatePreapprovalAmount: typeof updatePreapprovalAmount;
|
|
getAuthorizedPayment: typeof getAuthorizedPayment;
|
|
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
|
};
|
|
|
|
export const mpPreapprovalClient: PreapprovalClient = {
|
|
createPreapproval,
|
|
getPreapproval,
|
|
cancelPreapproval,
|
|
updatePreapprovalAmount,
|
|
getAuthorizedPayment,
|
|
searchAuthorizedPayments,
|
|
};
|