development #14

Merged
jselesan merged 102 commits from development into main 2026-11-07 13:21:43 +00:00
645 changed files with 56897 additions and 1199 deletions
Showing only changes of commit 9617447e05 - Show all commits

View File

@@ -54,11 +54,11 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`. 9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`.
10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos. 10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos.
11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`. 11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`.
- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual vía `/preapproval`), no lo que pagan los alumnos. Ojo con esto: - **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual), no lo que pagan los alumnos. Ojo con esto:
1. Usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_<CC>` / `MP_PLATFORM_WEBHOOK_SECRET_<CC>`, `getPlatformCredentials`), nunca `getMpAccessToken`. Un país sin credenciales da `503 billing_not_available`. 1. Proveedor intercambiable detrás del puerto `BillingProvider` (`providers/billing-provider.ts`, mismo patrón que WhatsApp): Mercado Pago (`/preapproval`) en **AR** y Stripe (Checkout en modo suscripción, `fetch` plano sin SDK) en el resto; el mapa es `BILLING_PROVIDER_BY_COUNTRY` (shared). Los use-cases, `SyncSubscription` y el job **nunca** importan un adaptador: piden `getBillingProvider(id)` (inyectable como `providers` en `deps`). El país elige proveedor solo para suscripciones **nuevas**: sync/cancel/webhook usan siempre `row.provider`. MP usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_<CC>`, nunca `getMpAccessToken`); Stripe, una sola cuenta (`STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET`) que cobra en la moneda local (CLP es zero-decimal). Sin credenciales: `503 billing_not_available`. Con Stripe la suscripción no existe hasta completar el checkout: la fila guarda `checkoutRef` (la session) y la sync completa `externalId`.
2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard. 2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard.
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`). 3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
4. El webhook `POST /billing/webhooks/mp/:country` es público (`isPublicApiRequest`), verifica `x-signature` y vuelve a pedirle todo a MP; el polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback. 4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`. 5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. 6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp.
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.

View File

@@ -32,12 +32,17 @@ MP_REDIRECT_URI=""
# Generar con: openssl rand -base64 32 # Generar con: openssl rand -base64 32
TOKEN_ENCRYPTION_KEY="" TOKEN_ENCRYPTION_KEY=""
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md). # Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra # Suscripciones de Mercado Pago; el resto de los países, con Stripe.
# entre países). No son las del OAuth del profesor. Un país sin las dos queda # Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY. # son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
MP_PLATFORM_ACCESS_TOKEN_AR="" MP_PLATFORM_ACCESS_TOKEN_AR=""
MP_PLATFORM_WEBHOOK_SECRET_AR="" MP_PLATFORM_WEBHOOK_SECRET_AR=""
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
STRIPE_SECRET_KEY=""
STRIPE_WEBHOOK_SECRET=""
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro. # on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
BILLING_ENFORCEMENT="off" BILLING_ENFORCEMENT="off"
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. # Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.

View File

@@ -0,0 +1,26 @@
-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest).
-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids.
-- CreateEnum
CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE');
-- billing_subscriptions: provider + provider-neutral ids
ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO';
ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT;
ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id";
ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key";
CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref");
-- billing_charges: provider-neutral id and normalized status
ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id";
ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key";
UPDATE "billing_charges"
SET "status" = CASE
WHEN "status" = 'approved' THEN 'approved'
WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected'
ELSE 'pending'
END;
-- billing_webhook_events: dedupe per sending account (`mp:<CC>` or `stripe`)
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";

View File

