Files
gruperly/apps/backend/src/modules/mp/lib/mp-http.ts
Jose Selesan aac142d324 feat(billing): configurable plans from the backoffice and MP payment notifications
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>
2026-11-11 07:50:14 -03:00

159 lines
5.2 KiB
TypeScript

import { logger } from '@/logger';
import { MpApiError } from './mp-oauth';
export const MP_API_URL = 'https://api.mercadopago.com';
// Mercado Pago runs the seller's money straight into the professor's own
// account: no platform_id of ours and no fee split.
export type MpCreatePreferenceInput = {
title: string;
unitPrice: number;
currencyId: string;
externalReference: string;
/** Where the buyer lands after paying (pending/success/failure). */
backUrl: string;
/** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */
notificationUrl?: string;
};
export type MpPreference = {
id: string;
initPoint: string;
sandboxInitPoint: string | null;
};
/**
* Mercado Pago refuses `auto_return` (`invalid_auto_return`) and notification
* URLs unless they are public HTTPS. In local development the web is on
* localhost: the buyer then gets MP's "back to the site" button instead of the
* automatic redirect, and without a tunnel only the polling confirms payments.
*/
export function isPublicHttpsUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
} catch {
return false;
}
}
/**
* Creates a Checkout Pro preference in the seller's account. This is a payment
* *link*: nothing is charged, and creating it again after a lost connection is
* safe (same external_reference would be a new link for the same payment).
*/
export async function createCheckoutPreference(
accessToken: string,
input: MpCreatePreferenceInput,
): Promise<MpPreference> {
let response: Response;
try {
response = await fetch(`${MP_API_URL}/checkout/preferences`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
items: [
{
title: input.title,
currency_id: input.currencyId,
quantity: 1,
unit_price: input.unitPrice,
},
],
external_reference: input.externalReference,
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
? { notification_url: input.notificationUrl }
: {}),
back_urls: {
success: input.backUrl,
pending: input.backUrl,
failure: input.backUrl,
},
}),
});
} catch (error) {
logger.error({ err: error }, 'Mercado Pago preferences endpoint 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?.error === 'string' ? payload.error : null;
logger.error(
{ status: response.status, reason },
'Mercado Pago preferences request failed',
);
throw new MpApiError(response.status, reason);
}
const payload = (await response.json()) as Record<string, unknown>;
return {
id: String(payload.id),
initPoint: String(payload.init_point),
sandboxInitPoint: payload.sandbox_init_point == null ? null : String(payload.sandbox_init_point),
};
}
export type MpSearchedPayment = {
id: string;
status: string;
externalReference: string;
liveMode: boolean;
dateApproved: string | null;
};
/**
* Finds a payment created for one of our payment rows.
*
* This is the reconciliation path: instead of trusting a webhook, the job asks
* the seller's account for payments whose `external_reference` is our payment
* id. Only an approved payment whose reference matches ours is a PAID row.
*/
export async function searchMpPaymentByExternalReference(
accessToken: string,
externalReference: string,
): Promise<MpSearchedPayment | null> {
const url = new URL(`${MP_API_URL}/v1/payments/search`);
url.searchParams.set('external_reference', externalReference);
let response: Response;
try {
response = await fetch(url, {
headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` },
});
} catch (error) {
logger.error({ err: error }, 'Mercado Pago payments search unreachable');
throw new MpApiError(0, null);
}
if (!response.ok) {
logger.error({ status: response.status }, 'Mercado Pago payments search failed');
throw new MpApiError(response.status, null);
}
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
const results = payload?.results ?? [];
// A rejected attempt and a later approved one share the reference: the
// approved one wins, whatever order Mercado Pago lists them in.
const ours = results.filter((payment) => payment.external_reference === externalReference);
const match = ours.find((payment) => payment.status === 'approved') ?? ours[0];
if (!match) {
return null;
}
return {
id: String(match.id),
status: String(match.status),
externalReference: String(match.external_reference),
liveMode: Boolean(match.live_mode),
dateApproved:
typeof match.date_approved === 'string' ? match.date_approved : null,
};
}