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; }; export type MpPreference = { id: string; initPoint: string; sandboxInitPoint: string | null; }; /** * 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, auto_return: 'approved', 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 ?? []; const match = results.find( (payment) => payment.external_reference === externalReference, ); 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, }; }