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 { 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 | 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; 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 { 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[] } | 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, }; }