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>
This commit is contained in:
@@ -15,17 +15,20 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||
import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||
import { CHECKOUT_BACK_PATH } from '../../lib';
|
||||
import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib';
|
||||
|
||||
type BatchDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||
apiOrigin?: string;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
@@ -128,6 +131,7 @@ export class CreatePaymentBatch {
|
||||
currencyId: currency,
|
||||
externalReference: payment.id,
|
||||
backUrl,
|
||||
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
|
||||
});
|
||||
link = preference;
|
||||
} catch (error) {
|
||||
|
||||
@@ -8,17 +8,20 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||
import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
import { CHECKOUT_BACK_PATH, type PaymentRecord, paymentNotificationUrl, toPaymentDto } from '../../lib';
|
||||
|
||||
type RenewDeps = {
|
||||
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||
apiOrigin?: string;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
@@ -94,6 +97,7 @@ export class RenewPaymentLink {
|
||||
currencyId: currency,
|
||||
externalReference: payment.id,
|
||||
backUrl,
|
||||
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
|
||||
17
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
17
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson } from '@/http/problem-details';
|
||||
import { HandleMpPaymentNotification } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
/**
|
||||
* Public (`isPublicApiRequest`): Mercado Pago calls it with the URL each
|
||||
* Checkout Pro link carries as `notification_url`.
|
||||
*/
|
||||
route.post('/webhooks/mp/:paymentId', async (c) => {
|
||||
const result = await new HandleMpPaymentNotification().execute(c.req.param('paymentId'));
|
||||
if (!result.ok) return problemJson(c, result.error);
|
||||
return c.json({ received: true });
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpProviderErrorProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { MpApiError } from '@/modules/mp/lib';
|
||||
import { type ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment } from '../../lib';
|
||||
|
||||
type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & {
|
||||
db?: Pick<PrismaClient, 'payment'>;
|
||||
};
|
||||
|
||||
export type MpPaymentNotificationOutcome = ConfirmMpPaymentOutcome | 'ignored';
|
||||
|
||||
/**
|
||||
* Mercado Pago says something happened to the payment of one of our links. The
|
||||
* body is not read: the payment id in the URL picks the row, and the owner's
|
||||
* account says whether it was approved (`confirmMpPayment`), so a forged or
|
||||
* repeated notification costs one lookup and changes nothing.
|
||||
*/
|
||||
export class HandleMpPaymentNotification {
|
||||
constructor(private readonly deps: HandleMpPaymentNotificationDeps = {}) {}
|
||||
|
||||
async execute(paymentId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
// OVERDUE too: a student can still pay a link after its due date.
|
||||
const payment = await db.payment.findFirst({
|
||||
where: { id: paymentId, status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
|
||||
select: { id: true, group: { select: { createdById: true } } },
|
||||
});
|
||||
if (!payment) return ok({ outcome: 'ignored' });
|
||||
|
||||
try {
|
||||
const outcome = await confirmMpPayment(db, { id: payment.id, ownerId: payment.group.createdById }, this.deps);
|
||||
return ok({ outcome });
|
||||
} catch (error) {
|
||||
if (!(error instanceof MpApiError)) throw error;
|
||||
// Not a 2xx, so Mercado Pago retries; the polling job is the fallback anyway.
|
||||
logger.warn({ paymentId: payment.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,13 @@ import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||
import { confirmMpPayment } from '../lib';
|
||||
|
||||
/**
|
||||
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
|
||||
* link is just a preference until someone pays it; this job asks the seller's
|
||||
* account for our `external_reference` and marks approved payments as PAID.
|
||||
*
|
||||
* This is the stopgap and the source of truth: if a webhook is ever added it
|
||||
* gives you the confirmation, but this job is what keeps the Cobros screen
|
||||
* correct even when a notification is lost.
|
||||
* Pulls payments from Mercado Pago. The notification
|
||||
* (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the
|
||||
* fallback for links created before it existed and for lost notifications.
|
||||
* Both go through `confirmMpPayment`.
|
||||
*/
|
||||
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
||||
const BATCH_LIMIT = 50;
|
||||
@@ -51,34 +49,21 @@ export class ReconcilePayments {
|
||||
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
||||
|
||||
for (const payment of awaiting) {
|
||||
const token = await getToken(payment.group.createdById);
|
||||
if (!token.ok) {
|
||||
// No usable token (not linked, or needs re-auth). Not a payment problem:
|
||||
// the row stays PENDING and the account notice tells the professor what to do.
|
||||
totals.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const found = await search(token.value.accessToken, payment.id);
|
||||
if (found && found.status === 'approved' && found.externalReference === payment.id) {
|
||||
await db.payment.update({
|
||||
where: { id: payment.id },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
mpPaymentId: found.id,
|
||||
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
||||
},
|
||||
});
|
||||
totals.paid += 1;
|
||||
}
|
||||
const outcome = await confirmMpPayment(
|
||||
db,
|
||||
{ id: payment.id, ownerId: payment.group.createdById },
|
||||
{ getToken, search },
|
||||
);
|
||||
// No usable token is not a payment problem: the row stays PENDING and
|
||||
// the account notice tells the professor what to do.
|
||||
if (outcome === 'no_token') totals.skipped += 1;
|
||||
if (outcome === 'paid') totals.paid += 1;
|
||||
} catch (error) {
|
||||
if (error instanceof MpApiError) {
|
||||
totals.failed += 1;
|
||||
} else {
|
||||
if (!(error instanceof MpApiError)) {
|
||||
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
||||
totals.failed += 1;
|
||||
}
|
||||
totals.failed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||
|
||||
export type ConfirmMpPaymentDeps = {
|
||||
getToken?: typeof getMpAccessToken;
|
||||
search?: typeof searchMpPaymentByExternalReference;
|
||||
};
|
||||
|
||||
/** `no_token`: the owner has no usable Mercado Pago link (not linked, or needs re-auth). */
|
||||
export type ConfirmMpPaymentOutcome = 'paid' | 'unpaid' | 'no_token';
|
||||
|
||||
/**
|
||||
* Asks the owner's Mercado Pago account whether this payment was approved and,
|
||||
* if so, marks it PAID. The only rule for a Checkout Pro payment, shared by the
|
||||
* polling job and the notification: whatever triggered it is never trusted, the
|
||||
* owner's account is. Throws `MpApiError` when Mercado Pago cannot answer.
|
||||
*/
|
||||
export async function confirmMpPayment(
|
||||
db: Pick<PrismaClient, 'payment'>,
|
||||
payment: { id: string; ownerId: string },
|
||||
deps: ConfirmMpPaymentDeps = {},
|
||||
): Promise<ConfirmMpPaymentOutcome> {
|
||||
const token = await (deps.getToken ?? getMpAccessToken)(payment.ownerId);
|
||||
if (!token.ok) return 'no_token';
|
||||
|
||||
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, payment.id);
|
||||
if (found?.status !== 'approved' || found.externalReference !== payment.id) return 'unpaid';
|
||||
|
||||
await db.payment.update({
|
||||
where: { id: payment.id },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
mpPaymentId: found.id,
|
||||
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
||||
},
|
||||
});
|
||||
return 'paid';
|
||||
}
|
||||
|
||||
/** Where Mercado Pago notifies a payment of this link (public: see `isPublicApiRequest`). */
|
||||
export function paymentNotificationUrl(apiOrigin: string, paymentId: string): string {
|
||||
// `source_news=webhooks`: only the webhook format, not the legacy IPN copy.
|
||||
return `${apiOrigin}/api/v1/payments/webhooks/mp/${encodeURIComponent(paymentId)}?source_news=webhooks`;
|
||||
}
|
||||
@@ -1 +1,7 @@
|
||||
export {
|
||||
type ConfirmMpPaymentDeps,
|
||||
type ConfirmMpPaymentOutcome,
|
||||
confirmMpPayment,
|
||||
paymentNotificationUrl,
|
||||
} from './confirm-mp-payment';
|
||||
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';
|
||||
|
||||
@@ -3,6 +3,7 @@ import getAllRoute from './features/get-all/route';
|
||||
import renewRoute from './features/renew/route';
|
||||
import reportedRoute from './features/reported/route';
|
||||
import transferDetailsRoute from './features/transfer-details/route';
|
||||
import webhookRoute from './features/webhook/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
@@ -10,5 +11,6 @@ routes.route('/', getAllRoute);
|
||||
routes.route('/', reportedRoute);
|
||||
routes.route('/', transferDetailsRoute);
|
||||
routes.route('/', renewRoute);
|
||||
routes.route('/', webhookRoute);
|
||||
|
||||
export default routes;
|
||||
Reference in New Issue
Block a user