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

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