feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)

- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-26 17:01:07 -03:00
parent cd82a1e549
commit 9617447e05
42 changed files with 1938 additions and 457 deletions

View File

@@ -32,12 +32,17 @@ MP_REDIRECT_URI=""
# Generar con: openssl rand -base64 32
TOKEN_ENCRYPTION_KEY=""
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
# Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con
# Suscripciones de Mercado Pago; el resto de los países, con Stripe.
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
MP_PLATFORM_ACCESS_TOKEN_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.
BILLING_ENFORCEMENT="off"
# 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
// Mercado Pago Subscriptions (preapproval), collected by Gruperly's account in
// the professor's country. Not to be confused with `Payment`, which is what
// students pay the professor.
// Gruperly's own billing: the professor pays a monthly Pro subscription,
// collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe
// (every other country), see `modules/billing/providers/`. Not to be confused
// with `Payment`, which is what students pay the professor.
enum BillingProviderId {
MERCADO_PAGO
STRIPE
}
enum SubscriptionStatus {
PENDING
@@ -17,8 +22,14 @@ model BillingSubscription {
currency String
amount Decimal @db.Decimal(12, 2)
payerEmail String @map("payer_email")
// Null between creating the row and Mercado Pago answering.
mpPreapprovalId String? @unique(map: "billing_subscriptions_mpPreapprovalId_key") @map("mp_preapproval_id")
// Who collects it. Sync and cancel always follow this, never the current country.
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)
// When the current attempt started: re-subscribing reuses the row.
requestedAt DateTime @default(now()) @map("requested_at")
@@ -39,18 +50,18 @@ model BillingSubscription {
@@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 {
id String @id @default(cuid())
subscriptionId String @map("subscription_id")
mpAuthorizedPaymentId String @unique(map: "billing_charges_mpAuthorizedPaymentId_key") @map("mp_authorized_payment_id")
amount Decimal @db.Decimal(12, 2)
currency String
// Mercado Pago's own status of the charge (e.g. approved, rejected).
status String
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(cuid())
subscriptionId String @map("subscription_id")
externalId String @unique(map: "billing_charges_externalId_key") @map("external_id")
amount Decimal @db.Decimal(12, 2)
currency String
// Normalized across providers: approved, pending or rejected.
status String
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey")
@@ -58,13 +69,14 @@ model BillingCharge {
@@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 {
country String @map("country_code")
source String @map("source")
dedupeKey String @map("dedupe_key")
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")
@@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 {
return {
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 {
return {
type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`,
title: 'Bad Gateway',
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',
};
}
/** 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 {
return conflictProblem({
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)) {
return true;
}
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;
}
return (
normalizedPath === '/api/v1/health'

View File

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

View File

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

View File

@@ -1,9 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client';
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 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. */
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
@@ -12,7 +13,7 @@ type GetBillingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
guard?: PlanGuard;
sync?: Pick<SyncSubscription, 'execute'>;
credentials?: typeof getPlatformCredentials;
providers?: BillingProviderResolver;
now?: () => Date;
};
@@ -29,11 +30,11 @@ export class GetBillingStatus {
let subscription = await db.billingSubscription.findUnique({ where: { userId } });
// Coming back from Mercado Pago, the webhook may not have arrived yet (or
// may never arrive in local dev): ask Mercado Pago directly, throttled.
// Coming back from the provider's checkout, the webhook may not have
// arrived yet (or may never arrive in local dev): ask directly, throttled.
if (
subscription?.status === 'PENDING'
&& subscription.mpPreapprovalId
&& (subscription.externalId || subscription.checkoutRef)
&& (!subscription.lastSyncedAt
|| 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
// current price of the country is what subscribing would cost.
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({
plan: entitlements.plan,
@@ -62,7 +68,8 @@ export class GetBillingStatus {
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
currency: live ? live.currency : COUNTRY_CURRENCY[country],
country,
availableInCountry: (this.deps.credentials ?? getPlatformCredentials)(country).ok,
provider: provider.id,
availableInCountry: provider.isAvailable(country),
enforced: entitlements.enforced,
usage: entitlements.usage,
limits: entitlements.limits,

View File

@@ -1,75 +1,75 @@
import type { PrismaClient } from '@generated/prisma/client';
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 {
billingProviderErrorProblem,
billingNotAvailableProblem,
notFoundResourceProblem,
payerEmailRequiredProblem,
subscriptionAlreadyActiveProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import {
buildSubscriptionBackUrl,
countryOf,
getPlatformCredentials,
mpPreapprovalClient,
type PreapprovalClient,
} from '../../lib';
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
client?: PreapprovalClient;
credentials?: typeof getPlatformCredentials;
providers?: BillingProviderResolver;
webOrigin?: string;
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.
*
* 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
* never authorized is cancelled first, so the professor can fix the payer
* email by simply trying again.
* never authorized is voided first, with whichever provider it was created, so
* the professor can fix the payer email (or switch country) by trying again.
*/
export class Subscribe {
constructor(private readonly deps: SubscribeDeps = {}) {}
async execute(userId: string, input: SubscribeInput): Promise<Result<SubscribeResultDto, ProblemDetails>> {
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 user = await db.user.findUnique({ where: { id: userId } });
if (!user) return err(notFoundResourceProblem('User', userId));
const country = countryOf(user);
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
if (!credentials.ok) return credentials;
const token = credentials.value.accessToken;
const provider = providers(billingProviderForCountry(country));
if (!provider.isAvailable(country)) return err(billingNotAvailableProblem());
if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem());
const existing = await db.billingSubscription.findUnique({ where: { userId } });
if (existing?.status === 'AUTHORIZED') {
return err(subscriptionAlreadyActiveProblem());
}
if (existing?.mpPreapprovalId && existing.status !== 'CANCELLED') {
if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') {
try {
await client.cancelPreapproval(token, existing.mpPreapprovalId);
await providers(existing.provider).cancel(subscriptionRefOf(existing));
} catch {
// A stale PENDING preapproval that cannot be cancelled is harmless: it
// was never authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not cancel the previous Mercado Pago preapproval');
// A stale attempt that cannot be voided is harmless: it was never
// authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not void the previous Pro subscription attempt');
}
}
const amount = PRO_PRICE_BY_COUNTRY[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({
where: { userId },
@@ -78,7 +78,8 @@ export class Subscribe {
...fields,
status: 'PENDING',
requestedAt: now,
mpPreapprovalId: null,
externalId: null,
checkoutRef: null,
authorizedAt: null,
nextPaymentDate: null,
},
@@ -88,31 +89,27 @@ export class Subscribe {
// so nobody pays twice for the same month.
const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined;
let preapproval: Awaited<ReturnType<PreapprovalClient['createPreapproval']>>;
let started: Awaited<ReturnType<typeof provider.start>>;
try {
preapproval = await client.createPreapproval(token, {
reason: SUBSCRIPTION_REASON,
externalReference: userId,
payerEmail: input.payerEmail,
started = await provider.start({
userId,
country,
amount,
currencyId: currency,
currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
startDate,
});
} catch {
return err(billingProviderErrorProblem());
}
if (!preapproval.initPoint) {
logger.error({ userId }, 'Mercado Pago preapproval came back without init_point');
return err(billingProviderErrorProblem());
} catch (error) {
logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription');
return err(toBillingProblem(error));
}
await db.billingSubscription.update({
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 { 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
* browser, so there is no session. One URL per country, because each country
* is a different Gruperly account with its own webhook secret.
* Public endpoints (see `isPublicApiRequest`): the providers call them, not the
* browser, so there is no session; each adapter checks its own signature.
* 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();
route.post('/webhooks/mp/:country', async (c) => {
const result = await new HandleBillingWebhook().execute({
country: c.req.param('country'),
const FAILURE_STATUS: Record<BillingWebhookFailure, 401 | 404 | 500 | 503> = {
invalid_signature: 401,
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(),
headers: c.req.raw.headers,
query: new URL(c.req.url).searchParams,
});
if (!result.ok) {
logger.warn({ reason: result.error }, 'Mercado Pago billing webhook rejected');
const status =
result.error === 'invalid_signature'
? 401
: result.error === 'unknown_country'
? 404
: result.error === 'not_configured'
? 503
: 500;
return c.body(null, status);
logger.warn({ provider: providerId, reason: result.error }, 'Billing webhook rejected');
return c.body(null, FAILURE_STATUS[result.error]);
}
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;

View File

@@ -1,78 +1,50 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared';
import { countryCodeSchema, err, ok } from '@gruperly/shared';
import type { BillingProviderId, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { SyncSubscription } from '../../lib';
import {
getPlatformCredentials,
mpPreapprovalClient,
type PreapprovalClient,
SyncSubscription,
verifyMpSignature,
} from '../../lib';
type BillingProviderResolver,
type BillingWebhookFailure,
type BillingWebhookRequest,
getBillingProvider,
} from '../../providers';
export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers';
type HandleBillingWebhookDeps = {
db?: Pick<PrismaClient, 'billingWebhookEvent'>;
client?: PreapprovalClient;
credentials?: typeof getPlatformCredentials;
sync?: Pick<SyncSubscription, 'byPreapprovalId'>;
providers?: BillingProviderResolver;
sync?: Pick<SyncSubscription, 'byExternalId'>;
};
export type BillingWebhookFailure =
| 'unknown_country'
| 'not_configured'
| 'invalid_signature'
| 'sync_failed';
/** Prisma's unique-constraint violation: this delivery was already processed. */
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
* is fetched again from Mercado Pago and synced (`SyncSubscription`). The body
* is never trusted for a status. If syncing fails the dedupe key is removed, so
* Mercado Pago's retry gets another chance (same rule as the WhatsApp webhook).
* The provider adapter checks the signature and says which subscription the
* notification is about; the subscription is then fetched again from the
* provider and synced (`SyncSubscription`). The body is never trusted for a
* 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 {
constructor(private readonly deps: HandleBillingWebhookDeps = {}) {}
async execute(
providerId: BillingProviderId,
request: BillingWebhookRequest,
): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
const parsedCountry = countryCodeSchema.safeParse(request.country.toUpperCase());
if (!parsedCountry.success) return err('unknown_country');
const country: CountryCode = parsedCountry.data;
const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request);
if (!parsed.ok) return parsed;
const hint = parsed.value;
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
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 });
}
if (!hint.externalId) return ok({ duplicate: false, applied: false });
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) {
try {
await db.billingWebhookEvent.create({ data: dedupe });
@@ -87,23 +59,15 @@ export class HandleBillingWebhook {
const unburn = async () => {
if (!dedupe) return;
await db.billingWebhookEvent
.delete({ where: { country_dedupeKey: dedupe } })
.delete({ where: { source_dedupeKey: dedupe } })
.catch(() => undefined);
};
try {
let preapprovalId = dataId;
if (type === 'subscription_authorized_payment') {
const invoice = await (this.deps.client ?? mpPreapprovalClient).getAuthorizedPayment(
credentials.value.accessToken,
dataId,
);
preapprovalId = invoice.preapprovalId;
}
const synced = await (this.deps.sync ?? new SyncSubscription()).byPreapprovalId(
country,
preapprovalId,
const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId(
providerId,
hint.externalId,
hint.country,
);
if (!synced.ok) {
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,12 +41,16 @@ export class ReconcileSubscriptions {
const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS);
const rows = await db.billingSubscription.findMany({
where: {
mpPreapprovalId: { not: null },
OR: [
{ status: 'PENDING' },
AND: [
{ OR: [{ externalId: { not: null } }, { checkoutRef: { not: null } }] },
{
status: { in: ['AUTHORIZED', 'PAUSED'] },
OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }],
OR: [
{ status: 'PENDING' },
{
status: { in: ['AUTHORIZED', 'PAUSED'] },
OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }],
},
],
},
],
},

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;
/**
* 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
* 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;
}
/** 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 {
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 {
type Entitlements,
exceedsLimits,
@@ -10,11 +10,4 @@ export {
type SubscriptionSnapshot,
} from './entitlements';
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
export {
type MpAuthorizedPayment,
type MpPreapproval,
mpPreapprovalClient,
type PreapprovalClient,
} from './mp-preapproval';
export { coveredUntil, SyncSubscription, type SyncSubscriptionDeps } from './sync';
export { verifyMpSignature } from './webhook-signature';
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';

View File

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

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(
accessToken: string,
preapprovalId: string,
): Promise<MpAuthorizedPayment[]> {
const query = new URLSearchParams({ preapproval_id: preapprovalId, limit: '50' });
const payload = await request(accessToken, `/authorized_payments/search?${query}`);
const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
return results.map(toAuthorizedPayment);
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 results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
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 = {

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 { ok } from '@gruperly/shared';
import { billingNotAvailableProblem } from '@/http/problem-builders';
import { CancelSubscription } from '@/modules/billing/features/cancel/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 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[] = [];
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 {
user: { findUnique: mock(async () => ({ id: userId, country })) },
user: { findUnique: mock(async () => ({ id: userId, country, email: 'login@mail.com' })) },
billingSubscription: {
findUnique: mock(async () => existing),
upsert: mock(async (args: { create: Record<string, unknown> }) => {
@@ -44,11 +44,16 @@ function makeClient(): PreapprovalClient {
} as unknown as PreapprovalClient;
}
function mpProvider(client: PreapprovalClient) {
return new MercadoPagoBillingProvider({ client, credentials });
}
function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
const provider = mpProvider(client);
return {
client,
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,
{ payerEmail: 'profe@mail.com', returnTo },
),
@@ -72,14 +77,14 @@ describe('Subscribe', () => {
reason: 'Gruperly Pro',
externalReference: userId,
payerEmail: 'profe@mail.com',
amount: 199,
currencyId: 'MXN',
amount: 15000,
currencyId: 'ARS',
backUrl: 'http://web/billing?sub=return',
startDate: undefined,
});
expect(db.billingSubscription.update).toHaveBeenCalledWith({
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 () => {
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();
@@ -103,7 +108,7 @@ describe('Subscribe', () => {
});
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();
@@ -112,7 +117,7 @@ describe('Subscribe', () => {
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 { client, run } = subscribe(makeDb({ status: 'CANCELLED', mpPreapprovalId: 'old', paidThrough }));
const { client, run } = subscribe(makeDb({ status: 'CANCELLED', provider: 'MERCADO_PAGO', externalId: 'old', paidThrough }));
await run();
@@ -123,13 +128,13 @@ describe('Subscribe', () => {
});
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 result = await new Subscribe({
db: db as never,
client,
credentials: () => ({ ok: false, error: billingNotAvailableProblem() }),
}).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing' });
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
payerEmail: 'profe@mail.com',
returnTo: 'billing',
});
expect(result.ok).toBe(false);
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 () => {
const db = {
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 () => ({})),
},
};
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(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1');
@@ -174,9 +187,113 @@ describe('CancelSubscription', () => {
it('has nothing to cancel without a live subscription', async () => {
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);
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 { ok } from '@gruperly/shared';
import type { MpAuthorizedPayment, PreapprovalClient } from '@/modules/billing/lib';
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 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> = {}) {
return {
@@ -14,7 +18,9 @@ function subscription(overrides: Record<string, unknown> = {}) {
country: 'AR',
currency: 'ARS',
status: 'PENDING',
mpPreapprovalId: 'pre-1',
provider: 'MERCADO_PAGO',
externalId: 'pre-1',
checkoutRef: null,
authorizedAt: null,
paidThrough: null,
...overrides,
@@ -62,8 +68,11 @@ function makeClient(params: { status?: string; externalReference?: string | null
} 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) {
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', () => {
@@ -74,10 +83,10 @@ describe('SyncSubscription', () => {
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
expect(db.billingCharge.upsert).toHaveBeenCalledWith({
where: { mpAuthorizedPaymentId: 'inv-1' },
where: { externalId: 'inv-1' },
create: {
subscriptionId: 'sub-1',
mpAuthorizedPaymentId: 'inv-1',
externalId: 'inv-1',
amount: 15000,
currency: 'ARS',
status: 'approved',
@@ -88,15 +97,36 @@ describe('SyncSubscription', () => {
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: {
externalId: undefined,
status: 'AUTHORIZED',
authorizedAt: now,
nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'),
paidThrough: new Date('2026-11-20T10:00:00.000Z'),
payerEmail: undefined,
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 () => {
const paidThrough = new Date('2026-10-25T00:00:00.000Z');
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.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({
where: { userId, country: 'AR', mpPreapprovalId: null },
data: { mpPreapprovalId: 'pre-1' },
where: { userId, provider: 'MERCADO_PAGO', externalId: null, country: 'AR' },
data: { externalId: 'pre-1' },
});
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 () => {
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(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 { isPublicApiRequest } from '@/http/session-auth';
import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case';
import type { PreapprovalClient } from '@/modules/billing/lib';
import { verifyMpSignature } from '@/modules/billing/lib/webhook-signature';
import {
MercadoPagoBillingProvider,
type PreapprovalClient,
verifyMpSignature,
} from '@/modules/billing/providers/mercado-pago';
import { StripeBillingProvider } from '@/modules/billing/providers/stripe';
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') {
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 }) {
const requestId = params.requestId ?? 'req-1';
return {
country: 'ar',
routeParam: 'ar',
rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }),
headers: new Headers({
'x-request-id': requestId,
@@ -35,7 +39,7 @@ function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const
delete: mock(async () => ({})),
},
};
const sync = { byPreapprovalId: mock(async () => syncResult) };
const sync = { byExternalId: mock(async () => syncResult) };
const client = {
getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })),
} as unknown as PreapprovalClient;
@@ -43,12 +47,8 @@ function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const
}
function handler(deps: ReturnType<typeof makeDeps>) {
return new HandleBillingWebhook({
db: deps.db as never,
sync: deps.sync as never,
client: deps.client,
credentials,
});
const provider = new MercadoPagoBillingProvider({ client: deps.client, credentials });
return new HandleBillingWebhook({ db: deps.db as never, sync: deps.sync as never, providers: () => provider });
}
describe('verifyMpSignature', () => {
@@ -69,31 +69,32 @@ describe('HandleBillingWebhook', () => {
const deps = makeDeps();
const result = await handler(deps).execute(
'MERCADO_PAGO',
request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }),
);
expect(result).toEqual(err('invalid_signature'));
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 () => {
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(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-1');
expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { country: 'AR', dedupeKey: 'req-1' } });
expect(deps.sync.byExternalId).toHaveBeenCalledWith('MERCADO_PAGO', 'pre-1', 'AR');
expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { source: 'mp:AR', dedupeKey: 'req-1' } });
});
it('resolves an invoice notification to its subscription', async () => {
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.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 () => {
@@ -102,35 +103,121 @@ describe('HandleBillingWebhook', () => {
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(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 () => {
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(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 () => {
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(deps.sync.byPreapprovalId).not.toHaveBeenCalled();
expect(deps.sync.byExternalId).not.toHaveBeenCalled();
});
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/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('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();
});
});