fix: rework stripe webhooks into idempotent subscription sync (#2977)

Replace per-event webhook handlers with a single sync function that
fetches the current state from Stripe and converges the local
subscription, claim, and organisation type.

- Create organisations upfront before checkout, restricted as
  "pending payment" until the first payment syncs
- Add rate-limited subscription sync route, triggered on checkout
  success so the UI doesn't wait on webhooks
- Surface pending payment state in banner, billing table, and limits
This commit is contained in:
Lucas Smith
2026-06-12 16:01:03 +10:00
committed by GitHub
parent b84b87cea6
commit 3887aa67c8
19 changed files with 667 additions and 664 deletions
@@ -1,6 +1,5 @@
import { onSubscriptionUpdated } from '@documenso/ee/server-only/stripe/webhook/on-subscription-updated';
import { syncStripeCustomerSubscription } from '@documenso/ee/server-only/stripe/sync-stripe-customer-subscription';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { Stripe, stripe } from '@documenso/lib/server-only/stripe';
import { prisma } from '@documenso/prisma';
import { adminProcedure } from '../trpc';
@@ -24,9 +23,6 @@ export const syncOrganisationSubscriptionRoute = adminProcedure
const organisation = await prisma.organisation.findUnique({
where: { id: organisationId },
include: {
subscription: true,
},
});
if (!organisation) {
@@ -35,47 +31,14 @@ export const syncOrganisationSubscriptionRoute = adminProcedure
});
}
if (!organisation.subscription) {
if (!organisation.customerId) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Organisation has no subscription to sync',
message: 'Organisation has no Stripe customer to sync from',
});
}
let stripeSubscription: Stripe.Subscription;
try {
stripeSubscription = await stripe.subscriptions.retrieve(organisation.subscription.planId, {
expand: ['items.data.price.product'],
});
} catch (error) {
if (error instanceof Stripe.errors.StripeInvalidRequestError && error.code === 'resource_missing') {
throw new AppError(AppErrorCode.NOT_FOUND, {
message: 'Subscription not found on Stripe',
});
}
throw error;
}
const stripeCustomerId =
typeof stripeSubscription.customer === 'string' ? stripeSubscription.customer : stripeSubscription.customer.id;
if (organisation.customerId !== stripeCustomerId) {
ctx.logger.error({
message: 'Organisation customerId does not match Stripe subscription customer',
organisationId,
localCustomerId: organisation.customerId,
stripeCustomerId,
});
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: `Organisation customerId mismatch: local=${organisation.customerId ?? 'null'}, Stripe=${stripeCustomerId}`,
});
}
await onSubscriptionUpdated({
subscription: stripeSubscription,
previousAttributes: null,
await syncStripeCustomerSubscription({
customerId: organisation.customerId,
bypassClaimUpdate: !syncClaims,
});
});
@@ -14,6 +14,7 @@ import { getPlansRoute } from './get-plans';
import { getSubscriptionRoute } from './get-subscription';
import { linkOrganisationAccountRoute } from './link-organisation-account';
import { manageSubscriptionRoute } from './manage-subscription';
import { syncSubscriptionRoute } from './sync-subscription';
import { updateOrganisationAuthenticationPortalRoute } from './update-organisation-authentication-portal';
import { updateOrganisationEmailRoute } from './update-organisation-email';
import { verifyOrganisationEmailDomainRoute } from './verify-organisation-email-domain';
@@ -48,6 +49,7 @@ export const enterpriseRouter = router({
get: getSubscriptionRoute,
create: createSubscriptionRoute,
manage: manageSubscriptionRoute,
sync: syncSubscriptionRoute,
},
invoices: {
get: getInvoicesRoute,
@@ -0,0 +1,70 @@
import { syncStripeCustomerSubscription } from '@documenso/ee/server-only/stripe/sync-stripe-customer-subscription';
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
import { ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP } from '@documenso/lib/constants/organisations';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { assertRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limit-middleware';
import { syncSubscriptionRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limits';
import { buildOrganisationWhereQuery } from '@documenso/lib/utils/organisations';
import { prisma } from '@documenso/prisma';
import { authenticatedProcedure } from '../trpc';
import { ZSyncSubscriptionRequestSchema, ZSyncSubscriptionResponseSchema } from './sync-subscription.types';
export const syncSubscriptionRoute = authenticatedProcedure
.input(ZSyncSubscriptionRequestSchema)
.output(ZSyncSubscriptionResponseSchema)
.mutation(async ({ ctx, input }) => {
const { organisationId } = input;
ctx.logger.info({
input: {
organisationId,
},
});
const userId = ctx.user.id;
if (!IS_BILLING_ENABLED()) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Billing is not enabled',
});
}
const rateLimitResult = await syncSubscriptionRateLimit.check({
ip: ctx.metadata.requestMetadata.ipAddress ?? 'unknown',
identifier: `${userId}`,
});
assertRateLimit(rateLimitResult);
const organisation = await prisma.organisation.findFirst({
where: buildOrganisationWhereQuery({
organisationId,
userId,
roles: ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP.MANAGE_BILLING,
}),
});
if (!organisation) {
throw new AppError(AppErrorCode.UNAUTHORIZED);
}
if (!organisation.customerId) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Organisation has no billing customer',
});
}
await syncStripeCustomerSubscription({
customerId: organisation.customerId,
}).catch((error) => {
ctx.logger.error({
msg: 'Failed to sync the subscription from Stripe',
error,
});
throw new AppError(AppErrorCode.UNKNOWN_ERROR, {
message: 'Failed to sync the subscription from Stripe',
});
});
});
@@ -0,0 +1,10 @@
import { z } from 'zod';
export const ZSyncSubscriptionRequestSchema = z.object({
organisationId: z.string().describe('The organisation to sync the subscription for'),
});
export const ZSyncSubscriptionResponseSchema = z.void();
export type TSyncSubscriptionRequest = z.infer<typeof ZSyncSubscriptionRequestSchema>;
export type TSyncSubscriptionResponse = z.infer<typeof ZSyncSubscriptionResponseSchema>;
@@ -5,9 +5,8 @@ import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { createOrganisation } from '@documenso/lib/server-only/organisation/create-organisation';
import { getSubscriptionClaim } from '@documenso/lib/server-only/subscription/get-subscription-claim';
import { INTERNAL_CLAIM_ID } from '@documenso/lib/types/subscription';
import { generateStripeOrganisationCreateMetadata } from '@documenso/lib/utils/billing';
import { prisma } from '@documenso/prisma';
import { OrganisationType } from '@prisma/client';
import { OrganisationType, SubscriptionStatus } from '@prisma/client';
import { authenticatedProcedure } from '../trpc';
import { ZCreateOrganisationRequestSchema, ZCreateOrganisationResponseSchema } from './create-organisation.types';
@@ -43,18 +42,67 @@ export const createOrganisationRoute = authenticatedProcedure
}
}
// Create checkout session for payment.
// Create the organisation upfront, then redirect to checkout for payment.
// The webhook sync will attach the real subscription and claim after payment.
if (IS_BILLING_ENABLED() && priceId) {
const customer = await createCustomer({
email: user.email,
name: user.name || user.email,
const pendingOrganisation = await prisma.organisation.findFirst({
where: {
ownerUserId: user.id,
type: OrganisationType.ORGANISATION,
OR: [
{
subscription: {
is: null,
},
},
{
subscription: {
status: SubscriptionStatus.INACTIVE,
},
},
],
},
});
if (pendingOrganisation) {
throw new AppError(AppErrorCode.LIMIT_EXCEEDED, {
message: 'You have a pending organisation awaiting payment. Complete or remove it before creating a new one.',
});
}
const freeSubscriptionClaim = await getSubscriptionClaim(INTERNAL_CLAIM_ID.FREE);
const organisation = await createOrganisation({
userId: user.id,
name,
type: OrganisationType.ORGANISATION,
claim: freeSubscriptionClaim,
});
let customerId = organisation.customerId;
if (!customerId) {
const customer = await createCustomer({
email: user.email,
name: user.name || user.email,
});
customerId = customer.id;
await prisma.organisation.update({
where: {
id: organisation.id,
},
data: {
customerId,
},
});
}
const checkoutUrl = await createCheckoutSession({
priceId,
customerId: customer.id,
returnUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/settings/organisations`,
subscriptionMetadata: generateStripeOrganisationCreateMetadata(name, user.id),
customerId,
returnUrl: `${NEXT_PUBLIC_WEBAPP_URL()}/o/${organisation.url}/settings/billing`,
});
return {