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:
124
apps/backend/src/modules/billing/providers/billing-provider.ts
Normal file
124
apps/backend/src/modules/billing/providers/billing-provider.ts
Normal 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();
|
||||
}
|
||||
32
apps/backend/src/modules/billing/providers/index.ts
Normal file
32
apps/backend/src/modules/billing/providers/index.ts
Normal 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();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
199
apps/backend/src/modules/billing/providers/mercado-pago/index.ts
Normal file
199
apps/backend/src/modules/billing/providers/mercado-pago/index.ts
Normal 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 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { logger } from '@/logger';
|
||||
import { MP_API_URL, MpApiError } from '@/modules/mp/lib';
|
||||
|
||||
// Mercado Pago Subscriptions (preapproval), called with Gruperly's own
|
||||
// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`.
|
||||
|
||||
export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled';
|
||||
|
||||
export type CreatePreapprovalInput = {
|
||||
reason: string;
|
||||
/** Our user id: the only thing that ties the subscription back to a professor. */
|
||||
externalReference: string;
|
||||
/** Mercado Pago requires the payer to log in with this exact email. */
|
||||
payerEmail: string;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
backUrl: string;
|
||||
/** First charge date; omitted means right after the professor authorizes. */
|
||||
startDate?: Date;
|
||||
};
|
||||
|
||||
export type MpPreapproval = {
|
||||
id: string;
|
||||
status: MpPreapprovalStatus | string;
|
||||
externalReference: string | null;
|
||||
initPoint: string | null;
|
||||
nextPaymentDate: string | null;
|
||||
};
|
||||
|
||||
export type MpAuthorizedPayment = {
|
||||
id: string;
|
||||
preapprovalId: string;
|
||||
/** Status of the invoice itself: scheduled, processed, recycling, cancelled. */
|
||||
status: string;
|
||||
/** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */
|
||||
paymentStatus: string | null;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
/** When the charge was debited (or attempted), ISO. */
|
||||
debitDate: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
async function request(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
init: { method?: string; body?: unknown } = {},
|
||||
): Promise<Record<string, unknown>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${MP_API_URL}${path}`, {
|
||||
method: init.method ?? 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: init.body === undefined ? undefined : JSON.stringify(init.body),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const reason = typeof payload?.message === 'string' ? payload.message : null;
|
||||
// The path carries ids, never tokens or emails; the body is not logged.
|
||||
logger.error(
|
||||
{ status: response.status, reason, path: path.split('?')[0] },
|
||||
'Mercado Pago subscriptions request failed',
|
||||
);
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function toPreapproval(payload: Record<string, unknown>): MpPreapproval {
|
||||
return {
|
||||
id: String(payload.id),
|
||||
status: String(payload.status),
|
||||
externalReference:
|
||||
typeof payload.external_reference === 'string' ? payload.external_reference : null,
|
||||
initPoint: typeof payload.init_point === 'string' ? payload.init_point : null,
|
||||
nextPaymentDate:
|
||||
typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a monthly subscription waiting for the professor's authorization.
|
||||
* Nothing is charged until they log in to Mercado Pago through `initPoint`.
|
||||
*/
|
||||
export async function createPreapproval(
|
||||
accessToken: string,
|
||||
input: CreatePreapprovalInput,
|
||||
): Promise<MpPreapproval> {
|
||||
const payload = await request(accessToken, '/preapproval', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
reason: input.reason,
|
||||
external_reference: input.externalReference,
|
||||
payer_email: input.payerEmail,
|
||||
back_url: input.backUrl,
|
||||
status: 'pending',
|
||||
auto_recurring: {
|
||||
frequency: 1,
|
||||
frequency_type: 'months',
|
||||
transaction_amount: input.amount,
|
||||
currency_id: input.currencyId,
|
||||
...(input.startDate ? { start_date: input.startDate.toISOString() } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toPreapproval(payload);
|
||||
}
|
||||
|
||||
export async function getPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
|
||||
}
|
||||
|
||||
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(
|
||||
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
body: { status: 'cancelled' },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
||||
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
||||
return {
|
||||
id: String(payload.id),
|
||||
preapprovalId: String(payload.preapproval_id),
|
||||
status: String(payload.status),
|
||||
paymentStatus: typeof payment?.status === 'string' ? payment.status : null,
|
||||
amount: Number(payload.transaction_amount ?? 0),
|
||||
currencyId: String(payload.currency_id ?? ''),
|
||||
debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null,
|
||||
createdAt: typeof payload.date_created === 'string' ? payload.date_created : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAuthorizedPayment(
|
||||
accessToken: string,
|
||||
id: string,
|
||||
): Promise<MpAuthorizedPayment> {
|
||||
return toAuthorizedPayment(
|
||||
await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 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 = {
|
||||
createPreapproval: typeof createPreapproval;
|
||||
getPreapproval: typeof getPreapproval;
|
||||
cancelPreapproval: typeof cancelPreapproval;
|
||||
getAuthorizedPayment: typeof getAuthorizedPayment;
|
||||
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
||||
};
|
||||
|
||||
export const mpPreapprovalClient: PreapprovalClient = {
|
||||
createPreapproval,
|
||||
getPreapproval,
|
||||
cancelPreapproval,
|
||||
getAuthorizedPayment,
|
||||
searchAuthorizedPayments,
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Checks Mercado Pago's `x-signature` header (`ts=<ts>,v1=<hex>`).
|
||||
*
|
||||
* Mercado Pago does not sign the body: it signs a manifest built from the
|
||||
* notified resource id (the `data.id` query parameter, lower-cased when it is
|
||||
* alphanumeric), the `x-request-id` header and the timestamp. Parts that did
|
||||
* not come in the request are left out of the manifest.
|
||||
*/
|
||||
export function verifyMpSignature(params: {
|
||||
signature: string | null;
|
||||
requestId: string | null;
|
||||
dataId: string | null;
|
||||
secret: string;
|
||||
}): boolean {
|
||||
if (!params.signature) return false;
|
||||
|
||||
let ts: string | null = null;
|
||||
let v1: string | null = null;
|
||||
for (const part of params.signature.split(',')) {
|
||||
const [key, value] = part.split('=', 2).map((piece) => piece.trim());
|
||||
if (key === 'ts') ts = value ?? null;
|
||||
if (key === 'v1') v1 = value ?? null;
|
||||
}
|
||||
if (!ts || !v1) return false;
|
||||
|
||||
const dataId = params.dataId && /^[a-z0-9]+$/i.test(params.dataId)
|
||||
? params.dataId.toLowerCase()
|
||||
: params.dataId;
|
||||
|
||||
let manifest = '';
|
||||
if (dataId) manifest += `id:${dataId};`;
|
||||
if (params.requestId) manifest += `request-id:${params.requestId};`;
|
||||
manifest += `ts:${ts};`;
|
||||
|
||||
const expected = Buffer.from(createHmac('sha256', params.secret).update(manifest).digest('hex'));
|
||||
const received = Buffer.from(v1);
|
||||
return received.length === expected.length && timingSafeEqual(received, expected);
|
||||
}
|
||||
18
apps/backend/src/modules/billing/providers/stripe/config.ts
Normal file
18
apps/backend/src/modules/billing/providers/stripe/config.ts
Normal 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 };
|
||||
}
|
||||
300
apps/backend/src/modules/billing/providers/stripe/index.ts
Normal file
300
apps/backend/src/modules/billing/providers/stripe/index.ts
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user