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

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