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

@@ -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);
});
}