@@ -1,7 +1,12 @@
// Gruperly's own billing: the professor pays a monthly Pro subscription through // Gruperly's own billing: the professor pays a monthly Pro subscription,
// Mercado Pago Subscriptions (preapproval), collected by Gruperly's account in // collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe
// the professor's country. Not to be confused with `Payment`, which is what // (every other country), see `modules/billing/providers/`. Not to be confused
// students pay the professor. // with `Payment`, which is what students pay the professor.
enum BillingProviderId {
MERCADO_PAGO
STRIPE
}
enum SubscriptionStatus { enum SubscriptionStatus {
PENDING PENDING
@@ -17,8 +22,14 @@ model BillingSubscription {
currency String currency String
amount Decimal @db.Decimal(12, 2) amount Decimal @db.Decimal(12, 2)
payerEmail String @map("payer_email") payerEmail String @map("payer_email")
// Null between creating the row and Mercado Pago answering. // Who collects it. Sync and cancel always follow this, never the current country.
mpPreapprovalId String? @unique(map: "billing_subscriptions_mpPreapprovalId_key") @map("mp_preapproval_id") provider BillingProviderId @default(MERCADO_PAGO)
// The provider's subscription id (MP preapproval, Stripe subscription). Null
// until the provider creates it: right after MP answers, or once the
// professor completes Stripe Checkout.
externalId String? @unique(map: "billing_subscriptions_externalId_key") @map("external_id")
// Stripe Checkout Session of the current attempt; null for Mercado Pago.
checkoutRef String? @unique(map: "billing_subscriptions_checkoutRef_key") @map("checkout_ref")
status SubscriptionStatus @default(PENDING) status SubscriptionStatus @default(PENDING)
// When the current attempt started: re-subscribing reuses the row. // When the current attempt started: re-subscribing reuses the row.
requestedAt DateTime @default(now()) @map("requested_at") requestedAt DateTime @default(now()) @map("requested_at")
@@ -39,14 +50,14 @@ model BillingSubscription {
@@map("billing_subscriptions") @@map("billing_subscriptions")
} }
// One Mercado Pago "authorized payment" (a monthly invoice) of a subscription. // One monthly invoice of a subscription (MP authorized payment, Stripe invoice).
model BillingCharge { model BillingCharge {
id String @id @default(cuid()) id String @id @default(cuid())
subscriptionId String @map("subscription_id") subscriptionId String @map("subscription_id")
mpAuthorizedPaymentId String @unique(map: "billing_charges_mpAuthorizedPaymentId_key") @map("mp_authorized_payment_id") externalId String @unique(map: "billing_charges_externalId_key") @map("external_id")
amount Decimal @db.Decimal(12, 2) amount Decimal @db.Decimal(12, 2)
currency String currency String
// Mercado Pago's own status of the charge (e.g. approved, rejected). // Normalized across providers: approved, pending or rejected.
status String status String
paidAt DateTime? @map("paid_at") paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
@@ -58,13 +69,14 @@ model BillingCharge {
@@map("billing_charges") @@map("billing_charges")
} }
// Deduplication of Mercado Pago webhook deliveries, per country account. // Deduplication of billing webhook deliveries, per sending account: `mp:<CC>`
// (one Mercado Pago account per country) or `stripe`.
model BillingWebhookEvent { model BillingWebhookEvent {
country String @map("country_code") source String @map("source")
dedupeKey String @map("dedupe_key") dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at") receivedAt DateTime @default(now()) @map("received_at")
@@id([country, dedupeKey], map: "billing_webhook_events_pkey") @@id([source, dedupeKey], map: "billing_webhook_events_pkey")
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx") @@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events") @@map("billing_webhook_events")
} }

View File

@@ -259,7 +259,7 @@ export function planReadOnlyProblem(): ProblemDetails {
}); });
} }
/** Gruperly has no Mercado Pago account configured for the professor's country. */ /** The billing provider of the professor's country is not configured. */
export function billingNotAvailableProblem(): ProblemDetails { export function billingNotAvailableProblem(): ProblemDetails {
return { return {
type: `${PROBLEM_DOMAIN}/problems/billing-not-available`, type: `${PROBLEM_DOMAIN}/problems/billing-not-available`,
@@ -270,17 +270,25 @@ export function billingNotAvailableProblem(): ProblemDetails {
}; };
} }
/** Mercado Pago refused the subscription request, or could not be reached. */ /** The billing provider (Mercado Pago or Stripe) refused the request, or could not be reached. */
export function billingProviderErrorProblem(): ProblemDetails { export function billingProviderErrorProblem(): ProblemDetails {
return { return {
type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`, type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`,
title: 'Bad Gateway', title: 'Bad Gateway',
status: 502, status: 502,
detail: 'No pudimos comunicarnos con Mercado Pago. Intentá de nuevo en unos minutos.', detail: 'No pudimos comunicarnos con el procesador de pagos. Intentá de nuevo en unos minutos.',
code: 'billing_provider_error', code: 'billing_provider_error',
}; };
} }
/** Mercado Pago makes the payer log in with this exact email, so it cannot be left out. */
export function payerEmailRequiredProblem(): ProblemDetails {
return validationProblem({
detail: 'Ingresá el email de tu cuenta de Mercado Pago.',
errors: { payerEmail: ['Ingresá el email de tu cuenta de Mercado Pago.'] },
});
}
export function subscriptionAlreadyActiveProblem(): ProblemDetails { export function subscriptionAlreadyActiveProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Ya tenés una suscripción a Pro activa.', detail: 'Ya tenés una suscripción a Pro activa.',

View File

@@ -47,6 +47,10 @@ export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) { if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
return true; return true;
} }
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;
}
return ( return (
normalizedPath === '/api/v1/health' normalizedPath === '/api/v1/health'

View File

@@ -45,6 +45,7 @@ export function toAccountListItem(
plan: accountPlan(account, context).plan, plan: accountPlan(account, context).plan,
subscription: subscription subscription: subscription
? { ? {
provider: subscription.provider,
status: subscription.status, status: subscription.status,
amount: Number(subscription.amount.toString()), amount: Number(subscription.amount.toString()),
currency: subscription.currency, currency: subscription.currency,

View File

@@ -1,19 +1,20 @@
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared'; import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { billingProviderErrorProblem, noActiveSubscriptionProblem } from '@/http/problem-builders'; import { noActiveSubscriptionProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { getPlatformCredentials, mpPreapprovalClient, type PreapprovalClient } from '../../lib'; import { subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type CancelSubscriptionDeps = { type CancelSubscriptionDeps = {
db?: Pick<PrismaClient, 'billingSubscription'>; db?: Pick<PrismaClient, 'billingSubscription'>;
client?: PreapprovalClient; providers?: BillingProviderResolver;
credentials?: typeof getPlatformCredentials;
}; };
/** /**
* Stops the monthly charge. `paidThrough` stays: the professor keeps Pro until * Stops the monthly charge with the provider that collects it. `paidThrough`
* the end of what they already paid (plus the grace period). * stays: the professor keeps Pro until the end of what they already paid
* (plus the grace period).
*/ */
export class CancelSubscription { export class CancelSubscription {
constructor(private readonly deps: CancelSubscriptionDeps = {}) {} constructor(private readonly deps: CancelSubscriptionDeps = {}) {}
@@ -22,22 +23,20 @@ export class CancelSubscription {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const subscription = await db.billingSubscription.findUnique({ where: { userId } }); const subscription = await db.billingSubscription.findUnique({ where: { userId } });
if (!subscription?.mpPreapprovalId || subscription.status === 'CANCELLED') { if (
!subscription
|| (!subscription.externalId && !subscription.checkoutRef)
|| subscription.status === 'CANCELLED'
) {
return err(noActiveSubscriptionProblem()); return err(noActiveSubscriptionProblem());
} }
const credentials = (this.deps.credentials ?? getPlatformCredentials)(
subscription.country as CountryCode,
);
if (!credentials.ok) return credentials;
try { try {
await (this.deps.client ?? mpPreapprovalClient).cancelPreapproval( await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel(
credentials.value.accessToken, subscriptionRefOf(subscription),
subscription.mpPreapprovalId,
); );
} catch { } catch (error) {
return err(billingProviderErrorProblem()); return err(toBillingProblem(error));
} }
await db.billingSubscription.update({ await db.billingSubscription.update({

View File

@@ -1,9 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { countryOf, getPlatformCredentials, PlanGuard, SyncSubscription } from '../../lib'; import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
/** A PENDING subscription is re-read from Mercado Pago at most this often. */ /** A PENDING subscription is re-read from Mercado Pago at most this often. */
const PENDING_SYNC_INTERVAL_MS = 30 * 1000; const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
@@ -12,7 +13,7 @@ type GetBillingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>; db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
guard?: PlanGuard; guard?: PlanGuard;
sync?: Pick<SyncSubscription, 'execute'>; sync?: Pick<SyncSubscription, 'execute'>;
credentials?: typeof getPlatformCredentials; providers?: BillingProviderResolver;
now?: () => Date; now?: () => Date;
}; };
@@ -29,11 +30,11 @@ export class GetBillingStatus {
let subscription = await db.billingSubscription.findUnique({ where: { userId } }); let subscription = await db.billingSubscription.findUnique({ where: { userId } });
// Coming back from Mercado Pago, the webhook may not have arrived yet (or // Coming back from the provider's checkout, the webhook may not have
// may never arrive in local dev): ask Mercado Pago directly, throttled. // arrived yet (or may never arrive in local dev): ask directly, throttled.
if ( if (
subscription?.status === 'PENDING' subscription?.status === 'PENDING'
&& subscription.mpPreapprovalId && (subscription.externalId || subscription.checkoutRef)
&& (!subscription.lastSyncedAt && (!subscription.lastSyncedAt
|| now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS) || now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS)
) { ) {
@@ -47,6 +48,11 @@ export class GetBillingStatus {
// A live subscription keeps the price it was created with; otherwise the // A live subscription keeps the price it was created with; otherwise the
// current price of the country is what subscribing would cost. // current price of the country is what subscribing would cost.
const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null; const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null;
// An authorized subscription stays with its provider; a new attempt (or
// retrying a PENDING one) goes to the country's current provider.
const provider = (this.deps.providers ?? getBillingProvider)(
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
);
return ok({ return ok({
plan: entitlements.plan, plan: entitlements.plan,
@@ -62,7 +68,8 @@ export class GetBillingStatus {
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country], priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
currency: live ? live.currency : COUNTRY_CURRENCY[country], currency: live ? live.currency : COUNTRY_CURRENCY[country],
country, country,
availableInCountry: (this.deps.credentials ?? getPlatformCredentials)(country).ok, provider: provider.id,
availableInCountry: provider.isAvailable(country),
enforced: entitlements.enforced, enforced: entitlements.enforced,
usage: entitlements.usage, usage: entitlements.usage,
limits: entitlements.limits, limits: entitlements.limits,

View File

@@ -1,75 +1,75 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared'; import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { import {
billingProviderErrorProblem, billingNotAvailableProblem,
notFoundResourceProblem, notFoundResourceProblem,
payerEmailRequiredProblem,
subscriptionAlreadyActiveProblem, subscriptionAlreadyActiveProblem,
} from '@/http/problem-builders'; } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib'; import { getWebOrigin } from '@/modules/mp/lib';
import { import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
buildSubscriptionBackUrl, import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
countryOf,
getPlatformCredentials,
mpPreapprovalClient,
type PreapprovalClient,
} from '../../lib';
type SubscribeDeps = { type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>; db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
client?: PreapprovalClient; providers?: BillingProviderResolver;
credentials?: typeof getPlatformCredentials;
webOrigin?: string; webOrigin?: string;
now?: () => Date; now?: () => Date;
}; };
const SUBSCRIPTION_REASON = 'Gruperly Pro';
/** /**
* Starts a monthly Pro subscription in Gruperly's Mercado Pago account of the * Starts a monthly Pro subscription with the billing provider of the
* professor's country and returns where the browser goes to authorize it. * professor's country and returns where the browser goes to authorize it.
* *
* The row is written PENDING before calling Mercado Pago (it is the source of * The row is written PENDING before calling the provider (it is the source of
* truth, like `Payment` rows in the batch). A previous subscription that was * truth, like `Payment` rows in the batch). A previous subscription that was
* never authorized is cancelled first, so the professor can fix the payer * never authorized is voided first, with whichever provider it was created, so
* email by simply trying again. * the professor can fix the payer email (or switch country) by trying again.
*/ */
export class Subscribe { export class Subscribe {
constructor(private readonly deps: SubscribeDeps = {}) {} constructor(private readonly deps: SubscribeDeps = {}) {}
async execute(userId: string, input: SubscribeInput): Promise<Result<SubscribeResultDto, ProblemDetails>> { async execute(userId: string, input: SubscribeInput): Promise<Result<SubscribeResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const client = this.deps.client ?? mpPreapprovalClient; const providers = this.deps.providers ?? getBillingProvider;
const now = this.deps.now?.() ?? new Date(); const now = this.deps.now?.() ?? new Date();
const user = await db.user.findUnique({ where: { id: userId } }); const user = await db.user.findUnique({ where: { id: userId } });
if (!user) return err(notFoundResourceProblem('User', userId)); if (!user) return err(notFoundResourceProblem('User', userId));
const country = countryOf(user); const country = countryOf(user);
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); const provider = providers(billingProviderForCountry(country));
if (!credentials.ok) return credentials; if (!provider.isAvailable(country)) return err(billingNotAvailableProblem());
const token = credentials.value.accessToken; if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem());
const existing = await db.billingSubscription.findUnique({ where: { userId } }); const existing = await db.billingSubscription.findUnique({ where: { userId } });
if (existing?.status === 'AUTHORIZED') { if (existing?.status === 'AUTHORIZED') {
return err(subscriptionAlreadyActiveProblem()); return err(subscriptionAlreadyActiveProblem());
} }
if (existing?.mpPreapprovalId && existing.status !== 'CANCELLED') { if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') {
try { try {
await client.cancelPreapproval(token, existing.mpPreapprovalId); await providers(existing.provider).cancel(subscriptionRefOf(existing));
} catch { } catch {
// A stale PENDING preapproval that cannot be cancelled is harmless: it // A stale attempt that cannot be voided is harmless: it was never
// was never authorized, and its notifications no longer match our row. // authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not cancel the previous Mercado Pago preapproval'); logger.warn({ userId }, 'Could not void the previous Pro subscription attempt');
} }
} }
const amount = PRO_PRICE_BY_COUNTRY[country]; const amount = PRO_PRICE_BY_COUNTRY[country];
const currency = COUNTRY_CURRENCY[country]; const currency = COUNTRY_CURRENCY[country];
const fields = { country, currency, amount, payerEmail: input.payerEmail }; const fields = {
country,
currency,
amount,
provider: provider.id,
// Stripe asks for the email in its checkout; the sync stores the real one.
payerEmail: input.payerEmail ?? user.email,
};
const row = await db.billingSubscription.upsert({ const row = await db.billingSubscription.upsert({
where: { userId }, where: { userId },
@@ -78,7 +78,8 @@ export class Subscribe {
...fields, ...fields,
status: 'PENDING', status: 'PENDING',
requestedAt: now, requestedAt: now,
mpPreapprovalId: null, externalId: null,
checkoutRef: null,
authorizedAt: null, authorizedAt: null,
nextPaymentDate: null, nextPaymentDate: null,
}, },
@@ -88,31 +89,27 @@ export class Subscribe {
// so nobody pays twice for the same month. // so nobody pays twice for the same month.
const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined; const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined;
let preapproval: Awaited<ReturnType<PreapprovalClient['createPreapproval']>>; let started: Awaited<ReturnType<typeof provider.start>>;
try { try {
preapproval = await client.createPreapproval(token, { started = await provider.start({
reason: SUBSCRIPTION_REASON, userId,
externalReference: userId, country,
payerEmail: input.payerEmail,
amount, amount,
currencyId: currency, currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo), backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
startDate, startDate,
}); });
} catch { } catch (error) {
return err(billingProviderErrorProblem()); logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription');
} return err(toBillingProblem(error));
if (!preapproval.initPoint) {
logger.error({ userId }, 'Mercado Pago preapproval came back without init_point');
return err(billingProviderErrorProblem());
} }
await db.billingSubscription.update({ await db.billingSubscription.update({
where: { id: row.id }, where: { id: row.id },
data: { mpPreapprovalId: preapproval.id, lastSyncedAt: now }, data: { externalId: started.externalId, checkoutRef: started.checkoutRef, lastSyncedAt: now },
}); });
return ok({ checkoutUrl: preapproval.initPoint }); return ok({ checkoutUrl: started.checkoutUrl });
} }
} }

View File

@@ -1,36 +1,41 @@
import type { BillingProviderId } from '@gruperly/shared';
import type { Context } from 'hono';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { HandleBillingWebhook } from './use-case'; import { type BillingWebhookFailure, HandleBillingWebhook } from './use-case';
/** /**
* Public endpoint (see `isPublicApiRequest`): Mercado Pago calls it, not the * Public endpoints (see `isPublicApiRequest`): the providers call them, not the
* browser, so there is no session. One URL per country, because each country * browser, so there is no session; each adapter checks its own signature.
* is a different Gruperly account with its own webhook secret. * Mercado Pago has one URL per country, because each country is a different
* Gruperly account with its own secret; Stripe is a single account.
*/ */
const route = new Hono(); const route = new Hono();
route.post('/webhooks/mp/:country', async (c) => { const FAILURE_STATUS: Record<BillingWebhookFailure, 401 | 404 | 500 | 503> = {
const result = await new HandleBillingWebhook().execute({ invalid_signature: 401,
country: c.req.param('country'), unknown_country: 404,
not_configured: 503,
sync_failed: 500,
};
async function handle(c: Context, providerId: BillingProviderId, routeParam: string | null) {
const result = await new HandleBillingWebhook().execute(providerId, {
routeParam,
rawBody: await c.req.text(), rawBody: await c.req.text(),
headers: c.req.raw.headers, headers: c.req.raw.headers,
query: new URL(c.req.url).searchParams, query: new URL(c.req.url).searchParams,
}); });
if (!result.ok) { if (!result.ok) {
logger.warn({ reason: result.error }, 'Mercado Pago billing webhook rejected'); logger.warn({ provider: providerId, reason: result.error }, 'Billing webhook rejected');
const status = return c.body(null, FAILURE_STATUS[result.error]);
result.error === 'invalid_signature'
? 401
: result.error === 'unknown_country'
? 404
: result.error === 'not_configured'
? 503
: 500;
return c.body(null, status);
} }
return c.json({ received: true, duplicate: result.value.duplicate }); return c.json({ received: true, duplicate: result.value.duplicate });
}); }
route.post('/webhooks/mp/:country', (c) => handle(c, 'MERCADO_PAGO', c.req.param('country')));
route.post('/webhooks/stripe', (c) => handle(c, 'STRIPE', null));
export default route; export default route;

View File

@@ -1,78 +1,50 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared'; import type { BillingProviderId, Result } from '@gruperly/shared';
import { countryCodeSchema, err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { SyncSubscription } from '../../lib';
import { import {
getPlatformCredentials, type BillingProviderResolver,
mpPreapprovalClient, type BillingWebhookFailure,
type PreapprovalClient, type BillingWebhookRequest,
SyncSubscription, getBillingProvider,
verifyMpSignature, } from '../../providers';
} from '../../lib';
export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers';
type HandleBillingWebhookDeps = { type HandleBillingWebhookDeps = {
db?: Pick<PrismaClient, 'billingWebhookEvent'>; db?: Pick<PrismaClient, 'billingWebhookEvent'>;
client?: PreapprovalClient; providers?: BillingProviderResolver;
credentials?: typeof getPlatformCredentials; sync?: Pick<SyncSubscription, 'byExternalId'>;
sync?: Pick<SyncSubscription, 'byPreapprovalId'>;
}; };
export type BillingWebhookFailure =
| 'unknown_country'
| 'not_configured'
| 'invalid_signature'
| 'sync_failed';
/** Prisma's unique-constraint violation: this delivery was already processed. */ /** Prisma's unique-constraint violation: this delivery was already processed. */
const UNIQUE_VIOLATION = 'P2002'; const UNIQUE_VIOLATION = 'P2002';
export type BillingWebhookRequest = {
country: string;
rawBody: string;
headers: Headers;
query: URLSearchParams;
};
/** /**
* Applies one Mercado Pago notification about a Pro subscription. * Applies one provider notification about a Pro subscription.
* *
* The notification is only a hint: after checking its signature, the resource * The provider adapter checks the signature and says which subscription the
* is fetched again from Mercado Pago and synced (`SyncSubscription`). The body * notification is about; the subscription is then fetched again from the
* is never trusted for a status. If syncing fails the dedupe key is removed, so * provider and synced (`SyncSubscription`). The body is never trusted for a
* Mercado Pago's retry gets another chance (same rule as the WhatsApp webhook). * status. If syncing fails the dedupe key is removed, so the provider's retry
* gets another chance (same rule as the WhatsApp webhook).
*/ */
export class HandleBillingWebhook { export class HandleBillingWebhook {
constructor(private readonly deps: HandleBillingWebhookDeps = {}) {} constructor(private readonly deps: HandleBillingWebhookDeps = {}) {}
async execute( async execute(
providerId: BillingProviderId,
request: BillingWebhookRequest, request: BillingWebhookRequest,
): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> { ): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
const parsedCountry = countryCodeSchema.safeParse(request.country.toUpperCase()); const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request);
if (!parsedCountry.success) return err('unknown_country'); if (!parsed.ok) return parsed;
const country: CountryCode = parsedCountry.data; const hint = parsed.value;
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); if (!hint.externalId) return ok({ duplicate: false, applied: false });
if (!credentials.ok) return err('not_configured');
const body = parseBody(request.rawBody);
const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId;
const type = request.query.get('type') ?? request.query.get('topic') ?? body.type;
const requestId = request.headers.get('x-request-id');
const valid = verifyMpSignature({
signature: request.headers.get('x-signature'),
requestId,
dataId,
secret: credentials.value.webhookSecret,
});
if (!valid) return err('invalid_signature');
if (!dataId || !isSubscriptionTopic(type)) {
return ok({ duplicate: false, applied: false });
}
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const dedupe = requestId ? { country, dedupeKey: requestId } : null; const dedupe = hint.dedupeKey ? { source: hint.source, dedupeKey: hint.dedupeKey } : null;
if (dedupe) { if (dedupe) {
try { try {
await db.billingWebhookEvent.create({ data: dedupe }); await db.billingWebhookEvent.create({ data: dedupe });
@@ -87,23 +59,15 @@ export class HandleBillingWebhook {
const unburn = async () => { const unburn = async () => {
if (!dedupe) return; if (!dedupe) return;
await db.billingWebhookEvent await db.billingWebhookEvent
.delete({ where: { country_dedupeKey: dedupe } }) .delete({ where: { source_dedupeKey: dedupe } })
.catch(() => undefined); .catch(() => undefined);
}; };
try { try {
let preapprovalId = dataId; const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId(
if (type === 'subscription_authorized_payment') { providerId,
const invoice = await (this.deps.client ?? mpPreapprovalClient).getAuthorizedPayment( hint.externalId,
credentials.value.accessToken, hint.country,
dataId,
);
preapprovalId = invoice.preapprovalId;
}
const synced = await (this.deps.sync ?? new SyncSubscription()).byPreapprovalId(
country,
preapprovalId,
); );
if (!synced.ok) { if (!synced.ok) {
await unburn(); await unburn();
@@ -116,21 +80,3 @@ export class HandleBillingWebhook {
} }
} }
} }
function isSubscriptionTopic(
type: string | null,
): type is 'subscription_preapproval' | 'subscription_authorized_payment' {
return type === 'subscription_preapproval' || type === 'subscription_authorized_payment';
}
function parseBody(rawBody: string): { dataId: string | null; type: string | null } {
try {
const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null;
return {
dataId: payload?.data?.id == null ? null : String(payload.data.id),
type: typeof payload?.type === 'string' ? payload.type : null,
};
} catch {
return { dataId: null, type: null };
}
}

View File

@@ -41,7 +41,9 @@ export class ReconcileSubscriptions {
const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS); const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS);
const rows = await db.billingSubscription.findMany({ const rows = await db.billingSubscription.findMany({
where: { where: {
mpPreapprovalId: { not: null }, AND: [
{ OR: [{ externalId: { not: null } }, { checkoutRef: { not: null } }] },
{
OR: [ OR: [
{ status: 'PENDING' }, { status: 'PENDING' },
{ {
@@ -50,6 +52,8 @@ export class ReconcileSubscriptions {
}, },
], ],
}, },
],
},
select: { id: true }, select: { id: true },
orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } }, orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } },
take: BATCH_SIZE, take: BATCH_SIZE,

View File

@@ -1,36 +1,5 @@
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { billingNotAvailableProblem } from '@/http/problem-builders';
export type PlatformCredentials = {
/** Access token of Gruperly's own Mercado Pago account in that country. */
accessToken: string;
/** Secret of the webhook configured in that account's panel. */
webhookSecret: string;
};
const DEFAULT_GRACE_DAYS = 7; const DEFAULT_GRACE_DAYS = 7;
/**
* Gruperly's Mercado Pago credentials for one country. Mercado Pago does not
* charge across countries, so each country has its own account; a country
* without both variables cannot subscribe to Pro (503, not a deployment crash:
* rolling out country by country is expected).
*
* These are platform credentials, never the professor's OAuth token.
*/
export function getPlatformCredentials(
country: CountryCode,
env: Record<string, string | undefined> = process.env,
): Result<PlatformCredentials, ProblemDetails> {
const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim();
const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim();
if (!accessToken || !webhookSecret) {
return err(billingNotAvailableProblem());
}
return ok({ accessToken, webhookSecret });
}
/** /**
* Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset * Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset
* included) treats everyone as Pro, so the module can ship before the existing * included) treats everyone as Pro, so the module can ship before the existing

View File

@@ -19,7 +19,7 @@ export function countryOf(user: { country: string | null } | null): CountryCode
return parsed.success ? parsed.data : DEFAULT_COUNTRY; return parsed.success ? parsed.data : DEFAULT_COUNTRY;
} }
/** Where Mercado Pago sends the professor after authorizing (or abandoning). */ /** Where the billing provider sends the professor after authorizing (or abandoning). */
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string { export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`; return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
} }

View File

@@ -1,4 +1,4 @@
export { getGraceDays, getPlatformCredentials, isBillingEnforced, type PlatformCredentials } from './config'; export { getGraceDays, isBillingEnforced } from './config';
export { export {
type Entitlements, type Entitlements,
exceedsLimits, exceedsLimits,
@@ -10,11 +10,4 @@ export {
type SubscriptionSnapshot, type SubscriptionSnapshot,
} from './entitlements'; } from './entitlements';
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers'; export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
export { export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';
type MpAuthorizedPayment,
type MpPreapproval,
mpPreapprovalClient,
type PreapprovalClient,
} from './mp-preapproval';
export { coveredUntil, SyncSubscription, type SyncSubscriptionDeps } from './sync';
export { verifyMpSignature } from './webhook-signature';

View File

@@ -1,43 +1,40 @@
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; import type { BillingSubscription, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared'; import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { billingProviderErrorProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { getPlatformCredentials } from './config'; import {
import { type MpPreapproval, mpPreapprovalClient, type PreapprovalClient } from './mp-preapproval'; type BillingProviderResolver,
getBillingProvider,
const MP_STATUS: Record<string, SubscriptionStatus> = { type ProviderCharge,
pending: 'PENDING', type ProviderSubscription,
authorized: 'AUTHORIZED', type SubscriptionRef,
paused: 'PAUSED', toBillingProblem,
cancelled: 'CANCELLED', } from '../providers';
};
/** One approved monthly charge covers one month from the day it was debited. */
export function coveredUntil(paidAt: Date): Date {
const until = new Date(paidAt);
until.setUTCMonth(until.getUTCMonth() + 1);
return until;
}
export type SyncSubscriptionDeps = { export type SyncSubscriptionDeps = {
db?: Pick<PrismaClient, 'billingSubscription' | 'billingCharge'>; db?: Pick<PrismaClient, 'billingSubscription' | 'billingCharge'>;
client?: PreapprovalClient; providers?: BillingProviderResolver;
credentials?: typeof getPlatformCredentials;
now?: () => Date; now?: () => Date;
}; };
export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null }; export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null };
export function subscriptionRefOf(
row: Pick<BillingSubscription, 'country' | 'externalId' | 'checkoutRef'>,
): SubscriptionRef {
return { country: row.country as CountryCode, externalId: row.externalId, checkoutRef: row.checkoutRef };
}
/** /**
* Brings one subscription row in line with Mercado Pago. Shared by the webhook, * Brings one subscription row in line with its provider. Shared by the
* the reconciliation job and the status endpoint (on read, while PENDING). * webhooks, the reconciliation job and the status endpoint (on read, while
* PENDING). It talks to `row.provider`, never to the country's current one.
* *
* Never trusts what a notification says: it asks Mercado Pago for the * Never trusts what a notification says: it asks the provider for the
* preapproval and its invoices, checks that the preapproval is ours * subscription and its invoices, checks that the subscription is ours (it
* (`external_reference` is the user id) and only then writes. Re-running it is * carries our user id) and only then writes. Re-running it is harmless; every
* harmless; every write is an upsert or a monotonic `paidThrough`. * write is an upsert or a monotonic `paidThrough`.
*/ */
export class SyncSubscription { export class SyncSubscription {
constructor(private readonly deps: SyncSubscriptionDeps = {}) {} constructor(private readonly deps: SyncSubscriptionDeps = {}) {}
@@ -45,69 +42,74 @@ export class SyncSubscription {
async execute(subscriptionId: string): Promise<Result<SyncOutcome, ProblemDetails>> { async execute(subscriptionId: string): Promise<Result<SyncOutcome, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } }); const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } });
if (!subscription?.mpPreapprovalId) { if (!subscription || (!subscription.externalId && !subscription.checkoutRef)) {
return ok({ synced: false, status: subscription?.status ?? null }); return ok({ synced: false, status: subscription?.status ?? null });
} }
const credentials = (this.deps.credentials ?? getPlatformCredentials)( const provider = (this.deps.providers ?? getBillingProvider)(subscription.provider);
subscription.country as CountryCode, const ref = subscriptionRefOf(subscription);
);
if (!credentials.ok) return credentials;
const client = this.deps.client ?? mpPreapprovalClient; let remote: ProviderSubscription | null;
const token = credentials.value.accessToken;
let preapproval: MpPreapproval;
let invoices: Awaited<ReturnType<PreapprovalClient['searchAuthorizedPayments']>>;
try { try {
preapproval = await client.getPreapproval(token, subscription.mpPreapprovalId); remote = await provider.fetch(ref);
invoices = await client.searchAuthorizedPayments(token, subscription.mpPreapprovalId); } catch (error) {
} catch { return err(toBillingProblem(error));
return err(billingProviderErrorProblem()); }
// Stripe: the checkout was not completed yet, there is nothing to sync.
if (!remote) return ok({ synced: false, status: subscription.status });
if (remote.ownerUserId !== subscription.userId) {
logger.warn({ subscriptionId }, 'Provider subscription does not belong to this subscription');
return ok({ synced: false, status: subscription.status });
} }
if (preapproval.externalReference !== subscription.userId) { // The status is what grants Pro (an authorized subscription is Pro during
logger.warn({ subscriptionId }, 'Mercado Pago preapproval does not belong to this subscription'); // the grace days), so failing to list the charges must not leave it
return ok({ synced: false, status: subscription.status }); // PENDING: write the status and leave `lastSyncedAt` alone, so the charges
// are retried on the next sync.
let charges: ProviderCharge[] = [];
let chargesSynced = true;
try {
charges = await provider.listCharges({ ...ref, externalId: remote.externalId });
} catch (error) {
chargesSynced = false;
logger.warn({ subscriptionId, err: error }, 'Could not list the subscription charges; syncing the status only');
} }
const now = this.deps.now?.() ?? new Date(); const now = this.deps.now?.() ?? new Date();
let paidThrough = subscription.paidThrough; let paidThrough = subscription.paidThrough;
for (const invoice of invoices) { for (const charge of charges) {
if (invoice.preapprovalId !== subscription.mpPreapprovalId) continue;
const approved = invoice.paymentStatus === 'approved';
const debitedAt = invoice.debitDate ?? invoice.createdAt;
const paidAt = approved && debitedAt ? new Date(debitedAt) : null;
await db.billingCharge.upsert({ await db.billingCharge.upsert({
where: { mpAuthorizedPaymentId: invoice.id }, where: { externalId: charge.externalId },
create: { create: {
subscriptionId: subscription.id, subscriptionId: subscription.id,
mpAuthorizedPaymentId: invoice.id, externalId: charge.externalId,
amount: invoice.amount, amount: charge.amount,
currency: invoice.currencyId || subscription.currency, currency: charge.currency || subscription.currency,
status: invoice.paymentStatus ?? invoice.status, status: charge.status,
paidAt, paidAt: charge.paidAt,
}, },
update: { status: invoice.paymentStatus ?? invoice.status, paidAt }, update: { status: charge.status, paidAt: charge.paidAt },
}); });
if (paidAt) { if (charge.coveredUntil && (!paidThrough || charge.coveredUntil > paidThrough)) {
const until = coveredUntil(paidAt); paidThrough = charge.coveredUntil;
if (!paidThrough || until > paidThrough) paidThrough = until;
} }
} }
const status = MP_STATUS[preapproval.status] ?? subscription.status; const status = remote.status ?? subscription.status;
await db.billingSubscription.update({ await db.billingSubscription.update({
where: { id: subscription.id }, where: { id: subscription.id },
data: { data: {
// Stripe only creates the subscription when the checkout completes.
externalId: subscription.externalId ? undefined : remote.externalId,
status, status,
authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined, authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined,
nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null, nextPaymentDate: remote.nextPaymentDate,
paidThrough, paidThrough,
lastSyncedAt: now, payerEmail: remote.payerEmail ?? undefined,
lastSyncedAt: chargesSynced ? now : undefined,
}, },
}); });
@@ -115,43 +117,48 @@ export class SyncSubscription {
} }
/** /**
* Same as `execute`, starting from a Mercado Pago preapproval id (webhooks). * Same as `execute`, starting from the provider's subscription id (webhooks).
* A notification can beat our own write of `mpPreapprovalId` (the professor * A notification can beat our own write of `externalId` (Mercado Pago: the
* authorizes faster than our request returns), so an unknown id falls back to * professor authorizes faster than our request returns; Stripe: the checkout
* the `external_reference` once Mercado Pago confirms it. * completes before anyone reads the session), so an unknown id falls back to
* the user id the provider holds, once the provider confirms it.
*/ */
async byPreapprovalId( async byExternalId(
country: CountryCode, providerId: BillingProviderId,
preapprovalId: string, externalId: string,
country: CountryCode | null,
): Promise<Result<SyncOutcome, ProblemDetails>> { ): Promise<Result<SyncOutcome, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const known = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } }); const known = await db.billingSubscription.findUnique({ where: { externalId } });
if (known) return this.execute(known.id); if (known) return this.execute(known.id);
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country); let remote: ProviderSubscription | null;
if (!credentials.ok) return credentials;
let preapproval: MpPreapproval;
try { try {
preapproval = await (this.deps.client ?? mpPreapprovalClient).getPreapproval( remote = await (this.deps.providers ?? getBillingProvider)(providerId).fetch({
credentials.value.accessToken, country,
preapprovalId, externalId,
); checkoutRef: null,
} catch { });
return err(billingProviderErrorProblem()); } catch (error) {
return err(toBillingProblem(error));
} }
// A cancelled one is a previous attempt being replaced, never the new one. // A cancelled one is a previous attempt being replaced, never the new one.
if (!preapproval.externalReference || preapproval.status === 'cancelled') { if (!remote?.ownerUserId || remote.status === 'CANCELLED') {
return ok({ synced: false, status: null }); return ok({ synced: false, status: null });
} }
const claimed = await db.billingSubscription.updateMany({ const claimed = await db.billingSubscription.updateMany({
where: { userId: preapproval.externalReference, country, mpPreapprovalId: null }, where: {
data: { mpPreapprovalId: preapprovalId }, userId: remote.ownerUserId,
provider: providerId,
externalId: null,
...(country ? { country } : {}),
},
data: { externalId },
}); });
if (claimed.count === 0) return ok({ synced: false, status: null }); if (claimed.count === 0) return ok({ synced: false, status: null });
const row = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } }); const row = await db.billingSubscription.findUnique({ where: { externalId } });
return row ? this.execute(row.id) : ok({ synced: false, status: null }); return row ? this.execute(row.id) : ok({ synced: false, status: null });
} }
} }

View File

@@ -0,0 +1,124 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared';
import { billingNotAvailableProblem, billingProviderErrorProblem } from '@/http/problem-builders';
/**
* The port every Pro billing provider implements. The domain (subscribing,
* cancelling, syncing, the webhook and the reconciliation job) only talks to
* this interface; everything that knows about Mercado Pago or Stripe lives in
* `providers/<name>/`. Same idea as WhatsApp's `MessagingProvider`.
*
* Calls that reach the provider throw on failure: `BillingProviderNotConfigured`
* when Gruperly has no credentials for it, anything else when the provider
* refused or could not be reached. `toBillingProblem` turns either into the
* Problem Details the use-cases answer with.
*/
export type { BillingProviderId };
/** What identifies one subscription at its provider. */
export type SubscriptionRef = {
/** Mercado Pago picks Gruperly's account by country; Stripe ignores it. */
country: CountryCode | null;
/** The provider's subscription id, once it exists. */
externalId: string | null;
/** A checkout started but not completed yet (Stripe Checkout Session). */
checkoutRef: string | null;
};
export type StartSubscriptionInput = {
/** Our user id: the only thing that ties the subscription back to a professor. */
userId: string;
country: CountryCode;
amount: number;
currency: string;
/** Mandatory when `requiresPayerEmail`; otherwise only a pre-fill. */
payerEmail: string | null;
/** Where the provider sends the professor back, completed or not. */
backUrl: string;
/** First charge date; omitted means right after the professor authorizes. */
startDate?: Date;
};
export type StartedSubscription = {
/** Where the browser goes to authorize the subscription. */
checkoutUrl: string;
externalId: string | null;
checkoutRef: string | null;
};
export type ProviderSubscription = {
externalId: string;
/** Our user id as the provider holds it; checked before trusting anything. */
ownerUserId: string | null;
/** `null` for a provider status we do not know: the row keeps its own. */
status: SubscriptionStatus | null;
nextPaymentDate: Date | null;
/** The email the professor actually paid with, when the provider asks for it. */
payerEmail: string | null;
};
export type ChargeStatus = 'approved' | 'pending' | 'rejected';
/** One monthly invoice of a subscription. */
export type ProviderCharge = {
externalId: string;
amount: number;
currency: string | null;
status: ChargeStatus;
paidAt: Date | null;
/** Last day this charge pays for; null unless approved. */
coveredUntil: Date | null;
};
export type BillingWebhookRequest = {
/** The `:country` of `/webhooks/mp/:country`; null for Stripe. */
routeParam: string | null;
rawBody: string;
headers: Headers;
query: URLSearchParams;
};
export type BillingWebhookFailure =
| 'unknown_country'
| 'not_configured'
| 'invalid_signature'
| 'sync_failed';
/** What a verified notification points at. The body is never trusted for a status. */
export type BillingWebhookHint = {
/** The sending account, for deduplication: `mp:<CC>` or `stripe`. */
source: string;
dedupeKey: string | null;
country: CountryCode | null;
/** The subscription to sync; null for events that do not concern one. */
externalId: string | null;
};
export interface BillingProvider {
readonly id: BillingProviderId;
/** Mercado Pago makes the payer log in with the email given up front. */
readonly requiresPayerEmail: boolean;
/** Gruperly has credentials to collect Pro in that country. */
isAvailable(country: CountryCode): boolean;
start(input: StartSubscriptionInput): Promise<StartedSubscription>;
/** `null` while the professor has not completed the checkout. */
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
/** Stops the monthly charge, or voids a checkout never completed. */
cancel(ref: SubscriptionRef): Promise<void>;
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
}
export class BillingProviderNotConfigured extends Error {
constructor(provider: BillingProviderId) {
super(`Billing provider ${provider} is not configured`);
this.name = 'BillingProviderNotConfigured';
}
}
export function toBillingProblem(error: unknown): ProblemDetails {
return error instanceof BillingProviderNotConfigured
? billingNotAvailableProblem()
: billingProviderErrorProblem();
}

View File

@@ -0,0 +1,32 @@
import type { BillingProviderId } from '@gruperly/shared';
import type { BillingProvider } from './billing-provider';
import { MercadoPagoBillingProvider } from './mercado-pago';
import { StripeBillingProvider } from './stripe';
export type * from './billing-provider';
export { BillingProviderNotConfigured, toBillingProblem } from './billing-provider';
export { MercadoPagoBillingProvider } from './mercado-pago';
export { StripeBillingProvider } from './stripe';
/** How the domain gets a provider; use-cases take one in `deps` for tests. */
export type BillingProviderResolver = (id: BillingProviderId) => BillingProvider;
/**
* The one place that maps a provider id to its adapter. Which provider a new
* subscription uses comes from `billingProviderForCountry` (shared); an
* existing row always keeps its own `provider`. Adding a provider means
* a new `providers/<name>/` implementing `BillingProvider`, a case here and an
* entry in `BILLING_PROVIDER_BY_COUNTRY` (shared).
*
* Construction never fails: missing credentials surface as `isAvailable` false
* or as `BillingProviderNotConfigured` (503) when a call needs them.
*/
export const getBillingProvider: BillingProviderResolver = (id) => {
switch (id) {
case 'MERCADO_PAGO':
return new MercadoPagoBillingProvider();
case 'STRIPE':
return new StripeBillingProvider();
}
};

View File

@@ -0,0 +1,26 @@
import type { CountryCode } from '@gruperly/shared';
export type PlatformCredentials = {
/** Access token of Gruperly's own Mercado Pago account in that country. */
accessToken: string;
/** Secret of the webhook configured in that account's panel. */
webhookSecret: string;
};
/**
* Gruperly's Mercado Pago credentials for one country. Mercado Pago does not
* charge across countries, so each country has its own account; a country
* without both variables cannot subscribe to Pro through Mercado Pago (503, not
* a deployment crash: rolling out country by country is expected).
*
* These are platform credentials, never the professor's OAuth token.
*/
export function getPlatformCredentials(
country: CountryCode,
env: Record<string, string | undefined> = process.env,
): PlatformCredentials | null {
const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim();
const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim();
if (!accessToken || !webhookSecret) return null;
return { accessToken, webhookSecret };
}

View File

@@ -0,0 +1,199 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared';
import { countryCodeSchema, err, ok } from '@gruperly/shared';
import {
type BillingProvider,
BillingProviderNotConfigured,
type BillingWebhookFailure,
type BillingWebhookHint,
type BillingWebhookRequest,
type ChargeStatus,
type ProviderCharge,
type ProviderSubscription,
type StartedSubscription,
type StartSubscriptionInput,
type SubscriptionRef,
} from '../billing-provider';
import { getPlatformCredentials, type PlatformCredentials } from './config';
import { type MpAuthorizedPayment, mpPreapprovalClient, type PreapprovalClient } from './preapproval';
import { verifyMpSignature } from './webhook-signature';
export { getPlatformCredentials, type PlatformCredentials } from './config';
export {
type MpAuthorizedPayment,
type MpPreapproval,
mpPreapprovalClient,
type PreapprovalClient,
} from './preapproval';
export { verifyMpSignature } from './webhook-signature';
const SUBSCRIPTION_REASON = 'Gruperly Pro';
const MP_STATUS: Record<string, SubscriptionStatus> = {
pending: 'PENDING',
authorized: 'AUTHORIZED',
paused: 'PAUSED',
cancelled: 'CANCELLED',
};
const REJECTED_PAYMENT = new Set(['rejected', 'cancelled', 'refunded', 'charged_back']);
/** One approved monthly charge covers one month from the day it was debited. */
export function coveredUntil(paidAt: Date): Date {
const until = new Date(paidAt);
until.setUTCMonth(until.getUTCMonth() + 1);
return until;
}
export function toChargeStatus(invoice: Pick<MpAuthorizedPayment, 'status' | 'paymentStatus'>): ChargeStatus {
if (invoice.paymentStatus === 'approved') return 'approved';
if (invoice.paymentStatus && REJECTED_PAYMENT.has(invoice.paymentStatus)) return 'rejected';
return invoice.status === 'cancelled' ? 'rejected' : 'pending';
}
type MercadoPagoBillingDeps = {
client?: PreapprovalClient;
credentials?: (country: CountryCode) => PlatformCredentials | null;
};
/**
* Pro through Mercado Pago Subscriptions (preapproval), collected by
* Gruperly's own account in the professor's country. The preapproval exists as
* soon as it is created, so `externalId` is known from the start and there is
* no `checkoutRef`.
*/
export class MercadoPagoBillingProvider implements BillingProvider {
readonly id = 'MERCADO_PAGO' as const;
readonly requiresPayerEmail = true;
constructor(private readonly deps: MercadoPagoBillingDeps = {}) {}
private get client(): PreapprovalClient {
return this.deps.client ?? mpPreapprovalClient;
}
private credentialsFor(country: CountryCode | null): PlatformCredentials | null {
return country ? (this.deps.credentials ?? getPlatformCredentials)(country) : null;
}
private tokenFor(country: CountryCode | null): string {
const credentials = this.credentialsFor(country);
if (!credentials) throw new BillingProviderNotConfigured(this.id);
return credentials.accessToken;
}
isAvailable(country: CountryCode): boolean {
return this.credentialsFor(country) !== null;
}
async start(input: StartSubscriptionInput): Promise<StartedSubscription> {
if (!input.payerEmail) throw new Error('Mercado Pago needs the payer email');
const preapproval = await this.client.createPreapproval(this.tokenFor(input.country), {
reason: SUBSCRIPTION_REASON,
externalReference: input.userId,
payerEmail: input.payerEmail,
amount: input.amount,
currencyId: input.currency,
backUrl: input.backUrl,
startDate: input.startDate,
});
if (!preapproval.initPoint) throw new Error('Mercado Pago preapproval came back without init_point');
return { checkoutUrl: preapproval.initPoint, externalId: preapproval.id, checkoutRef: null };
}
async fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null> {
if (!ref.externalId) return null;
const preapproval = await this.client.getPreapproval(this.tokenFor(ref.country), ref.externalId);
return {
externalId: preapproval.id,
ownerUserId: preapproval.externalReference,
status: MP_STATUS[preapproval.status] ?? null,
nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null,
payerEmail: null,
};
}
async listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]> {
const invoices = await this.client.searchAuthorizedPayments(this.tokenFor(ref.country), ref.externalId);
return invoices
.filter((invoice) => invoice.preapprovalId === ref.externalId)
.map((invoice) => {
const status = toChargeStatus(invoice);
const debitedAt = invoice.debitDate ?? invoice.createdAt;
const paidAt = status === 'approved' && debitedAt ? new Date(debitedAt) : null;
return {
externalId: invoice.id,
amount: invoice.amount,
currency: invoice.currencyId || null,
status,
paidAt,
coveredUntil: paidAt ? coveredUntil(paidAt) : null,
};
});
}
async cancel(ref: SubscriptionRef): Promise<void> {
if (!ref.externalId) return;
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
}
/**
* One URL per country, because each country is a different Gruperly account
* with its own secret. Mercado Pago signs a manifest of the notified id, the
* `x-request-id` and a timestamp (`x-signature`), not the body.
*/
async parseWebhook(
request: BillingWebhookRequest,
): Promise<Result<BillingWebhookHint, BillingWebhookFailure>> {
const parsedCountry = countryCodeSchema.safeParse(request.routeParam?.toUpperCase());
if (!parsedCountry.success) return err('unknown_country');
const country = parsedCountry.data;
const credentials = this.credentialsFor(country);
if (!credentials) return err('not_configured');
const body = parseBody(request.rawBody);
const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId;
const type = request.query.get('type') ?? request.query.get('topic') ?? body.type;
const requestId = request.headers.get('x-request-id');
const valid = verifyMpSignature({
signature: request.headers.get('x-signature'),
requestId,
dataId,
secret: credentials.webhookSecret,
});
if (!valid) return err('invalid_signature');
const hint: BillingWebhookHint = { source: `mp:${country}`, dedupeKey: requestId, country, externalId: null };
if (!dataId || !isSubscriptionTopic(type)) return ok(hint);
if (type === 'subscription_preapproval') return ok({ ...hint, externalId: dataId });
// An invoice notification: the subscription is its preapproval.
try {
const invoice = await this.client.getAuthorizedPayment(credentials.accessToken, dataId);
return ok({ ...hint, externalId: invoice.preapprovalId });
} catch {
return err('sync_failed');
}
}
}
function isSubscriptionTopic(
type: string | null,
): type is 'subscription_preapproval' | 'subscription_authorized_payment' {
return type === 'subscription_preapproval' || type === 'subscription_authorized_payment';
}
function parseBody(rawBody: string): { dataId: string | null; type: string | null } {
try {
const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null;
return {
dataId: payload?.data?.id == null ? null : String(payload.data.id),
type: typeof payload?.type === 'string' ? payload.type : null,
};
} catch {
return { dataId: null, type: null };
}
}

View File

@@ -152,15 +152,29 @@ export async function getAuthorizedPayment(
); );
} }
/** The invoices of one subscription, newest first as Mercado Pago returns them. */ /** 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( export async function searchAuthorizedPayments(
accessToken: string, accessToken: string,
preapprovalId: string, preapprovalId: string,
): Promise<MpAuthorizedPayment[]> { ): Promise<MpAuthorizedPayment[]> {
const query = new URLSearchParams({ preapproval_id: preapprovalId, limit: '50' }); 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 payload = await request(accessToken, `/authorized_payments/search?${query}`);
const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : []; const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
return results.map(toAuthorizedPayment); 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 = { export type PreapprovalClient = {

View File

@@ -0,0 +1,18 @@
export type StripeConfig = {
/** Secret key of Gruperly's single Stripe account (`sk_live_…` / `sk_test_…`). */
secretKey: string;
/** Signing secret of the webhook endpoint (`whsec_…`). */
webhookSecret: string;
};
/**
* One Stripe account collects Pro in every country that is not on Mercado Pago,
* each in its own currency. Without both variables those countries see Pro as
* "no disponible" (503), the same as a Mercado Pago country without credentials.
*/
export function getStripeConfig(env: Record<string, string | undefined> = process.env): StripeConfig | null {
const secretKey = env.STRIPE_SECRET_KEY?.trim();
const webhookSecret = env.STRIPE_WEBHOOK_SECRET?.trim();
if (!secretKey || !webhookSecret) return null;
return { secretKey, webhookSecret };
}

View File

@@ -0,0 +1,300 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
type BillingProvider,
BillingProviderNotConfigured,
type BillingWebhookFailure,
type BillingWebhookHint,
type BillingWebhookRequest,
type ChargeStatus,
type ProviderCharge,
type ProviderSubscription,
type StartedSubscription,
type StartSubscriptionInput,
type SubscriptionRef,
} from '../billing-provider';
import { getStripeConfig, type StripeConfig } from './config';
import { createStripeRequest, type StripeObject, type StripeRequest } from './stripe-http';
import { verifyStripeSignature } from './webhook-signature';
export { getStripeConfig, type StripeConfig } from './config';
export { STRIPE_API_VERSION, StripeApiError, toForm } from './stripe-http';
export { verifyStripeSignature } from './webhook-signature';
const PRODUCT_NAME = 'Gruperly Pro';
/** Our user id on the Stripe subscription: what ties it back to a professor. */
const USER_ID_METADATA = 'gruperly_user_id';
/** Checkout only accepts a `trial_end` at least this far ahead. */
const MIN_TRIAL_MS = 48 * 60 * 60 * 1000;
// Stripe takes amounts in the currency's minor unit, except these.
const ZERO_DECIMAL_CURRENCIES = new Set([
'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF',
]);
export function toStripeUnitAmount(amount: number, currency: string): number {
return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? Math.round(amount) : Math.round(amount * 100);
}
export function fromStripeUnitAmount(unitAmount: number, currency: string): number {
return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? unitAmount : unitAmount / 100;
}
const STRIPE_STATUS: Record<string, SubscriptionStatus> = {
incomplete: 'PENDING',
active: 'AUTHORIZED',
trialing: 'AUTHORIZED',
// Stripe is retrying the charge; Pro survives it on `paidThrough` + grace.
past_due: 'AUTHORIZED',
unpaid: 'PAUSED',
paused: 'PAUSED',
canceled: 'CANCELLED',
incomplete_expired: 'CANCELLED',
};
const INVOICE_STATUS: Record<string, ChargeStatus> = {
paid: 'approved',
open: 'pending',
uncollectible: 'rejected',
void: 'rejected',
};
type StripeBillingDeps = {
config?: () => StripeConfig | null;
fetch?: typeof fetch;
now?: () => Date;
};
/**
* Pro through Stripe Billing: a Checkout Session in subscription mode, priced
* inline in the professor's currency (`PRO_PRICE_BY_COUNTRY`), so there are no
* Prices to keep in sync in the Dashboard.
*
* The Stripe subscription only exists once the professor completes the
* checkout: until then the row carries the session id (`checkoutRef`) and
* `fetch` resolves the subscription through it.
*/
export class StripeBillingProvider implements BillingProvider {
readonly id = 'STRIPE' as const;
readonly requiresPayerEmail = false;
constructor(private readonly deps: StripeBillingDeps = {}) {}
private get config(): StripeConfig | null {
return (this.deps.config ?? getStripeConfig)();
}
private get request(): StripeRequest {
const config = this.config;
if (!config) throw new BillingProviderNotConfigured(this.id);
return createStripeRequest(config.secretKey, this.deps.fetch);
}
isAvailable(_country: CountryCode): boolean {
return this.config !== null;
}
async start(input: StartSubscriptionInput): Promise<StartedSubscription> {
const now = this.deps.now?.() ?? new Date();
// Re-subscribing within a paid period: the first charge waits for its end.
// Closer than Checkout allows, it is charged now instead (a few days overlap).
const trialEnd =
input.startDate && input.startDate.getTime() - now.getTime() >= MIN_TRIAL_MS
? Math.floor(input.startDate.getTime() / 1000)
: null;
const session = await this.request('/checkout/sessions', {
method: 'POST',
form: {
mode: 'subscription',
client_reference_id: input.userId,
customer_email: input.payerEmail,
success_url: input.backUrl,
cancel_url: input.backUrl,
line_items: [
{
quantity: 1,
price_data: {
currency: input.currency.toLowerCase(),
unit_amount: toStripeUnitAmount(input.amount, input.currency),
recurring: { interval: 'month' },
product_data: { name: PRODUCT_NAME },
},
},
],
subscription_data: {
metadata: { [USER_ID_METADATA]: input.userId },
trial_end: trialEnd,
},
},
});
const url = stringOf(session.url);
if (!url) throw new Error('Stripe checkout session came back without url');
return { checkoutUrl: url, externalId: null, checkoutRef: String(session.id) };
}
async fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null> {
const request = this.request;
let subscriptionId = ref.externalId;
let payerEmail: string | null = null;
if (!subscriptionId) {
if (!ref.checkoutRef) return null;
const session = await request(`/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`);
subscriptionId = idOf(session.subscription);
payerEmail = stringOf(objectOf(session.customer_details)?.email);
if (!subscriptionId) return null;
}
const subscription = await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, {
query: new URLSearchParams({ 'expand[]': 'customer' }),
});
const status = STRIPE_STATUS[String(subscription.status)] ?? null;
return {
externalId: String(subscription.id),
ownerUserId: stringOf(objectOf(subscription.metadata)?.[USER_ID_METADATA]),
status,
nextPaymentDate: status === 'CANCELLED' ? null : nextChargeOf(subscription),
payerEmail: payerEmail ?? stringOf(objectOf(subscription.customer)?.email),
};
}
async listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]> {
const page = await this.request('/invoices', {
query: new URLSearchParams({ subscription: ref.externalId, limit: '50' }),
});
const invoices = Array.isArray(page.data) ? (page.data as StripeObject[]) : [];
return invoices.flatMap((invoice) => {
const status = INVOICE_STATUS[String(invoice.status)];
// Drafts are not charges yet, and a zero invoice (a trial) charges nothing.
if (!status || Number(invoice.total ?? 0) === 0) return [];
const currency = String(invoice.currency ?? '').toUpperCase();
const unitAmount = Number(status === 'approved' ? invoice.amount_paid : invoice.amount_due);
const paidAt = status === 'approved' ? dateOf(objectOf(invoice.status_transitions)?.paid_at) : null;
return [
{
externalId: String(invoice.id),
amount: fromStripeUnitAmount(unitAmount || 0, currency),
currency: currency || null,
status,
paidAt,
coveredUntil: paidAt ? (periodEndOf(invoice) ?? oneMonthAfter(paidAt)) : null,
},
];
});
}
/**
* A live subscription is cancelled right away (Pro lasts on `paidThrough`).
* A checkout still open is expired, so it cannot be completed later; one that
* was completed meanwhile has a subscription, which is cancelled instead.
*/
async cancel(ref: SubscriptionRef): Promise<void> {
const request = this.request;
let subscriptionId = ref.externalId;
if (!subscriptionId && ref.checkoutRef) {
const path = `/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`;
const session = await request(path);
if (session.status === 'open') {
await request(`${path}/expire`, { method: 'POST' });
return;
}
subscriptionId = idOf(session.subscription);
}
if (subscriptionId) {
await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, { method: 'DELETE' });
}
}
/** A single endpoint for the whole account; the event id is the dedupe key. */
async parseWebhook(
request: BillingWebhookRequest,
): Promise<Result<BillingWebhookHint, BillingWebhookFailure>> {
const config = this.config;
if (!config) return err('not_configured');
const valid = verifyStripeSignature({
signature: request.headers.get('stripe-signature'),
rawBody: request.rawBody,
secret: config.webhookSecret,
now: this.deps.now?.(),
});
if (!valid) return err('invalid_signature');
let event: StripeObject;
try {
event = JSON.parse(request.rawBody) as StripeObject;
} catch {
return err('invalid_signature');
}
return ok({
source: 'stripe',
dedupeKey: stringOf(event.id),
country: null,
externalId: subscriptionOfEvent(String(event.type), objectOf(objectOf(event.data)?.object)),
});
}
}
/** The subscription an event is about, for the events that change Pro. */
function subscriptionOfEvent(type: string, object: StripeObject | null): string | null {
if (!object) return null;
if (type === 'checkout.session.completed' || type === 'checkout.session.async_payment_succeeded') {
return object.mode === 'subscription' ? idOf(object.subscription) : null;
}
if (type.startsWith('customer.subscription.')) return idOf(object.id);
if (type.startsWith('invoice.')) {
const details = objectOf(objectOf(object.parent)?.subscription_details);
return idOf(details?.subscription) ?? idOf(object.subscription);
}
return null;
}
/** Next charge: the end of the trial or of the current period. */
function nextChargeOf(subscription: StripeObject): Date | null {
if (subscription.status === 'trialing') return dateOf(subscription.trial_end);
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
return dateOf(item?.current_period_end ?? subscription.current_period_end);
}
/** The last day the invoice's lines pay for. */
function periodEndOf(invoice: StripeObject): Date | null {
const lines = (objectOf(invoice.lines)?.data as unknown[] | undefined) ?? [];
const ends = lines
.map((line) => dateOf(objectOf(objectOf(line)?.period)?.end))
.filter((end): end is Date => end !== null);
return ends.length > 0 ? new Date(Math.max(...ends.map((end) => end.getTime()))) : null;
}
function oneMonthAfter(date: Date): Date {
const until = new Date(date);
until.setUTCMonth(until.getUTCMonth() + 1);
return until;
}
function objectOf(value: unknown): StripeObject | null {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as StripeObject) : null;
}
function stringOf(value: unknown): string | null {
return typeof value === 'string' && value ? value : null;
}
/** An expandable field: the id, or the expanded object's id. */
function idOf(value: unknown): string | null {
return stringOf(value) ?? stringOf(objectOf(value)?.id);
}
/** Stripe timestamps are Unix seconds. */
function dateOf(value: unknown): Date | null {
return typeof value === 'number' && value > 0 ? new Date(value * 1000) : null;
}

View File

@@ -0,0 +1,82 @@
import { logger } from '@/logger';
// Stripe's REST API with plain `fetch` (no SDK, like Mercado Pago and Kapso):
// form-encoded bodies, JSON answers, and a pinned API version so a change in
// the account's default version cannot reshape the payloads under us.
export const STRIPE_API_URL = 'https://api.stripe.com/v1';
export const STRIPE_API_VERSION = '2025-03-31.basil';
export type StripeObject = Record<string, unknown>;
export class StripeApiError extends Error {
constructor(
readonly status: number,
readonly code: string | null,
) {
super(`Stripe request failed with status ${status}`);
this.name = 'StripeApiError';
}
}
type FormValue = string | number | boolean | null | undefined | FormValue[] | { [key: string]: FormValue };
/**
* Stripe's form encoding of nested params: `a[b][0][c]=1`. `null`/`undefined`
* are left out.
*/
export function toForm(params: Record<string, FormValue>): URLSearchParams {
const form = new URLSearchParams();
const add = (key: string, value: FormValue) => {
if (value === null || value === undefined) return;
if (Array.isArray(value)) {
for (const [index, item] of value.entries()) add(`${key}[${index}]`, item);
return;
}
if (typeof value === 'object') {
for (const [child, nested] of Object.entries(value)) add(`${key}[${child}]`, nested);
return;
}
form.append(key, String(value));
};
for (const [key, value] of Object.entries(params)) add(key, value);
return form;
}
export type StripeRequest = (
path: string,
init?: { method?: 'GET' | 'POST' | 'DELETE'; form?: Record<string, FormValue>; query?: URLSearchParams },
) => Promise<StripeObject>;
export function createStripeRequest(secretKey: string, fetchImpl: typeof fetch = fetch): StripeRequest {
return async (path, init = {}) => {
const method = init.method ?? 'GET';
const query = init.query?.toString();
let response: Response;
try {
response = await fetchImpl(`${STRIPE_API_URL}${path}${query ? `?${query}` : ''}`, {
method,
headers: {
Authorization: `Bearer ${secretKey}`,
'Stripe-Version': STRIPE_API_VERSION,
...(init.form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),
},
body: init.form ? toForm(init.form).toString() : undefined,
});
} catch (error) {
logger.error({ err: error, path }, 'Stripe unreachable');
throw new StripeApiError(0, null);
}
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: StripeObject } | null;
const code = typeof payload?.error?.code === 'string' ? payload.error.code : null;
// Only the error code: Stripe's messages can echo what we sent (emails).
// The path carries ids, never keys or emails.
logger.error({ status: response.status, code, path }, 'Stripe request failed');
throw new StripeApiError(response.status, code);
}
return (await response.json()) as StripeObject;
};
}

View File

@@ -0,0 +1,41 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/** Stripe's own default: older deliveries are treated as replays. */
const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
/**
* Checks Stripe's `Stripe-Signature` header (`t=<ts>,v1=<hex>[,v1=<hex>…]`).
*
* Stripe signs `<ts>.<raw body>` with the endpoint secret (HMAC-SHA256). There
* can be several `v1` while a secret is being rolled; any of them may match.
*/
export function verifyStripeSignature(params: {
signature: string | null;
rawBody: string;
secret: string;
now?: Date;
toleranceSeconds?: number;
}): boolean {
if (!params.signature) return false;
let timestamp: string | null = null;
const candidates: string[] = [];
for (const part of params.signature.split(',')) {
const [key, value] = part.split('=', 2).map((piece) => piece.trim());
if (key === 't') timestamp = value ?? null;
if (key === 'v1' && value) candidates.push(value);
}
if (!timestamp || !/^\d+$/.test(timestamp) || candidates.length === 0) return false;
const nowSeconds = Math.floor((params.now ?? new Date()).getTime() / 1000);
const tolerance = params.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) return false;
const expected = Buffer.from(
createHmac('sha256', params.secret).update(`${timestamp}.${params.rawBody}`).digest('hex'),
);
return candidates.some((candidate) => {
const received = Buffer.from(candidate);
return received.length === expected.length && timingSafeEqual(received, expected);
});
}

View File

@@ -0,0 +1,242 @@
import { describe, expect, it, mock } from 'bun:test';
import { createHmac } from 'node:crypto';
import {
fromStripeUnitAmount,
StripeBillingProvider,
toForm,
toStripeUnitAmount,
verifyStripeSignature,
} from '@/modules/billing/providers/stripe';
const now = new Date('2026-10-22T12:00:00.000Z');
const seconds = (date: Date) => Math.floor(date.getTime() / 1000);
type Call = { url: string; method: string; body: URLSearchParams | null };
/** A fake `fetch` answering by "METHOD path" (query left out). */
function fakeStripe(routes: Record<string, unknown>) {
const calls: Call[] = [];
const fetch = mock(async (input: string, init: RequestInit) => {
const url = new URL(input);
const method = init.method ?? 'GET';
calls.push({ url: input, method, body: init.body ? new URLSearchParams(String(init.body)) : null });
const key = `${method} ${url.pathname.replace('/v1', '')}`;
if (!(key in routes)) return new Response(JSON.stringify({ error: { code: 'resource_missing' } }), { status: 404 });
return new Response(JSON.stringify(routes[key]));
});
const provider = new StripeBillingProvider({
config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }),
fetch: fetch as never,
now: () => now,
});
return { provider, calls };
}
const startInput = {
userId: 'user-1',
country: 'MX' as const,
amount: 199,
currency: 'MXN',
payerEmail: null,
backUrl: 'http://web/billing?sub=return',
};
describe('Stripe amounts', () => {
it('uses minor units except for zero-decimal currencies', () => {
expect(toStripeUnitAmount(199, 'MXN')).toBe(19900);
expect(toStripeUnitAmount(9900, 'CLP')).toBe(9900);
expect(fromStripeUnitAmount(19900, 'mxn')).toBe(199);
expect(fromStripeUnitAmount(9900, 'clp')).toBe(9900);
});
it('encodes nested params the way Stripe expects', () => {
const form = toForm({ a: { b: [{ c: 1 }] }, skip: null });
expect(form.toString()).toBe(new URLSearchParams({ 'a[b][0][c]': '1' }).toString());
});
});
describe('StripeBillingProvider.start', () => {
it('opens a subscription checkout priced inline in the local currency', async () => {
const { provider, calls } = fakeStripe({
'POST /checkout/sessions': { id: 'cs_1', url: 'https://checkout.stripe.com/cs_1' },
});
const started = await provider.start(startInput);
expect(started).toEqual({ checkoutUrl: 'https://checkout.stripe.com/cs_1', externalId: null, checkoutRef: 'cs_1' });
const body = calls[0]?.body;
expect(body?.get('mode')).toBe('subscription');
expect(body?.get('client_reference_id')).toBe('user-1');
expect(body?.get('line_items[0][price_data][currency]')).toBe('mxn');
expect(body?.get('line_items[0][price_data][unit_amount]')).toBe('19900');
expect(body?.get('line_items[0][price_data][recurring][interval]')).toBe('month');
expect(body?.get('subscription_data[metadata][gruperly_user_id]')).toBe('user-1');
expect(body?.has('customer_email')).toBe(false);
expect(body?.has('subscription_data[trial_end]')).toBe(false);
});
it('defers the first charge to the end of a paid period', async () => {
const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } });
const startDate = new Date('2026-11-10T00:00:00.000Z');
await provider.start({ ...startInput, startDate });
expect(calls[0]?.body?.get('subscription_data[trial_end]')).toBe(String(seconds(startDate)));
});
it('charges right away when the paid period ends sooner than Checkout allows', async () => {
const { provider, calls } = fakeStripe({ 'POST /checkout/sessions': { id: 'cs_1', url: 'https://x' } });
await provider.start({ ...startInput, startDate: new Date('2026-10-23T00:00:00.000Z') });
expect(calls[0]?.body?.has('subscription_data[trial_end]')).toBe(false);
});
});
describe('StripeBillingProvider.fetch', () => {
it('is null while the checkout is open', async () => {
const { provider } = fakeStripe({ 'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open', subscription: null } });
expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toBeNull();
});
it('resolves the subscription through a completed checkout', async () => {
const periodEnd = new Date('2026-11-22T12:00:00.000Z');
const { provider } = fakeStripe({
'GET /checkout/sessions/cs_1': {
id: 'cs_1',
status: 'complete',
subscription: 'sub_1',
customer_details: { email: 'card@mail.com' },
},
'GET /subscriptions/sub_1': {
id: 'sub_1',
status: 'active',
metadata: { gruperly_user_id: 'user-1' },
items: { data: [{ current_period_end: seconds(periodEnd) }] },
customer: { id: 'cus_1', email: 'other@mail.com' },
},
});
expect(await provider.fetch({ country: 'MX', externalId: null, checkoutRef: 'cs_1' })).toEqual({
externalId: 'sub_1',
ownerUserId: 'user-1',
status: 'AUTHORIZED',
nextPaymentDate: periodEnd,
payerEmail: 'card@mail.com',
});
});
it('maps Stripe statuses to ours', async () => {
const statusOf = async (status: string) => {
const { provider } = fakeStripe({
'GET /subscriptions/sub_1': { id: 'sub_1', status, metadata: {}, items: { data: [] } },
});
return (await provider.fetch({ country: null, externalId: 'sub_1', checkoutRef: null }))?.status;
};
expect(await statusOf('incomplete')).toBe('PENDING');
expect(await statusOf('past_due')).toBe('AUTHORIZED');
expect(await statusOf('unpaid')).toBe('PAUSED');
expect(await statusOf('canceled')).toBe('CANCELLED');
expect(await statusOf('something_new')).toBeNull();
});
});
describe('StripeBillingProvider.listCharges', () => {
it('turns invoices into charges covering their period', async () => {
const paidAt = new Date('2026-10-22T12:00:00.000Z');
const periodEnd = new Date('2026-11-22T12:00:00.000Z');
const { provider } = fakeStripe({
'GET /invoices': {
data: [
{
id: 'in_1',
status: 'paid',
total: 19900,
amount_paid: 19900,
currency: 'mxn',
status_transitions: { paid_at: seconds(paidAt) },
lines: { data: [{ period: { end: seconds(periodEnd) } }] },
},
{ id: 'in_2', status: 'open', total: 19900, amount_due: 19900, currency: 'mxn' },
{ id: 'in_3', status: 'uncollectible', total: 19900, amount_due: 19900, currency: 'mxn' },
{ id: 'in_trial', status: 'paid', total: 0, amount_paid: 0, currency: 'mxn' },
{ id: 'in_draft', status: 'draft', total: 19900, currency: 'mxn' },
],
},
});
const charges = await provider.listCharges({ country: 'MX', externalId: 'sub_1', checkoutRef: null });
expect(charges).toEqual([
{ externalId: 'in_1', amount: 199, currency: 'MXN', status: 'approved', paidAt, coveredUntil: periodEnd },
{ externalId: 'in_2', amount: 199, currency: 'MXN', status: 'pending', paidAt: null, coveredUntil: null },
{ externalId: 'in_3', amount: 199, currency: 'MXN', status: 'rejected', paidAt: null, coveredUntil: null },
]);
});
});
describe('StripeBillingProvider.cancel', () => {
it('cancels a live subscription', async () => {
const { provider, calls } = fakeStripe({ 'DELETE /subscriptions/sub_1': { id: 'sub_1', status: 'canceled' } });
await provider.cancel({ country: 'MX', externalId: 'sub_1', checkoutRef: 'cs_1' });
expect(calls.map((call) => `${call.method} ${new URL(call.url).pathname}`)).toEqual(['DELETE /v1/subscriptions/sub_1']);
});
it('expires a checkout that is still open', async () => {
const { provider, calls } = fakeStripe({
'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'open' },
'POST /checkout/sessions/cs_1/expire': { id: 'cs_1', status: 'expired' },
});
await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' });
expect(calls.map((call) => call.method)).toEqual(['GET', 'POST']);
});
it('cancels the subscription of a checkout completed meanwhile', async () => {
const { provider, calls } = fakeStripe({
'GET /checkout/sessions/cs_1': { id: 'cs_1', status: 'complete', subscription: 'sub_1' },
'DELETE /subscriptions/sub_1': { id: 'sub_1' },
});
await provider.cancel({ country: 'MX', externalId: null, checkoutRef: 'cs_1' });
expect(calls.at(-1)?.method).toBe('DELETE');
});
});
describe('StripeBillingProvider without credentials', () => {
it('is not available and refuses to call Stripe', async () => {
const provider = new StripeBillingProvider({ config: () => null });
expect(provider.isAvailable('MX')).toBe(false);
await expect(provider.start(startInput)).rejects.toThrow('not configured');
});
});
describe('verifyStripeSignature', () => {
const secret = 'whsec_test';
const rawBody = '{"id":"evt_1"}';
const t = seconds(now);
const sign = (ts: number, body = rawBody) => createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex');
it('accepts a valid signature, including one among several v1', () => {
expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody, secret, now })).toBe(true);
expect(verifyStripeSignature({ signature: `t=${t},v1=${'0'.repeat(64)},v1=${sign(t)}`, rawBody, secret, now })).toBe(
true,
);
});
it('rejects a tampered body, a missing header and an old timestamp', () => {
expect(verifyStripeSignature({ signature: `t=${t},v1=${sign(t)}`, rawBody: '{"id":"evt_2"}', secret, now })).toBe(
false,
);
expect(verifyStripeSignature({ signature: null, rawBody, secret, now })).toBe(false);
const old = t - 10 * 60;
expect(verifyStripeSignature({ signature: `t=${old},v1=${sign(old)}`, rawBody, secret, now })).toBe(false);
});
});

View File

@@ -1,19 +1,19 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { billingNotAvailableProblem } from '@/http/problem-builders';
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
import type { PreapprovalClient } from '@/modules/billing/lib'; import type { BillingProvider } from '@/modules/billing/providers';
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
const userId = 'user-1'; const userId = 'user-1';
const now = new Date('2026-10-22T12:00:00.000Z'); const now = new Date('2026-10-22T12:00:00.000Z');
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' }); const credentials = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' });
let calls: string[] = []; let calls: string[] = [];
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'MX') { // Argentina: Mercado Pago. Any other country goes to Stripe.
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'AR') {
return { return {
user: { findUnique: mock(async () => ({ id: userId, country })) }, user: { findUnique: mock(async () => ({ id: userId, country, email: 'login@mail.com' })) },
billingSubscription: { billingSubscription: {
findUnique: mock(async () => existing), findUnique: mock(async () => existing),
upsert: mock(async (args: { create: Record<string, unknown> }) => { upsert: mock(async (args: { create: Record<string, unknown> }) => {
@@ -44,11 +44,16 @@ function makeClient(): PreapprovalClient {
} as unknown as PreapprovalClient; } as unknown as PreapprovalClient;
} }
function mpProvider(client: PreapprovalClient) {
return new MercadoPagoBillingProvider({ client, credentials });
}
function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) { function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
const provider = mpProvider(client);
return { return {
client, client,
run: (returnTo: 'billing' | 'onboarding' = 'billing') => run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
new Subscribe({ db: db as never, client, credentials, webOrigin: 'http://web', now: () => now }).execute( new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute(
userId, userId,
{ payerEmail: 'profe@mail.com', returnTo }, { payerEmail: 'profe@mail.com', returnTo },
), ),
@@ -72,14 +77,14 @@ describe('Subscribe', () => {
reason: 'Gruperly Pro', reason: 'Gruperly Pro',
externalReference: userId, externalReference: userId,
payerEmail: 'profe@mail.com', payerEmail: 'profe@mail.com',
amount: 199, amount: 15000,
currencyId: 'MXN', currencyId: 'ARS',
backUrl: 'http://web/billing?sub=return', backUrl: 'http://web/billing?sub=return',
startDate: undefined, startDate: undefined,
}); });
expect(db.billingSubscription.update).toHaveBeenCalledWith({ expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' }, where: { id: 'sub-1' },
data: { mpPreapprovalId: 'pre-1', lastSyncedAt: now }, data: { externalId: 'pre-1', checkoutRef: null, lastSyncedAt: now },
}); });
}); });
@@ -93,7 +98,7 @@ describe('Subscribe', () => {
}); });
it('refuses a second subscription while one is authorized', async () => { it('refuses a second subscription while one is authorized', async () => {
const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', mpPreapprovalId: 'pre-0' })); const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', provider: 'MERCADO_PAGO', externalId: 'pre-0' }));
const result = await run(); const result = await run();
@@ -103,7 +108,7 @@ describe('Subscribe', () => {
}); });
it('cancels an abandoned attempt before starting a new one', async () => { it('cancels an abandoned attempt before starting a new one', async () => {
const { run } = subscribe(makeDb({ status: 'PENDING', mpPreapprovalId: 'old' })); const { run } = subscribe(makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null }));
await run(); await run();
@@ -112,7 +117,7 @@ describe('Subscribe', () => {
it('delays the first charge to the end of a period already paid', async () => { it('delays the first charge to the end of a period already paid', async () => {
const paidThrough = new Date('2026-11-10T00:00:00.000Z'); const paidThrough = new Date('2026-11-10T00:00:00.000Z');
const { client, run } = subscribe(makeDb({ status: 'CANCELLED', mpPreapprovalId: 'old', paidThrough })); const { client, run } = subscribe(makeDb({ status: 'CANCELLED', provider: 'MERCADO_PAGO', externalId: 'old', paidThrough }));
await run(); await run();
@@ -123,13 +128,13 @@ describe('Subscribe', () => {
}); });
it('answers 503 when Gruperly has no account in that country', async () => { it('answers 503 when Gruperly has no account in that country', async () => {
const db = makeDb(null, 'PE'); const db = makeDb(null, 'AR');
const client = makeClient(); const client = makeClient();
const result = await new Subscribe({ const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
db: db as never, const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
client, payerEmail: 'profe@mail.com',
credentials: () => ({ ok: false, error: billingNotAvailableProblem() }), returnTo: 'billing',
}).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing' }); });
expect(result.ok).toBe(false); expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' }); if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' });
@@ -155,13 +160,21 @@ describe('CancelSubscription', () => {
it('cancels in Mercado Pago and keeps what was paid', async () => { it('cancels in Mercado Pago and keeps what was paid', async () => {
const db = { const db = {
billingSubscription: { billingSubscription: {
findUnique: mock(async () => ({ id: 'sub-1', status: 'AUTHORIZED', mpPreapprovalId: 'pre-1', country: 'AR' })), findUnique: mock(async () => ({
id: 'sub-1',
status: 'AUTHORIZED',
provider: 'MERCADO_PAGO',
externalId: 'pre-1',
checkoutRef: null,
country: 'AR',
})),
update: mock(async () => ({})), update: mock(async () => ({})),
}, },
}; };
const client = makeClient(); const client = makeClient();
const result = await new CancelSubscription({ db: db as never, client, credentials }).execute(userId); const provider = mpProvider(client);
const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId);
expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } }); expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } });
expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1'); expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1');
@@ -174,9 +187,113 @@ describe('CancelSubscription', () => {
it('has nothing to cancel without a live subscription', async () => { it('has nothing to cancel without a live subscription', async () => {
const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } }; const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } };
const result = await new CancelSubscription({ db: db as never, client: makeClient(), credentials }).execute(userId); const provider = mpProvider(makeClient());
const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId);
expect(result.ok).toBe(false); expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('no_active_subscription'); if (!result.ok) expect(result.error.code).toBe('no_active_subscription');
}); });
}); });
function fakeStripe(overrides: Partial<BillingProvider> = {}) {
return {
id: 'STRIPE',
requiresPayerEmail: false,
isAvailable: () => true,
start: mock(async () => {
calls.push('start');
return { checkoutUrl: 'https://checkout.stripe/cs_1', externalId: null, checkoutRef: 'cs_1' };
}),
fetch: mock(),
listCharges: mock(),
cancel: mock(async () => {
calls.push('cancel');
}),
parseWebhook: mock(),
...overrides,
} as BillingProvider;
}
describe('Subscribe outside Argentina (Stripe)', () => {
beforeEach(() => {
calls = [];
});
it('picks the provider of the country and starts a checkout without asking the email', async () => {
const db = makeDb(null, 'MX');
const stripe = fakeStripe();
const resolved: string[] = [];
const result = await new Subscribe({
db: db as never,
providers: (id) => {
resolved.push(id);
return stripe;
},
webOrigin: 'http://web',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
expect(resolved).toEqual(['STRIPE']);
expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://checkout.stripe/cs_1' } });
expect(stripe.start).toHaveBeenCalledWith({
userId,
country: 'MX',
amount: 199,
currency: 'MXN',
payerEmail: null,
backUrl: 'http://web/billing?sub=return',
startDate: undefined,
});
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
provider: 'STRIPE',
payerEmail: 'login@mail.com',
});
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: { externalId: null, checkoutRef: 'cs_1', lastSyncedAt: now },
});
});
it('voids an abandoned attempt with the provider it was created with', async () => {
const db = makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null }, 'MX');
const client = makeClient();
const mp = mpProvider(client);
const stripe = fakeStripe();
await new Subscribe({
db: db as never,
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
webOrigin: 'http://web',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
expect(calls).toEqual(['cancelPreapproval', 'upsert', 'start', 'update']);
});
it('answers 503 when Stripe is not configured', async () => {
const db = makeDb(null, 'CL');
const stripe = fakeStripe({ isAvailable: () => false });
const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, {
returnTo: 'billing',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' });
expect(db.billingSubscription.upsert).not.toHaveBeenCalled();
});
it('still requires the payer email for Mercado Pago', async () => {
const db = makeDb(null, 'AR');
const provider = mpProvider(makeClient());
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
returnTo: 'billing',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 400 });
expect(db.billingSubscription.upsert).not.toHaveBeenCalled();
});
});

View File

@@ -1,11 +1,15 @@
import { describe, expect, it, mock } from 'bun:test'; import { describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import type { MpAuthorizedPayment, PreapprovalClient } from '@/modules/billing/lib';
import { SyncSubscription } from '@/modules/billing/lib/sync'; import { SyncSubscription } from '@/modules/billing/lib/sync';
import type { BillingProvider, ProviderSubscription } from '@/modules/billing/providers';
import {
MercadoPagoBillingProvider,
type MpAuthorizedPayment,
type PreapprovalClient,
} from '@/modules/billing/providers/mercado-pago';
const userId = 'user-1'; const userId = 'user-1';
const now = new Date('2026-10-22T12:00:00.000Z'); const now = new Date('2026-10-22T12:00:00.000Z');
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' }); const credentials = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' });
function subscription(overrides: Record<string, unknown> = {}) { function subscription(overrides: Record<string, unknown> = {}) {
return { return {
@@ -14,7 +18,9 @@ function subscription(overrides: Record<string, unknown> = {}) {
country: 'AR', country: 'AR',
currency: 'ARS', currency: 'ARS',
status: 'PENDING', status: 'PENDING',
mpPreapprovalId: 'pre-1', provider: 'MERCADO_PAGO',
externalId: 'pre-1',
checkoutRef: null,
authorizedAt: null, authorizedAt: null,
paidThrough: null, paidThrough: null,
...overrides, ...overrides,
@@ -62,8 +68,11 @@ function makeClient(params: { status?: string; externalReference?: string | null
} as unknown as PreapprovalClient; } as unknown as PreapprovalClient;
} }
// The real Mercado Pago adapter over a fake preapproval client: the sync and
// the adapter's mapping are tested together.
function sync(db: ReturnType<typeof makeDb>, client: PreapprovalClient) { function sync(db: ReturnType<typeof makeDb>, client: PreapprovalClient) {
return new SyncSubscription({ db: db as never, client, credentials, now: () => now }); const provider = new MercadoPagoBillingProvider({ client, credentials });
return new SyncSubscription({ db: db as never, providers: () => provider, now: () => now });
} }
describe('SyncSubscription', () => { describe('SyncSubscription', () => {
@@ -74,10 +83,10 @@ describe('SyncSubscription', () => {
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } }); expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
expect(db.billingCharge.upsert).toHaveBeenCalledWith({ expect(db.billingCharge.upsert).toHaveBeenCalledWith({
where: { mpAuthorizedPaymentId: 'inv-1' }, where: { externalId: 'inv-1' },
create: { create: {
subscriptionId: 'sub-1', subscriptionId: 'sub-1',
mpAuthorizedPaymentId: 'inv-1', externalId: 'inv-1',
amount: 15000, amount: 15000,
currency: 'ARS', currency: 'ARS',
status: 'approved', status: 'approved',
@@ -88,15 +97,36 @@ describe('SyncSubscription', () => {
expect(db.billingSubscription.update).toHaveBeenCalledWith({ expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' }, where: { id: 'sub-1' },
data: { data: {
externalId: undefined,
status: 'AUTHORIZED', status: 'AUTHORIZED',
authorizedAt: now, authorizedAt: now,
nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'), nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'),
paidThrough: new Date('2026-11-20T10:00:00.000Z'), paidThrough: new Date('2026-11-20T10:00:00.000Z'),
payerEmail: undefined,
lastSyncedAt: now, lastSyncedAt: now,
}, },
}); });
}); });
it('still marks the subscription authorized when listing the charges fails', async () => {
const db = makeDb(subscription());
const client = makeClient({});
(client.searchAuthorizedPayments as ReturnType<typeof mock>).mockImplementation(async () => {
throw new Error('400 Invalid value for limit');
});
const result = await sync(db, client).execute('sub-1');
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
expect(db.billingCharge.upsert).not.toHaveBeenCalled();
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
expect(data.status).toBe('AUTHORIZED');
expect(data.authorizedAt).toEqual(now);
expect(data.paidThrough).toBeNull();
// Without `lastSyncedAt` the next sync retries the charges.
expect(data.lastSyncedAt).toBeUndefined();
});
it('records a rejected charge without extending what was paid', async () => { it('records a rejected charge without extending what was paid', async () => {
const paidThrough = new Date('2026-10-25T00:00:00.000Z'); const paidThrough = new Date('2026-10-25T00:00:00.000Z');
const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough })); const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough }));
@@ -142,11 +172,11 @@ describe('SyncSubscription', () => {
db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never; db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never;
db.billingSubscription.updateMany = mock(async () => ({ count: 1 })); db.billingSubscription.updateMany = mock(async () => ({ count: 1 }));
const result = await sync(db, makeClient({})).byPreapprovalId('AR', 'pre-1'); const result = await sync(db, makeClient({})).byExternalId('MERCADO_PAGO', 'pre-1', 'AR');
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({ expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
where: { userId, country: 'AR', mpPreapprovalId: null }, where: { userId, provider: 'MERCADO_PAGO', externalId: null, country: 'AR' },
data: { mpPreapprovalId: 'pre-1' }, data: { externalId: 'pre-1' },
}); });
expect(result.ok && result.value.synced).toBe(true); expect(result.ok && result.value.synced).toBe(true);
}); });
@@ -154,9 +184,92 @@ describe('SyncSubscription', () => {
it('does not claim a cancelled preapproval (a replaced attempt)', async () => { it('does not claim a cancelled preapproval (a replaced attempt)', async () => {
const db = makeDb(null); const db = makeDb(null);
const result = await sync(db, makeClient({ status: 'cancelled' })).byPreapprovalId('AR', 'old'); const result = await sync(db, makeClient({ status: 'cancelled' })).byExternalId('MERCADO_PAGO', 'old', 'AR');
expect(result).toEqual({ ok: true, value: { synced: false, status: null } }); expect(result).toEqual({ ok: true, value: { synced: false, status: null } });
expect(db.billingSubscription.updateMany).not.toHaveBeenCalled(); expect(db.billingSubscription.updateMany).not.toHaveBeenCalled();
}); });
it('follows the row provider, not the country (a Mercado Pago subscription outside Argentina)', async () => {
const db = makeDb(subscription({ country: 'MX', currency: 'MXN' }));
const resolved: string[] = [];
const provider = new MercadoPagoBillingProvider({ client: makeClient({}), credentials });
await new SyncSubscription({
db: db as never,
providers: (id) => {
resolved.push(id);
return provider;
},
now: () => now,
}).execute('sub-1');
expect(resolved).toEqual(['MERCADO_PAGO']);
});
it('does nothing while the Stripe checkout is not completed', async () => {
const db = makeDb(subscription({ provider: 'STRIPE', externalId: null, checkoutRef: 'cs_1' }));
const provider = fakeProvider(null);
const result = await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute(
'sub-1',
);
expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } });
expect(provider.fetch).toHaveBeenCalledWith({ country: 'AR', externalId: null, checkoutRef: 'cs_1' });
expect(db.billingSubscription.update).not.toHaveBeenCalled();
});
it('stores the Stripe subscription id and payer email once the checkout completes', async () => {
const db = makeDb(subscription({ provider: 'STRIPE', country: 'MX', externalId: null, checkoutRef: 'cs_1' }));
const coveredUntil = new Date('2026-11-21T00:00:00.000Z');
const provider = fakeProvider(
{
externalId: 'sub_stripe',
ownerUserId: userId,
status: 'AUTHORIZED',
nextPaymentDate: coveredUntil,
payerEmail: 'card@mail.com',
},
[
{
externalId: 'in_1',
amount: 199,
currency: 'MXN',
status: 'approved',
paidAt: new Date('2026-10-21T00:00:00.000Z'),
coveredUntil,
},
],
);
await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute('sub-1');
expect(provider.listCharges).toHaveBeenCalledWith({ country: 'MX', externalId: 'sub_stripe', checkoutRef: 'cs_1' });
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: {
externalId: 'sub_stripe',
status: 'AUTHORIZED',
authorizedAt: now,
nextPaymentDate: coveredUntil,
paidThrough: coveredUntil,
payerEmail: 'card@mail.com',
lastSyncedAt: now,
},
});
});
}); });
function fakeProvider(remote: ProviderSubscription | null, charges: Awaited<ReturnType<BillingProvider['listCharges']>> = []) {
return {
id: 'STRIPE',
requiresPayerEmail: false,
isAvailable: () => true,
start: mock(),
fetch: mock(async () => remote),
listCharges: mock(async () => charges),
cancel: mock(),
parseWebhook: mock(),
} satisfies BillingProvider;
}

View File

@@ -4,11 +4,15 @@ import { err, ok } from '@gruperly/shared';
import { billingProviderErrorProblem } from '@/http/problem-builders'; import { billingProviderErrorProblem } from '@/http/problem-builders';
import { isPublicApiRequest } from '@/http/session-auth'; import { isPublicApiRequest } from '@/http/session-auth';
import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case'; import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case';
import type { PreapprovalClient } from '@/modules/billing/lib'; import {
import { verifyMpSignature } from '@/modules/billing/lib/webhook-signature'; MercadoPagoBillingProvider,
type PreapprovalClient,
verifyMpSignature,
} from '@/modules/billing/providers/mercado-pago';
import { StripeBillingProvider } from '@/modules/billing/providers/stripe';
const secret = 'webhook-secret'; const secret = 'webhook-secret';
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: secret }); const credentials = () => ({ accessToken: 'platform-token', webhookSecret: secret });
function sign(dataId: string, requestId: string, ts = '1729600000') { function sign(dataId: string, requestId: string, ts = '1729600000') {
const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex'); const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex');
@@ -18,7 +22,7 @@ function sign(dataId: string, requestId: string, ts = '1729600000') {
function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) { function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) {
const requestId = params.requestId ?? 'req-1'; const requestId = params.requestId ?? 'req-1';
return { return {
country: 'ar', routeParam: 'ar',
rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }), rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }),
headers: new Headers({ headers: new Headers({
'x-request-id': requestId, 'x-request-id': requestId,
@@ -35,7 +39,7 @@ function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const
delete: mock(async () => ({})), delete: mock(async () => ({})),
}, },
}; };
const sync = { byPreapprovalId: mock(async () => syncResult) }; const sync = { byExternalId: mock(async () => syncResult) };
const client = { const client = {
getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })), getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })),
} as unknown as PreapprovalClient; } as unknown as PreapprovalClient;
@@ -43,12 +47,8 @@ function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const
} }
function handler(deps: ReturnType<typeof makeDeps>) { function handler(deps: ReturnType<typeof makeDeps>) {
return new HandleBillingWebhook({ const provider = new MercadoPagoBillingProvider({ client: deps.client, credentials });
db: deps.db as never, return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider });
sync: deps.sync as never,
client: deps.client,
credentials,
});
} }
describe('verifyMpSignature', () => { describe('verifyMpSignature', () => {
@@ -69,31 +69,32 @@ describe('HandleBillingWebhook', () => {
const deps = makeDeps(); const deps = makeDeps();
const result = await handler(deps).execute( const result = await handler(deps).execute(
'MERCADO_PAGO',
request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }), request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }),
); );
expect(result).toEqual(err('invalid_signature')); expect(result).toEqual(err('invalid_signature'));
expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled(); expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled();
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); expect(deps.sync.byExternalId).not.toHaveBeenCalled();
}); });
it('re-fetches the preapproval instead of trusting the body', async () => { it('re-fetches the preapproval instead of trusting the body', async () => {
const deps = makeDeps(); const deps = makeDeps();
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
expect(result).toEqual(ok({ duplicate: false, applied: true })); expect(result).toEqual(ok({ duplicate: false, applied: true }));
expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-1'); expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-1', 'AR');
expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { country: 'AR', dedupeKey: 'req-1' } }); expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'mp:AR', dedupeKey: 'req-1' } });
}); });
it('resolves an invoice notification to its subscription', async () => { it('resolves an invoice notification to its subscription', async () => {
const deps = makeDeps(); const deps = makeDeps();
await handler(deps).execute(request({ type: 'subscription_authorized_payment', dataId: 'inv-1' })); await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_authorized_payment', dataId: 'inv-1' }));
expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1'); expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1');
expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-9'); expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-9', 'AR');
}); });
it('answers a repeated delivery as a duplicate', async () => { it('answers a repeated delivery as a duplicate', async () => {
@@ -102,35 +103,121 @@ describe('HandleBillingWebhook', () => {
throw Object.assign(new Error('unique'), { code: 'P2002' }); throw Object.assign(new Error('unique'), { code: 'P2002' });
}); });
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
expect(result).toEqual(ok({ duplicate: true, applied: false })); expect(result).toEqual(ok({ duplicate: true, applied: false }));
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); expect(deps.sync.byExternalId).not.toHaveBeenCalled();
}); });
it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => { it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => {
const deps = makeDeps(err(billingProviderErrorProblem()) as never); const deps = makeDeps(err(billingProviderErrorProblem()) as never);
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' })); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
expect(result).toEqual(err('sync_failed')); expect(result).toEqual(err('sync_failed'));
expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({ expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({
where: { country_dedupeKey: { country: 'AR', dedupeKey: 'req-1' } }, where: { source_dedupeKey: { source: 'mp:AR', dedupeKey: 'req-1' } },
}); });
}); });
it('acknowledges topics it does not handle', async () => { it('acknowledges topics it does not handle', async () => {
const deps = makeDeps(); const deps = makeDeps();
const result = await handler(deps).execute(request({ type: 'payment', dataId: '123' })); const result = await handler(deps).execute('MERCADO_PAGO', request({ type: 'payment', dataId: '123' }));
expect(result).toEqual(ok({ duplicate: false, applied: false })); expect(result).toEqual(ok({ duplicate: false, applied: false }));
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled(); expect(deps.sync.byExternalId).not.toHaveBeenCalled();
}); });
it('is reachable without a session, and only that path', () => { it('is reachable without a session, and only that path', () => {
expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true); expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/stripe')).toBe(true);
expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/stripe')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false); expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false); expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false);
}); });
}); });
const stripeSecret = 'whsec_test';
const stripeNow = new Date('2026-10-22T12:00:00.000Z');
function stripeRequest(event: Record<string, unknown>, signature?: string) {
const rawBody = JSON.stringify(event);
const t = Math.floor(stripeNow.getTime() / 1000);
const v1 = createHmac('sha256', stripeSecret).update(`${t}.${rawBody}`).digest('hex');
return {
routeParam: null,
rawBody,
headers: new Headers({ 'stripe-signature': signature ?? `t=${t},v1=${v1}` }),
query: new URLSearchParams(),
};
}
function stripeHandler(deps: ReturnType<typeof makeDeps>) {
const provider = new StripeBillingProvider({
config: () => ({ secretKey: 'sk_test', webhookSecret: stripeSecret }),
fetch: mock(async () => {
throw new Error('the webhook must not call Stripe');
}) as never,
now: () => stripeNow,
});
return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider });
}
describe('HandleBillingWebhook with Stripe', () => {
it('syncs the subscription of a completed checkout, deduplicated by event id', async () => {
const deps = makeDeps();
const result = await stripeHandler(deps).execute(
'STRIPE',
stripeRequest({
id: 'evt_1',
type: 'checkout.session.completed',
data: { object: { id: 'cs_1', mode: 'subscription', subscription: 'sub_1' } },
}),
);
expect(result).toEqual(ok({ duplicate: false, applied: true }));
expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'stripe', dedupeKey: 'evt_1' } });
expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_1', null);
});
it('finds the subscription of an invoice event', async () => {
const deps = makeDeps();
await stripeHandler(deps).execute(
'STRIPE',
stripeRequest({
id: 'evt_2',
type: 'invoice.paid',
data: { object: { id: 'in_1', parent: { subscription_details: { subscription: 'sub_2' } } } },
}),
);
expect(deps.sync.byExternalId).toHaveBeenCalledWith('STRIPE', 'sub_2', null);
});
it('rejects a bad signature', async () => {
const deps = makeDeps();
const result = await stripeHandler(deps).execute(
'STRIPE',
stripeRequest({ id: 'evt_3', type: 'invoice.paid', data: { object: {} } }, 't=1,v1=deadbeef'),
);
expect(result).toEqual(err('invalid_signature'));
expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled();
});
it('acknowledges events that do not concern a subscription', async () => {
const deps = makeDeps();
const result = await stripeHandler(deps).execute(
'STRIPE',
stripeRequest({ id: 'evt_4', type: 'customer.created', data: { object: { id: 'cus_1' } } }),
);
expect(result).toEqual(ok({ duplicate: false, applied: false }));
expect(deps.sync.byExternalId).not.toHaveBeenCalled();
});
});

View File

@@ -5,7 +5,7 @@ import { ArrowLeft, Loader2 } from 'lucide-react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Badge, Button } from '../../components/ui' import { Badge, Button } from '../../components/ui'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { formatBillingDate, formatUsage, subscriptionStatusLabel } from '../billing' import { BILLING_PROVIDER_NAMES, formatBillingDate, formatUsage, subscriptionStatusLabel } from '../billing'
import { useAdminAccountDetail } from './AdminAccountDetailProvider' import { useAdminAccountDetail } from './AdminAccountDetailProvider'
import { import {
countryLabel, countryLabel,
@@ -85,6 +85,7 @@ function AccountDetail({ account }: { account: AdminAccountDetail }) {
</Field> </Field>
{subscription ? ( {subscription ? (
<> <>
<Field label="Cobra">{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
<Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field> <Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field>
<Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field> <Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
<Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field> <Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>

View File

@@ -3,6 +3,7 @@ import { Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { useBilling } from './BillingProvider' import { useBilling } from './BillingProvider'
import { import {
BILLING_PROVIDER_NAMES,
formatBillingDate, formatBillingDate,
formatUsage, formatUsage,
PLAN_NAMES, PLAN_NAMES,
@@ -45,7 +46,7 @@ export function PlanSummaryCard() {
) : null} ) : null}
{status.status === 'PENDING' ? ( {status.status === 'PENDING' ? (
<p className="mt-0.5 text-xs text-foreground/50"> <p className="mt-0.5 text-xs text-foreground/50">
Estamos esperando que Mercado Pago confirme tu suscripción. Estamos esperando que {BILLING_PROVIDER_NAMES[status.provider]} confirme tu suscripción.
</p> </p>
) : null} ) : null}
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? ( {status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (

View File

@@ -1,38 +1,46 @@
import type { BillingProviderId } from '@gruperly/shared'
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
import { type FormEvent, useState } from 'react' import { type FormEvent, useState } from 'react'
import { Button, Input, Label } from '../../components/ui' import { Button, Input, Label } from '../../components/ui'
import { BILLING_PROVIDER_NAMES } from './copy'
type SubscribeFormProps = { type SubscribeFormProps = {
provider: BillingProviderId
defaultEmail: string defaultEmail: string
isPending: boolean isPending: boolean
error: string | null error: string | null
submitLabel?: string submitLabel?: string
onSubmit: (payerEmail: string) => void /** `undefined` cuando el proveedor no necesita el email (Stripe lo pide en su checkout). */
onSubmit: (payerEmail: string | undefined) => void
onCancel?: () => void onCancel?: () => void
} }
/** /**
* El email de la cuenta de Mercado Pago que paga. Mercado Pago exige que el * Antes de ir a pagar Pro. Con Mercado Pago pide el email de la cuenta que
* profesor inicie sesión con ese mismo email, por eso se pide en vez de asumir * paga: Mercado Pago exige que el profesor inicie sesión con ese mismo email,
* el de Gruperly (que viene precargado). * por eso no se asume el de Gruperly (que viene precargado). Con Stripe no hay
* nada que completar: el email y la tarjeta se cargan en su checkout.
*/ */
export function SubscribeForm({ export function SubscribeForm({
provider,
defaultEmail, defaultEmail,
isPending, isPending,
error, error,
submitLabel = 'Ir a Mercado Pago', submitLabel = `Ir a ${BILLING_PROVIDER_NAMES[provider]}`,
onSubmit, onSubmit,
onCancel, onCancel,
}: SubscribeFormProps) { }: SubscribeFormProps) {
const [email, setEmail] = useState(defaultEmail) const [email, setEmail] = useState(defaultEmail)
const asksEmail = provider === 'MERCADO_PAGO'
const handleSubmit = (event: FormEvent) => { const handleSubmit = (event: FormEvent) => {
event.preventDefault() event.preventDefault()
onSubmit(email.trim()) onSubmit(asksEmail ? email.trim() : undefined)
} }
return ( return (
<form className="space-y-4" onSubmit={handleSubmit}> <form className="space-y-4" onSubmit={handleSubmit}>
{asksEmail ? (
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label htmlFor="payer-email">Email de tu cuenta de Mercado Pago</Label> <Label htmlFor="payer-email">Email de tu cuenta de Mercado Pago</Label>
<Input <Input
@@ -48,6 +56,7 @@ export function SubscribeForm({
Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual. Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual.
</p> </p>
</div> </div>
) : null}
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null} {error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
@@ -57,7 +66,7 @@ export function SubscribeForm({
Cancelar Cancelar
</Button> </Button>
) : null} ) : null}
<Button type="submit" variant="primary" disabled={isPending || !email.trim()}> <Button type="submit" variant="primary" disabled={isPending || (asksEmail && !email.trim())}>
{isPending ? <Loader2 className="size-4 animate-spin" /> : null} {isPending ? <Loader2 className="size-4 animate-spin" /> : null}
{isPending ? 'Abriendo…' : submitLabel} {isPending ? 'Abriendo…' : submitLabel}
</Button> </Button>

View File

@@ -1,6 +1,7 @@
import { Modal } from '../../components/ui' import { Modal } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider' import { useAuth } from '../../context/AuthProvider'
import { useBilling } from './BillingProvider' import { useBilling } from './BillingProvider'
import { subscribeDescription } from './copy'
import { SubscribeForm } from './SubscribeForm' import { SubscribeForm } from './SubscribeForm'
import { useStartSubscription } from './useStartSubscription' import { useStartSubscription } from './useStartSubscription'
@@ -8,18 +9,20 @@ export function SubscribeModal() {
const { user } = useAuth() const { user } = useAuth()
const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling() const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling()
const subscription = useStartSubscription() const subscription = useStartSubscription()
const provider = statusQuery.data?.provider ?? 'MERCADO_PAGO'
return ( return (
<Modal <Modal
isOpen={isSubscribeOpen} isOpen={isSubscribeOpen}
onClose={closeSubscribe} onClose={closeSubscribe}
title="Pasate a Pro" title="Pasate a Pro"
description="Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras." description={subscribeDescription(provider)}
maxWidth="sm" maxWidth="sm"
> >
{/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */} {/* Se monta solo con el modal abierto, así el autoFocus del email funciona cada vez. */}
{isSubscribeOpen ? ( {isSubscribeOpen ? (
<SubscribeForm <SubscribeForm
provider={provider}
defaultEmail={statusQuery.data?.payerEmail ?? user?.email ?? ''} defaultEmail={statusQuery.data?.payerEmail ?? user?.email ?? ''}
isPending={subscription.isStarting} isPending={subscription.isStarting}
error={subscription.error} error={subscription.error}

View File

@@ -1,4 +1,11 @@
import type { BillingStatusDto, Plan, PlanFeature, PlanLimits, SubscriptionStatus } from '@gruperly/shared' import type {
BillingProviderId,
BillingStatusDto,
Plan,
PlanFeature,
PlanLimits,
SubscriptionStatus,
} from '@gruperly/shared'
import type { BadgeVariant } from '../../components/ui' import type { BadgeVariant } from '../../components/ui'
/* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el /* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el
@@ -8,7 +15,21 @@ import type { BadgeVariant } from '../../components/ui'
export const PLAN_NAMES: Record<Plan, string> = { FREE: 'Free', PRO: 'Pro' } export const PLAN_NAMES: Record<Plan, string> = { FREE: 'Free', PRO: 'Pro' }
export const SUBSCRIBE_ERROR_MESSAGE = export const SUBSCRIBE_ERROR_MESSAGE =
'No pudimos abrir Mercado Pago. Revisá tu conexión e intentá de nuevo.' 'No pudimos abrir la página de pago. Revisá tu conexión e intentá de nuevo.'
/* Quién cobra Pro: Mercado Pago en Argentina, Stripe en el resto. Es solo la
suscripción a Gruperly; los cobros a alumnos siguen siendo con Mercado Pago. */
export const BILLING_PROVIDER_NAMES: Record<BillingProviderId, string> = {
MERCADO_PAGO: 'Mercado Pago',
STRIPE: 'Stripe',
}
/** Qué pasa al tocar "Pasar a Pro", según quién cobra. */
export function subscribeDescription(provider: BillingProviderId): string {
return provider === 'STRIPE'
? 'Te llevamos a Stripe para cargar tu tarjeta. El cobro es mensual y podés cancelarlo cuando quieras.'
: 'Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras.'
}
/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */ /** Lo que incluye cada plan, como lista para las tarjetas de comparación. */
export function planFeatureList(limits: PlanLimits): { label: string; included: boolean }[] { export function planFeatureList(limits: PlanLimits): { label: string; included: boolean }[] {
@@ -113,7 +134,7 @@ export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' |
text: text:
status.status === 'CANCELLED' status.status === 'CANCELLED'
? `Cancelaste Pro: lo seguís teniendo hasta el ${graceUntil}.` ? `Cancelaste Pro: lo seguís teniendo hasta el ${graceUntil}.`
: `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en Mercado Pago antes del ${graceUntil}.`, : `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en ${BILLING_PROVIDER_NAMES[status.provider]} antes del ${graceUntil}.`,
} }
} }
return null return null

View File

@@ -1,4 +1,5 @@
export { export {
BILLING_PROVIDER_NAMES,
formatBillingDate, formatBillingDate,
formatUsage, formatUsage,
hasPlanFeature, hasPlanFeature,
@@ -7,6 +8,7 @@ export {
PLAN_NAMES, PLAN_NAMES,
planFeatureList, planFeatureList,
planNoticeMessage, planNoticeMessage,
subscribeDescription,
subscriptionStatusLabel, subscriptionStatusLabel,
} from './copy' } from './copy'
export { dismissPlanPrompt, showPlanPrompt, usePlanPrompt } from './plan-prompt' export { dismissPlanPrompt, showPlanPrompt, usePlanPrompt } from './plan-prompt'

View File

@@ -5,14 +5,14 @@ import { SUBSCRIBE_ERROR_MESSAGE } from './copy'
/** /**
* Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se * Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se
* resuelve con `fetch`: el navegador navega a Mercado Pago para que el profesor * resuelve con `fetch`: el navegador navega al checkout del proveedor (Mercado
* autorice el débito, y Mercado Pago lo devuelve con `?sub=return`. * Pago o Stripe) para que el profesor autorice el cobro, y vuelve con `?sub=return`.
*/ */
export function useStartSubscription() { export function useStartSubscription() {
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [isStarting, setIsStarting] = useState(false) const [isStarting, setIsStarting] = useState(false)
const start = async (payerEmail: string, returnTo: BillingReturnTo = 'billing') => { const start = async (payerEmail: string | undefined, returnTo: BillingReturnTo = 'billing') => {
setError(null) setError(null)
setIsStarting(true) setIsStarting(true)
try { try {

View File

@@ -1,5 +1,5 @@
import type { SelectPlanInput } from '@gruperly/shared' import type { SelectPlanInput } from '@gruperly/shared'
import { COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared' import { billingProviderForCountry, COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'
import { useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react' import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react'
import { type ReactNode, useEffect, useState } from 'react' import { type ReactNode, useEffect, useState } from 'react'
@@ -8,6 +8,7 @@ import { useAuth } from '../../context/AuthProvider'
import { ApiError, selectPlan } from '../../lib/api' import { ApiError, selectPlan } from '../../lib/api'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { import {
BILLING_PROVIDER_NAMES,
PlanOptionCard, PlanOptionCard,
SubscribeForm, SubscribeForm,
useBillingStatus, useBillingStatus,
@@ -19,15 +20,16 @@ const SELECT_PLAN_ERROR_MESSAGE = 'No pudimos guardar tu plan. Revisá tu conexi
/** /**
* Paso "Plan" del onboarding (obligatorio). Free sigue directo al primer grupo * Paso "Plan" del onboarding (obligatorio). Free sigue directo al primer grupo
* (sin Cobros ni WhatsApp, que son de Pro). Pro lleva a Mercado Pago a * (sin Cobros ni WhatsApp, que son de Pro). Pro lleva al checkout del
* autorizar el débito y vuelve acá con `?sub=return`; mientras Mercado Pago * proveedor del país (Mercado Pago en Argentina, Stripe en el resto) y vuelve
* confirma se puede seguir igual. * acá con `?sub=return`; mientras el proveedor confirma se puede seguir igual.
*/ */
export function PlanStep() { export function PlanStep() {
const { user } = useAuth() const { user } = useAuth()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const { country, selectedPlan, setSelectedPlan, returnedFromSubscription, goTo, goBack, statusQuery } = const { country, selectedPlan, setSelectedPlan, returnedFromSubscription, goTo, goBack, statusQuery } =
useOnboarding() useOnboarding()
// Con Mercado Pago, el paso intermedio de pedir el email; con Stripe, el de confirmar.
const [isEnteringEmail, setIsEnteringEmail] = useState(false) const [isEnteringEmail, setIsEnteringEmail] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [proUnavailable, setProUnavailable] = useState(false) const [proUnavailable, setProUnavailable] = useState(false)
@@ -42,6 +44,8 @@ export function PlanStep() {
if (returnedFromSubscription) polling.startPolling() if (returnedFromSubscription) polling.startPolling()
}, [returnedFromSubscription, polling.startPolling]) }, [returnedFromSubscription, polling.startPolling])
const provider = billingProviderForCountry(country)
const providerName = BILLING_PROVIDER_NAMES[provider]
const subscriptionStatus = billingQuery.data?.status ?? statusQuery.data?.subscriptionStatus ?? null const subscriptionStatus = billingQuery.data?.status ?? statusQuery.data?.subscriptionStatus ?? null
const mutation = useMutation({ const mutation = useMutation({
@@ -71,7 +75,7 @@ export function PlanStep() {
setError(null) setError(null)
mutation.mutate({ plan: 'FREE', country }) mutation.mutate({ plan: 'FREE', country })
} }
const choosePro = (payerEmail: string) => { const choosePro = (payerEmail: string | undefined) => {
setError(null) setError(null)
mutation.mutate({ plan: 'PRO', country, payerEmail }) mutation.mutate({ plan: 'PRO', country, payerEmail })
} }
@@ -109,8 +113,8 @@ export function PlanStep() {
</p> </p>
<p className="text-xs text-foreground/50"> <p className="text-xs text-foreground/50">
{returnedFromSubscription {returnedFromSubscription
? 'Mercado Pago puede tardar unos minutos en confirmarlo. Podés seguir mientras tanto: te avisamos cuando quede activa.' ? `${providerName} puede tardar unos minutos en confirmarlo. Podés seguir mientras tanto: te avisamos cuando quede activa.`
: 'No terminaste de autorizar el débito en Mercado Pago. Podés reintentarlo o seguir con Free.'} : `No terminaste de autorizar el pago en ${providerName}. Podés reintentarlo o seguir con Free.`}
</p> </p>
</div> </div>
</div> </div>
@@ -156,6 +160,7 @@ export function PlanStep() {
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p> <p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
) : isEnteringEmail ? ( ) : isEnteringEmail ? (
<SubscribeForm <SubscribeForm
provider={provider}
defaultEmail={user?.email ?? ''} defaultEmail={user?.email ?? ''}
isPending={isLeavingToMp} isPending={isLeavingToMp}
error={null} error={null}

View File

@@ -1,6 +1,6 @@
# Plan de Gruperly: Free y Pro con Suscripciones de Mercado Pago # Plan de Gruperly: Free y Pro con Mercado Pago y Stripe
Gruperly le cobra **al profesor** una suscripción mensual a **Pro** con débito automático (Suscripciones de Mercado Pago, `/preapproval`). No tiene nada que ver con `payments`, que es lo que los **alumnos** le pagan al profesor con su propia cuenta de MP vinculada por OAuth. Gruperly le cobra **al profesor** una suscripción mensual a **Pro** con débito automático: con **Suscripciones de Mercado Pago** (`/preapproval`) en Argentina y con **Stripe** en el resto de los países. No tiene nada que ver con `payments`, que es lo que los **alumnos** le pagan al profesor con su propia cuenta de MP vinculada por OAuth (eso sigue siendo Mercado Pago en todos los países).
| | **Free** | **Pro** | | | **Free** | **Pro** |
| --- | --- | --- | | --- | --- | --- |
@@ -9,7 +9,20 @@ Gruperly le cobra **al profesor** una suscripción mensual a **Pro** con débito
| Cobros a alumnos con Mercado Pago | No | Sí | | Cobros a alumnos con Mercado Pago | No | Sí |
| Mensajes automáticos por WhatsApp | No | Sí | | Mensajes automáticos por WhatsApp | No | Sí |
Los límites y los precios por país viven en `packages/shared/src/schemas/billing.ts` (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`). No hay trial. Los límites, los precios por país y quién cobra en cada uno viven en `packages/shared/src/schemas/billing.ts` (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`, `BILLING_PROVIDER_BY_COUNTRY`). No hay trial.
## Proveedores
| País | Proveedor | Cuenta de Gruperly |
| --- | --- | --- |
| AR | Mercado Pago | Una cuenta de MP en Argentina |
| BR, CL, CO, MX, PE, UY | Stripe | Una sola cuenta, cobra en la moneda local (BRL, CLP, COP, MXN, PEN, UYU) |
El código no sabe qué proveedor hay detrás: los use-cases, la sync, el webhook y el job hablan con el puerto `BillingProvider` (`apps/backend/src/modules/billing/providers/billing-provider.ts`), y lo específico de cada uno vive en `providers/mercado-pago/` y `providers/stripe/`. `getBillingProvider(id)` es el único lugar que elige el adaptador.
- El país decide el proveedor **solo de una suscripción nueva**. Una fila existente guarda su `provider` y siempre se sincroniza y cancela con él, aunque el mapa cambie.
- Cambiar un país de proveedor es editar `BILLING_PROVIDER_BY_COUNTRY`. Sumar un proveedor es un `providers/<nombre>/` que implemente el puerto, más un `case` en `getBillingProvider`.
- Los cobros (`billing_charges.status`) se guardan normalizados: `approved`, `pending` o `rejected`.
## Reglas ## Reglas
@@ -20,30 +33,51 @@ Los límites y los precios por país viven en `packages/shared/src/schemas/billi
- `BILLING_ENFORCEMENT=on` aplica los límites. Con cualquier otro valor, o sin la variable, todos funcionan como Pro y los guards no tocan la base. Sirve para desplegar sin pasar a solo lectura de golpe a los profesores actuales. - `BILLING_ENFORCEMENT=on` aplica los límites. Con cualquier otro valor, o sin la variable, todos funcionan como Pro y los guards no tocan la base. Sirve para desplegar sin pasar a solo lectura de golpe a los profesores actuales.
- **Onboarding**: el paso **Plan** (después de País) es obligatorio. `POST /onboarding/first-group` responde `409 plan_not_selected` si falta `users.plan_selected_at`. Con Free se saltean los pasos Cobros y WhatsApp. - **Onboarding**: el paso **Plan** (después de País) es obligatorio. `POST /onboarding/first-group` responde `409 plan_not_selected` si falta `users.plan_selected_at`. Con Free se saltean los pasos Cobros y WhatsApp.
## Cuentas de Mercado Pago (una por país) ## Cuenta de Mercado Pago (Argentina)
MP no cobra entre países, así que Gruperly necesita **su propia cuenta en cada país** donde vende Pro. Por cada país: MP no cobra entre países, así que cada país con MP necesita **su propia cuenta de Gruperly**. Hoy es solo Argentina (el código acepta cualquier `CC` si algún día se vuelve a usar MP en otro país):
1. Crear la cuenta de MP de Gruperly y una aplicación en el [panel de desarrolladores](https://www.mercadopago.com/developers/panel/app). 1. Crear la cuenta de MP de Gruperly y una aplicación en el [panel de desarrolladores](https://www.mercadopago.com/developers/panel/app).
2. Copiar el **Access Token de producción** en `MP_PLATFORM_ACCESS_TOKEN_<CC>`, donde `CC` es `AR`, `BR`, `CL`, `CO`, `MX`, `PE` o `UY`. 2. Copiar el **Access Token de producción** en `MP_PLATFORM_ACCESS_TOKEN_AR`.
3. En **Webhooks**, configurar la URL `https://<API>/api/v1/billing/webhooks/mp/<cc>` (país en minúscula) con los eventos **Planes y suscripciones** (`subscription_preapproval` y `subscription_authorized_payment`). Copiar la **clave secreta** en `MP_PLATFORM_WEBHOOK_SECRET_<CC>`. 3. En **Webhooks**, configurar la URL `https://<API>/api/v1/billing/webhooks/mp/ar` con los eventos **Planes y suscripciones** (`subscription_preapproval` y `subscription_authorized_payment`). Copiar la **clave secreta** en `MP_PLATFORM_WEBHOOK_SECRET_AR`.
Un país sin las dos variables ofrece Pro como "no disponible" (`503 billing_not_available`). Free funciona igual. Estas son credenciales de **Gruperly**, no las del OAuth del profesor (`getMpAccessToken`). Nunca se loguean. Estas son credenciales de **Gruperly**, no las del OAuth del profesor (`getMpAccessToken`). Nunca se loguean.
## Cuenta de Stripe (resto de los países)
Una sola cuenta de Stripe cobra en todos los países que no usan MP, cada uno en su moneda (el precio va inline en la Checkout Session, así que no hay Products ni Prices que mantener en el Dashboard).
1. Copiar la **Secret key** en `STRIPE_SECRET_KEY`.
2. En **Developers → Webhooks**, crear el endpoint `https://<API>/api/v1/billing/webhooks/stripe` con los eventos `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` e `invoice.payment_failed`. Copiar el **Signing secret** (`whsec_…`) en `STRIPE_WEBHOOK_SECRET`.
3. Habilitar los medios de pago (tarjetas) y revisar que la cuenta pueda cobrar en BRL, CLP, COP, MXN, PEN y UYU.
La API se llama con `fetch` plano y la versión fija `STRIPE_API_VERSION` (`providers/stripe/stripe-http.ts`). Nunca se loguean la clave, los cuerpos ni los mensajes de error de Stripe (pueden repetir el email).
Un país cuyo proveedor no tiene credenciales ofrece Pro como "no disponible" (`503 billing_not_available`). Free funciona igual.
## Flujo ## Flujo
1. `POST /billing/subscribe` (o `POST /onboarding/plan` con `PRO`) crea la fila `billing_subscriptions` en `PENDING` **antes** de llamar a MP. Después crea el preapproval (`external_reference` = id del usuario, `payer_email` el que puso el profesor) y devuelve `{ checkoutUrl }`. El navegador navega ahí. 1. `POST /billing/subscribe` (o `POST /onboarding/plan` con `PRO`) crea la fila `billing_subscriptions` en `PENDING`, con el `provider` del país, **antes** de llamar al proveedor. Después:
2. El profesor inicia sesión en MP **con ese mismo email** (MP lo exige) y autoriza. MP lo devuelve a `/billing?sub=return` o a `/onboarding?sub=return`. - **Mercado Pago**: crea el preapproval (`external_reference` = id del usuario, `payer_email` el que puso el profesor, obligatorio) y guarda su id en `external_id`.
3. El estado se sincroniza por tres caminos, todos con `SyncSubscription`, que es idempotente: - **Stripe**: crea una Checkout Session en modo suscripción (`client_reference_id` y `subscription_data.metadata.gruperly_user_id` = id del usuario) y guarda su id en `checkout_ref`. No se pide email: lo carga el profesor en el checkout. La suscripción de Stripe recién existe cuando completa el pago; ahí la sync guarda su id en `external_id` y el email real en `payer_email`.
- el **webhook** verifica `x-signature` (HMAC-SHA256 de `id:<data.id>;request-id:<x-request-id>;ts:<ts>;`), deduplica en `billing_webhook_events` y **no confía en el body**: vuelve a pedirle a MP el preapproval y sus `authorized_payments`;
- `GET /billing/status` reconsulta a MP si la suscripción sigue `PENDING`, como mucho cada 30 s. Es lo que actualiza la pantalla al volver de MP;
- el job `ReconcileSubscriptions` (`*/30 * * * *` UTC) procesa las `PENDING` y las `AUTHORIZED` que llevan más de 24 h sin sincronizar, y da por `CANCELLED` las `PENDING` con más de 7 días.
4. Cada `authorized_payment` aprobado queda en `billing_charges` y extiende `paid_through` un mes desde el débito. `paid_through` nunca retrocede.
Volver a suscribirse cancela en MP el intento `PENDING` anterior, así se puede corregir el email. Si todavía hay un período pago, el primer débito se agenda para cuando termine (`start_date`). Devuelve `{ checkoutUrl }` y el navegador navega ahí.
2. El profesor autoriza (en MP, **con el mismo email**; en Stripe, cargando la tarjeta) y vuelve a `/billing?sub=return` o a `/onboarding?sub=return`.
3. El estado se sincroniza por tres caminos, todos con `SyncSubscription`, que es idempotente y **no confía en el body** de ninguna notificación: le vuelve a pedir al proveedor la suscripción y sus facturas, y chequea que sea del usuario.
- el **webhook**: MP verifica `x-signature` (HMAC-SHA256 de `id:<data.id>;request-id:<x-request-id>;ts:<ts>;`); Stripe verifica `Stripe-Signature` (HMAC-SHA256 de `<t>.<body>`, tolerancia 5 min). Se deduplica en `billing_webhook_events` por `(source, dedupe_key)` (`mp:<CC>` + `x-request-id`, o `stripe` + id del evento);
- `GET /billing/status` reconsulta al proveedor si la suscripción sigue `PENDING`, como mucho cada 30 s. Es lo que actualiza la pantalla al volver del checkout;
- el job `ReconcileSubscriptions` (`*/30 * * * *` UTC) procesa las `PENDING` y las `AUTHORIZED` que llevan más de 24 h sin sincronizar, y da por `CANCELLED` las `PENDING` con más de 7 días.
4. Cada cobro aprobado queda en `billing_charges` y extiende `paid_through` hasta lo que cubre: un mes desde el débito en MP, el fin del período de la factura en Stripe. `paid_through` nunca retrocede.
Estados: en Stripe, `past_due` (reintentando el cobro) cuenta como `AUTHORIZED` y la gracia la da `paid_through`; `unpaid`/`paused` son `PAUSED`; `canceled`/`incomplete_expired`, `CANCELLED`.
Volver a suscribirse anula el intento `PENDING` anterior con su propio proveedor (cancela el preapproval o expira la Checkout Session), así se puede corregir el email. Si todavía hay un período pago, el primer cobro se agenda para cuando termine (`start_date` en MP, `trial_end` en Stripe; Stripe exige que esté al menos 48 h adelante, si no se cobra en el momento).
Cancelar (`POST /billing/cancel`) cancela en el proveedor en el acto; Pro sigue hasta `paid_through` más la gracia.
## Desarrollo local ## Desarrollo local
- El webhook necesita una URL pública: el mismo túnel de ngrok de `MP_REDIRECT_URI` sirve (`https://TU-DOMINIO.ngrok-free.app/api/v1/billing/webhooks/mp/ar`). Sin webhook todo funciona igual, porque el status sincroniza al leer. - El webhook de MP necesita una URL pública: el mismo túnel de ngrok de `MP_REDIRECT_URI` sirve (`https://TU-DOMINIO.ngrok-free.app/api/v1/billing/webhooks/mp/ar`). Sin webhook todo funciona igual, porque el status sincroniza al leer.
- Para probar sin plata real, usar **usuarios de prueba** de MP del mismo país (un vendedor de test cuyo token va en `MP_PLATFORM_ACCESS_TOKEN_AR` y un comprador de test para pagar). - Para probar MP sin plata real, usar **usuarios de prueba** de MP de Argentina (un vendedor de test cuyo token va en `MP_PLATFORM_ACCESS_TOKEN_AR` y un comprador de test para pagar).
- Para Stripe, usar las claves de **test mode** (`sk_test_…`) y la CLI: `stripe listen --forward-to localhost:4000/api/v1/billing/webhooks/stripe` imprime el `whsec_…` para `STRIPE_WEBHOOK_SECRET`. Tarjetas de prueba: `4242 4242 4242 4242` (aprobada) y `4000 0000 0000 0341` (se vincula pero rechaza los cobros, para probar la gracia). El profesor tiene que tener un país distinto de AR.
- Para simular un vencimiento, poner `paid_through` en el pasado en `billing_subscriptions`. Con `BILLING_ENFORCEMENT=on` y más uso que el permitido por Free, aparece el aviso de solo lectura. - Para simular un vencimiento, poner `paid_through` en el pasado en `billing_subscriptions`. Con `BILLING_ENFORCEMENT=on` y más uso que el permitido por Free, aparece el aviso de solo lectura.

View File

@@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { BillingChargeDtoSchema, planSchema, subscriptionStatusSchema } from './billing.js'; import { BillingChargeDtoSchema, billingProviderIdSchema, planSchema, subscriptionStatusSchema } from './billing.js';
import { countryCodeSchema } from './country.js'; import { countryCodeSchema } from './country.js';
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
@@ -32,6 +32,7 @@ export type AdminAccountQuery = z.output<typeof AdminAccountQuerySchema>;
export type AdminAccountQueryInput = z.input<typeof AdminAccountQuerySchema>; export type AdminAccountQueryInput = z.input<typeof AdminAccountQuerySchema>;
const AdminSubscriptionSummarySchema = z.object({ const AdminSubscriptionSummarySchema = z.object({
provider: billingProviderIdSchema,
status: subscriptionStatusSchema, status: subscriptionStatusSchema,
amount: z.number(), amount: z.number(),
currency: z.string(), currency: z.string(),

View File

@@ -25,9 +25,8 @@ export const PLAN_LIMITS: Record<Plan, PlanLimits> = {
PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true }, PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true },
}; };
// Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY). // Monthly price of Pro, in the currency of each country (COUNTRY_CURRENCY),
// Mercado Pago does not charge across countries, so each one is collected by // whichever provider collects it.
// Gruperly's own account in that country.
export const PRO_PRICE_BY_COUNTRY: Record<CountryCode, number> = { export const PRO_PRICE_BY_COUNTRY: Record<CountryCode, number> = {
AR: 15000, AR: 15000,
BR: 49, BR: 49,
@@ -38,7 +37,28 @@ export const PRO_PRICE_BY_COUNTRY: Record<CountryCode, number> = {
UY: 390, UY: 390,
}; };
// Mirror of the Mercado Pago preapproval status. // Who collects Pro. Argentina stays on Mercado Pago (Gruperly's own account
// there); every other country is collected by Gruperly's single Stripe account,
// in the country's currency. Only decides *new* subscriptions: a live one keeps
// the provider it was created with.
export const billingProviderIdSchema = z.enum(['MERCADO_PAGO', 'STRIPE']);
export type BillingProviderId = z.output<typeof billingProviderIdSchema>;
export const BILLING_PROVIDER_BY_COUNTRY: Record<CountryCode, BillingProviderId> = {
AR: 'MERCADO_PAGO',
BR: 'STRIPE',
CL: 'STRIPE',
CO: 'STRIPE',
MX: 'STRIPE',
PE: 'STRIPE',
UY: 'STRIPE',
};
export function billingProviderForCountry(country: CountryCode): BillingProviderId {
return BILLING_PROVIDER_BY_COUNTRY[country];
}
// Subscription status, normalized across providers.
export const subscriptionStatusSchema = z.enum(['PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED']); export const subscriptionStatusSchema = z.enum(['PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED']);
export type SubscriptionStatus = z.output<typeof subscriptionStatusSchema>; export type SubscriptionStatus = z.output<typeof subscriptionStatusSchema>;
@@ -67,7 +87,9 @@ export const BillingStatusDtoSchema = z.object({
priceAmount: z.number(), priceAmount: z.number(),
currency: z.string(), currency: z.string(),
country: countryCodeSchema, country: countryCodeSchema,
/** Gruperly has Mercado Pago credentials for the professor's country. */ /** Who collects (or would collect) the subscription. */
provider: billingProviderIdSchema,
/** That provider is configured for the professor's country. */
availableInCountry: z.boolean(), availableInCountry: z.boolean(),
/** `false` when the server runs with BILLING_ENFORCEMENT off. */ /** `false` when the server runs with BILLING_ENFORCEMENT off. */
enforced: z.boolean(), enforced: z.boolean(),
@@ -76,9 +98,12 @@ export const BillingStatusDtoSchema = z.object({
}); });
export type BillingStatusDto = z.output<typeof BillingStatusDtoSchema>; export type BillingStatusDto = z.output<typeof BillingStatusDtoSchema>;
// Mercado Pago requires the payer to log in with this exact email; Stripe asks
// for it in its own checkout, so it is only mandatory for Mercado Pago.
const payerEmailSchema = z.string().trim().email('Ingresá un email válido');
export const SubscribeInputSchema = z.strictObject({ export const SubscribeInputSchema = z.strictObject({
// Mercado Pago requires the payer to log in with this exact email. payerEmail: payerEmailSchema.optional(),
payerEmail: z.string().trim().email('Ingresá un email válido'),
returnTo: billingReturnToSchema.default('billing'), returnTo: billingReturnToSchema.default('billing'),
}); });
export type SubscribeInput = z.output<typeof SubscribeInputSchema>; export type SubscribeInput = z.output<typeof SubscribeInputSchema>;
@@ -92,6 +117,7 @@ export const BillingChargeDtoSchema = z.object({
id: z.string(), id: z.string(),
amount: z.number(), amount: z.number(),
currency: z.string(), currency: z.string(),
/** Normalized across providers: `approved`, `pending` or `rejected`. */
status: z.string(), status: z.string(),
paidAt: isoDateTimeSchema.nullable(), paidAt: isoDateTimeSchema.nullable(),
createdAt: isoDateTimeSchema, createdAt: isoDateTimeSchema,
@@ -111,13 +137,13 @@ export const BillingChargeListSchema = z.object({
export type BillingChargeList = z.output<typeof BillingChargeListSchema>; export type BillingChargeList = z.output<typeof BillingChargeListSchema>;
// Onboarding step "Plan": mandatory. The country comes along because it is not // Onboarding step "Plan": mandatory. The country comes along because it is not
// stored until then, and it decides the price and the Mercado Pago account. // stored until then, and it decides the price and the billing provider.
export const SelectPlanInputSchema = z.discriminatedUnion('plan', [ export const SelectPlanInputSchema = z.discriminatedUnion('plan', [
z.strictObject({ plan: z.literal('FREE'), country: countryCodeSchema }), z.strictObject({ plan: z.literal('FREE'), country: countryCodeSchema }),
z.strictObject({ z.strictObject({
plan: z.literal('PRO'), plan: z.literal('PRO'),
country: countryCodeSchema, country: countryCodeSchema,
payerEmail: z.string().trim().email('Ingresá un email válido'), payerEmail: payerEmailSchema.optional(),
}), }),
]); ]);
export type SelectPlanInput = z.output<typeof SelectPlanInputSchema>; export type SelectPlanInput = z.output<typeof SelectPlanInputSchema>;