Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Fix involuntary churn

Blue Mousebf9edc9bd0c2
diff --git a/backend/apps/cloud/src/common/templates/en/subscription-payment-failed.html b/backend/apps/cloud/src/common/templates/en/subscription-payment-failed.html
new file mode 100644
index 000000000..909a3df72
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/subscription-payment-failed.html
@@ -0,0 +1,10 @@
+We could not process your latest Swetrix subscription payment{{#if
+amountFormatted}} for {{amountFormatted}}{{/if}}.<br /><br />
+
+Your dashboard remains available while Paddle retries the payment{{#if
+nextRetryAtFormatted}} on {{nextRetryAtFormatted}}{{/if}}. Please update your
+payment details to avoid an access lock.<br /><br />
+
+<a href="{{billingUrl}}" target="_blank">Update payment details</a>
+<br /><br />
+Reply to this email if you have questions or need help.
diff --git a/backend/apps/cloud/src/common/templates/en/subscription-payment-final-warning.html b/backend/apps/cloud/src/common/templates/en/subscription-payment-final-warning.html
new file mode 100644
index 000000000..cbd85b9c3
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/subscription-payment-final-warning.html
@@ -0,0 +1,10 @@
+Your Swetrix subscription payment still has not gone through.<br /><br />
+
+Your dashboard is scheduled to lock{{#if suspendsAtFormatted}} on
+{{suspendsAtFormatted}}{{/if}}, but we will keep your projects and analytics
+data safe. Update your payment details before then to keep access uninterrupted.
+<br /><br />
+
+<a href="{{billingUrl}}" target="_blank">Update payment details</a>
+<br /><br />
+Reply to this email if you have questions or need help.
diff --git a/backend/apps/cloud/src/common/templates/en/subscription-payment-recovered.html b/backend/apps/cloud/src/common/templates/en/subscription-payment-recovered.html
new file mode 100644
index 000000000..982fa3fba
--- /dev/null
+++ b/backend/apps/cloud/src/common/templates/en/subscription-payment-recovered.html
@@ -0,0 +1,8 @@
+Your Swetrix subscription payment has been recovered and your account is back in
+good standing.<br /><br />
+
+If your dashboard was locked, access has now been restored. You can review your
+billing details from your
+<a href="{{billingUrl}}" target="_blank">billing page</a>.<br /><br />
+
+Reply to this email if you have questions or need help.
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index ce1e69f42..1b32b52ac 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -13,6 +13,9 @@ export enum LetterTemplate {
TrialExpired = 'trial-expired',
TrialEndsTomorrow = 'trial-ends-tomorrow',
TrialEndingCancelled = 'trial-ending-cancelled',
+ SubscriptionPaymentFailed = 'subscription-payment-failed',
+ SubscriptionPaymentFinalWarning = 'subscription-payment-final-warning',
+ SubscriptionPaymentRecovered = 'subscription-payment-recovered',
ProjectSubscriberInvitation = 'project-subscriber-invitation',
ProjectTransfer = 'project-transfer',
UsageOverLimit = 'usage-over-limit',
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index 6f1b53c98..91ef9de48 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -96,6 +96,21 @@ const metaInfoJson = {
en: () => 'Your Swetrix trial ends in 48 hours — action needed',
},
},
+ [LetterTemplate.SubscriptionPaymentFailed]: {
+ subject: {
+ en: () => 'Action required: your Swetrix payment failed',
+ },
+ },
+ [LetterTemplate.SubscriptionPaymentFinalWarning]: {
+ subject: {
+ en: () => 'Final reminder: update your Swetrix payment details',
+ },
+ },
+ [LetterTemplate.SubscriptionPaymentRecovered]: {
+ subject: {
+ en: () => 'Your Swetrix payment was recovered',
+ },
+ },
[LetterTemplate.ProjectSubscriberInvitation]: {
subject: {
en: () => 'You have been invited to join the project',
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 38d633695..67135027e 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -40,6 +40,10 @@ import {
ReportFrequency as UserReportFrequency,
getDefaultAccountLimitUpdates,
} from '../user/entities/user.entity'
+import {
+ BillingDunningEmailStage,
+ SubscriptionDunningStatus,
+} from '../user/entities/subscription-dunning.entity'
import {
SEND_WARNING_AT_PERC,
PROJECT_INVITE_EXPIRE,
@@ -119,6 +123,7 @@ const CHUNK_SIZE = 5000
const REPORTS_USERS_CONCURRENCY = 3
const REPORTS_PROJECTS_CONCURRENCY = 5
const NO_EVENTS_REMINDER_DELAY_DAYS = 2
+const BILLING_URL = 'https://swetrix.com/user-settings?tab=billing'
const CAPTCHA_PASS_CONDITION =
"type = 'captcha' AND if(indexOf(`meta.key`, 'captcha_event') = 0, 'pass', arrayElement(`meta.value`, indexOf(`meta.key`, 'captcha_event'))) = 'pass'"
const TELEGRAM_MARKDOWN_URL_KEYS = new Set(['dashboard_url', 'errors_url'])
@@ -146,6 +151,26 @@ const mapLimit = async <T, R>(
return results
}
+const formatBillingDateForEmail = (
+ date?: Date | string | null,
+): string | null => {
+ if (!date) {
+ return null
+ }
+
+ const parsed = new Date(date)
+
+ if (isNaN(parsed.getTime())) {
+ return null
+ }
+
+ return `${parsed.toLocaleString('en-GB', {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ timeZone: 'UTC',
+ })} UTC`
+}
+
const generatePlanUsageQueryForUser = (): string => {
// NOTE: keep all values parameterized to avoid injection and formatting issues.
// Counts every billable event kind (pageview, custom_event, error, captcha)
@@ -1462,6 +1487,64 @@ export class TaskManagerService {
}
}
+ @Cron(CronExpression.EVERY_HOUR)
+ async processBillingDunning() {
+ try {
+ const suspensionDunnings =
+ await this.userService.getSubscriptionDunningsForSuspension()
+
+ await Promise.allSettled(
+ _map(suspensionDunnings, async (dunning) => {
+ const user = dunning.user
+
+ await this.userService.update(user.id, {
+ dashboardBlockReason: DashboardBlockReason.payment_failed,
+ isAccountBillingSuspended: true,
+ })
+ await this.userService.updateSubscriptionDunning(dunning.id, {
+ status: SubscriptionDunningStatus.locked,
+ emailStage: BillingDunningEmailStage.locked,
+ })
+ await this.projectService.clearProjectsRedisCache(user.id)
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.DashboardLockedPaymentFailure,
+ {
+ billingUrl: user.subUpdateURL || BILLING_URL,
+ },
+ )
+ }),
+ )
+
+ const warningDunnings =
+ await this.userService.getSubscriptionDunningsForFinalWarning()
+
+ await Promise.allSettled(
+ _map(warningDunnings, async (dunning) => {
+ const user = dunning.user
+
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.SubscriptionPaymentFinalWarning,
+ {
+ billingUrl: user.subUpdateURL || BILLING_URL,
+ suspendsAtFormatted: formatBillingDateForEmail(
+ dunning.suspendsAt,
+ ),
+ },
+ )
+ await this.userService.updateSubscriptionDunning(dunning.id, {
+ emailStage: BillingDunningEmailStage.final_warning,
+ })
+ }),
+ )
+ } catch (reason) {
+ this.logger.error(
+ `[CRON WORKER](processBillingDunning) Error occured: ${reason}`,
+ )
+ }
+ }
+
@Cron(CronExpression.EVERY_2_HOURS)
async cleanUpUnpaidSubUsers() {
const users = await this.userService.find({
@@ -1495,6 +1578,10 @@ export class TaskManagerService {
planType: null,
...getDefaultAccountLimitUpdates(),
})
+ await this.userService.resolveOpenSubscriptionDunnings(
+ user.id,
+ SubscriptionDunningStatus.cancelled,
+ )
await this.projectService.clearProjectsRedisCache(user.id)
}
})
@@ -1593,6 +1680,10 @@ export class TaskManagerService {
dashboardBlockReason: DashboardBlockReason.trial_ended,
// trialEndDate: null,
})
+ await this.userService.resolveOpenSubscriptionDunnings(
+ id,
+ SubscriptionDunningStatus.cancelled,
+ )
await this.mailerService.sendEmail(email, LetterTemplate.TrialExpired, {
url: 'https://swetrix.com/user-settings?tab=billing',
})
diff --git a/backend/apps/cloud/src/user/entities/subscription-dunning.entity.ts b/backend/apps/cloud/src/user/entities/subscription-dunning.entity.ts
new file mode 100644
index 000000000..711333eee
--- /dev/null
+++ b/backend/apps/cloud/src/user/entities/subscription-dunning.entity.ts
@@ -0,0 +1,89 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ JoinColumn,
+ ManyToOne,
+ PrimaryGeneratedColumn,
+ UpdateDateColumn,
+} from 'typeorm'
+
+import { User } from './user.entity'
+
+export enum SubscriptionDunningStatus {
+ active = 'active',
+ recovered = 'recovered',
+ locked = 'locked',
+ cancelled = 'cancelled',
+}
+
+export enum BillingDunningEmailStage {
+ payment_failed = 'payment_failed',
+ final_warning = 'final_warning',
+ locked = 'locked',
+}
+
+@Entity()
+@Index(['userId', 'status'])
+@Index(['subID', 'status'])
+@Index(['subscriptionPaymentId'])
+@Index(['suspendsAt', 'status'])
+export class SubscriptionDunning {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar', { length: 36 })
+ userId: string
+
+ @ManyToOne(() => User, { onDelete: 'CASCADE' })
+ @JoinColumn({ name: 'userId' })
+ user: User
+
+ @Column('varchar', { length: 32, nullable: true })
+ subID: string | null
+
+ @Column('varchar', { length: 80, nullable: true })
+ subscriptionPaymentId: string | null
+
+ @Column({
+ type: 'enum',
+ enum: SubscriptionDunningStatus,
+ default: SubscriptionDunningStatus.active,
+ })
+ status: SubscriptionDunningStatus
+
+ @Column('int', { default: 1 })
+ attempt: number
+
+ @Column({
+ type: 'enum',
+ enum: BillingDunningEmailStage,
+ nullable: true,
+ })
+ emailStage: BillingDunningEmailStage | null
+
+ @Column({ type: 'timestamp', nullable: true })
+ startedAt: Date | null
+
+ @Column({ type: 'timestamp', nullable: true })
+ lastFailedAt: Date | null
+
+ @Column({ type: 'timestamp', nullable: true })
+ nextRetryAt: Date | null
+
+ @Column({ type: 'timestamp', nullable: true })
+ suspendsAt: Date | null
+
+ @Column({ type: 'timestamp', nullable: true })
+ resolvedAt: Date | null
+
+ @Column({ type: 'json', nullable: true })
+ metadata: Record<string, unknown> | null
+
+ @CreateDateColumn()
+ createdAt: Date
+
+ @UpdateDateColumn()
+ updatedAt: Date
+}
diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.ts
index a744dd1a8..9c985f8db 100644
--- a/backend/apps/cloud/src/user/user.module.ts
+++ b/backend/apps/cloud/src/user/user.module.ts
@@ -17,6 +17,7 @@ import { Message } from '../integrations/telegram/entities/message.entity'
import { OrganisationModule } from '../organisation/organisation.module'
import { UserAddon } from './entities/user-addon.entity'
import { UserAddonCharge } from './entities/user-addon-charge.entity'
+import { SubscriptionDunning } from './entities/subscription-dunning.entity'
@Module({
imports: [
@@ -28,6 +29,7 @@ import { UserAddonCharge } from './entities/user-addon-charge.entity'
UserFeedback,
UserAddon,
UserAddonCharge,
+ SubscriptionDunning,
Message,
]),
ActionTokensModule,
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 1216368ba..23b758a66 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -56,6 +56,11 @@ import {
UserAddonChargeKind,
UserAddonChargeStatus,
} from './entities/user-addon-charge.entity'
+import {
+ BillingDunningEmailStage,
+ SubscriptionDunning,
+ SubscriptionDunningStatus,
+} from './entities/subscription-dunning.entity'
import { UserGoogleDTO } from './dto/user-google.dto'
import { UserGithubDTO } from './dto/user-github.dto'
import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'
@@ -280,6 +285,8 @@ export class UserService {
private readonly userAddonRepository: Repository<UserAddon>,
@InjectRepository(UserAddonCharge)
private readonly userAddonChargeRepository: Repository<UserAddonCharge>,
+ @InjectRepository(SubscriptionDunning)
+ private readonly subscriptionDunningRepository: Repository<SubscriptionDunning>,
private readonly organisationService: OrganisationService,
) {}
@@ -2814,6 +2821,133 @@ export class UserService {
return bytes.toString(CryptoJS.enc.Utf8)
}
+ getOpenSubscriptionDunning(
+ userId: string,
+ ): Promise<SubscriptionDunning | null> {
+ return this.subscriptionDunningRepository.findOne({
+ where: {
+ userId,
+ status: In([
+ SubscriptionDunningStatus.active,
+ SubscriptionDunningStatus.locked,
+ ]),
+ },
+ order: {
+ createdAt: 'DESC',
+ },
+ })
+ }
+
+ async saveSubscriptionDunning(
+ dunning: Partial<SubscriptionDunning>,
+ ): Promise<SubscriptionDunning> {
+ if (dunning.id) {
+ const { id, ...update } = dunning
+
+ await this.subscriptionDunningRepository.update(id, update)
+
+ return this.subscriptionDunningRepository.findOne({
+ where: { id },
+ })
+ }
+
+ return this.subscriptionDunningRepository.save(
+ this.subscriptionDunningRepository.create(dunning),
+ )
+ }
+
+ async updateSubscriptionDunning(
+ id: string,
+ update: Partial<SubscriptionDunning>,
+ ): Promise<void> {
+ await this.subscriptionDunningRepository.update(id, update)
+ }
+
+ async resolveOpenSubscriptionDunnings(
+ userId: string,
+ status: SubscriptionDunningStatus,
+ ): Promise<void> {
+ await this.subscriptionDunningRepository.update(
+ {
+ userId,
+ status: In([
+ SubscriptionDunningStatus.active,
+ SubscriptionDunningStatus.locked,
+ ]),
+ },
+ {
+ status,
+ resolvedAt: new Date(),
+ },
+ )
+ }
+
+ async resolveSubscriptionDunningsBySubID(
+ subID: string,
+ status: SubscriptionDunningStatus,
+ ): Promise<void> {
+ await this.subscriptionDunningRepository.update(
+ {
+ subID,
+ status: In([
+ SubscriptionDunningStatus.active,
+ SubscriptionDunningStatus.locked,
+ ]),
+ },
+ {
+ status,
+ resolvedAt: new Date(),
+ },
+ )
+ }
+
+ async getSubscriptionDunningsForFinalWarning(
+ now = new Date(),
+ ): Promise<SubscriptionDunning[]> {
+ const cutoff = dayjs.utc(now).add(24, 'hour').toDate()
+
+ return this.subscriptionDunningRepository
+ .createQueryBuilder('dunning')
+ .leftJoinAndSelect('dunning.user', 'user')
+ .where('dunning.status = :status', {
+ status: SubscriptionDunningStatus.active,
+ })
+ .andWhere('dunning.suspendsAt IS NOT NULL')
+ .andWhere('dunning.suspendsAt < :cutoff', { cutoff })
+ .andWhere('user.dashboardBlockReason IS NULL')
+ .andWhere('user.isAccountBillingSuspended = :isSuspended', {
+ isSuspended: false,
+ })
+ .andWhere(
+ '(dunning.emailStage IS NULL OR dunning.emailStage NOT IN (:...stages))',
+ {
+ stages: [
+ BillingDunningEmailStage.final_warning,
+ BillingDunningEmailStage.locked,
+ ],
+ },
+ )
+ .getMany()
+ }
+
+ async getSubscriptionDunningsForSuspension(
+ now = new Date(),
+ ): Promise<SubscriptionDunning[]> {
+ return this.subscriptionDunningRepository
+ .createQueryBuilder('dunning')
+ .leftJoinAndSelect('dunning.user', 'user')
+ .where('dunning.status = :status', {
+ status: SubscriptionDunningStatus.active,
+ })
+ .andWhere('dunning.suspendsAt IS NOT NULL')
+ .andWhere('dunning.suspendsAt < :now', { now })
+ .andWhere('user.dashboardBlockReason IS NULL')
+ .andWhere('user.isAccountBillingSuspended = :isSuspended', {
+ isSuspended: false,
+ })
+ .getMany()
+ }
+
async getReportUsers(
reportFrequency:
| ReportFrequency.WEEKLY
diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.ts
index ef1d4bb77..da65fce71 100644
--- a/backend/apps/cloud/src/webhook/webhook.controller.ts
+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts
@@ -15,9 +15,15 @@ import { getIPFromHeaders } from '../common/utils'
import {
DashboardBlockReason,
PlanType,
+ User,
getAccountPlanByPaddleProductId,
isNextPlan,
} from '../user/entities/user.entity'
+import {
+ BillingDunningEmailStage,
+ SubscriptionDunning,
+ SubscriptionDunningStatus,
+} from '../user/entities/subscription-dunning.entity'
import { UserService } from '../user/user.service'
import { AppLoggerService } from '../logger/logger.service'
import { WebhookService } from './webhook.service'
@@ -31,6 +37,10 @@ import {
RevenueType,
} from '../revenue/interfaces/revenue.interface'
+const BILLING_URL = 'https://swetrix.com/user-settings?tab=billing'
+const BILLING_DUNNING_GRACE_DAYS = 7
+const BILLING_DUNNING_FINAL_GRACE_HOURS = 24
+
@ApiTags('Webhook')
@Controller('webhook')
export class WebhookController {
@@ -110,6 +120,303 @@ export class WebhookController {
return isNaN(date.getTime()) ? new Date() : date
}
+ private getPaddleDate(
+ body: Record<string, unknown>,
+ fields: string[],
+ ): Date | null {
+ const value = this.getPaddleField(body, fields)
+
+ if (!value) {
+ return null
+ }
+
+ const date = new Date(
+ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(value)
+ ? `${value.replace(' ', 'T')}Z`
+ : value,
+ )
+
+ return isNaN(date.getTime()) ? null : date
+ }
+
+ private getPaddleNumber(
+ body: Record<string, unknown>,
+ fields: string[],
+ ): number | null {
+ const value = this.getPaddleField(body, fields)
+
+ if (!value) {
+ return null
+ }
+
+ const number = Number(value)
+
+ return Number.isFinite(number) ? number : null
+ }
+
+ private formatDateForEmail(date?: Date | string | null): string | null {
+ if (!date) {
+ return null
+ }
+
+ const parsed = new Date(date)
+
+ if (isNaN(parsed.getTime())) {
+ return null
+ }
+
+ return `${parsed.toLocaleString('en-GB', {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ timeZone: 'UTC',
+ })} UTC`
+ }
+
+ private formatPaymentAmount(body: Record<string, unknown>): string | null {
+ const amount = this.getPaddleAmount(body, [
+ 'amount',
+ 'sale_gross',
+ 'balance_gross',
+ 'unit_price',
+ ])
+ const currency = this.getPaddleField(body, [
+ 'currency',
+ 'balance_currency',
+ ])?.toUpperCase()
+
+ return amount && currency ? `${currency} ${amount.toFixed(2)}` : null
+ }
+
+ private getBillingUrl(user?: User | null): string {
+ return user?.subUpdateURL || BILLING_URL
+ }
+
+ private getDunningSuspendsAt(
+ dunning: SubscriptionDunning | null,
+ nextRetryAt: Date | null,
+ pausedFrom: Date | null,
+ finalFailure: boolean,
+ ): Date {
+ const now = new Date()
+
+ if (pausedFrom) {
+ return pausedFrom
+ }
+
+ if (finalFailure) {
+ return new Date(
+ now.getTime() + BILLING_DUNNING_FINAL_GRACE_HOURS * 60 * 60 * 1000,
+ )
+ }
+
+ const graceDate = new Date(
+ now.getTime() + BILLING_DUNNING_GRACE_DAYS * 24 * 60 * 60 * 1000,
+ )
+ const retryDate = nextRetryAt
+ ? new Date(
+ nextRetryAt.getTime() +
+ BILLING_DUNNING_FINAL_GRACE_HOURS * 60 * 60 * 1000,
+ )
+ : null
+ const fallbackDate =
+ retryDate && retryDate > graceDate ? retryDate : graceDate
+ const existingDate = dunning?.suspendsAt
+ ? new Date(dunning.suspendsAt)
+ : null
+
+ return existingDate && existingDate > fallbackDate
+ ? existingDate
+ : fallbackDate
+ }
+
+ private async findPaddleSubscriber(
+ body: Record<string, unknown>,
+ ): Promise<User | null> {
+ const passthrough = this.getPaddlePassthrough(body)
+ const uid = this.getPaddleField(passthrough, ['uid'])
+ const subID = this.getPaddleField(body, ['subscription_id'])
+ const email = this.getPaddleField(body, ['email'])
+
+ if (subID) {
+ const user = await this.userService.findOne({ where: { subID } })
+
+ if (user) {
+ return user
+ }
+ }
+
+ if (uid) {
+ const user = await this.userService.findOne({ where: { id: uid } })
+
+ if (user) {
+ return user
+ }
+ }
+
+ return email ? this.userService.findOne({ where: { email } }) : null
+ }
+
+ private async handlePaddlePaymentIssue(
+ body: Record<string, unknown>,
+ knownUser?: User,
+ ): Promise<void> {
+ const user = knownUser || (await this.findPaddleSubscriber(body))
+
+ if (!user) {
+ this.logger.error(
+ `[${body.alert_name}] Cannot find the subscriber: ${JSON.stringify(body)}`,
+ )
+ return
+ }
+
+ const now = new Date()
+ const status = this.getPaddleField(body, ['status'])
+ const isPaused = status === 'paused'
+ const isPaymentFailedWebhook =
+ body.alert_name === 'subscription_payment_failed'
+ const dunning = await this.userService.getOpenSubscriptionDunning(user.id)
+ const nextRetryAt = this.getPaddleDate(body, ['next_retry_date'])
+ const pausedFrom = this.getPaddleDate(body, ['paused_from'])
+ const subID = this.getPaddleField(body, ['subscription_id']) || user.subID
+ const paymentId = this.getPaddleField(body, [
+ 'subscription_payment_id',
+ 'payment_id',
+ 'alert_id',
+ ])
+ const rawAttempt = this.getPaddleNumber(body, ['attempt_number'])
+ const attempt = rawAttempt || dunning?.attempt || 1
+ const updateUrl = this.getPaddleField(body, ['update_url'])
+ const cancelUrl = this.getPaddleField(body, ['cancel_url'])
+ const finalFailure = isPaused || (isPaymentFailedWebhook && !nextRetryAt)
+ const suspendsAt = this.getDunningSuspendsAt(
+ dunning,
+ nextRetryAt,
+ pausedFrom,
+ finalFailure,
+ )
+ const isAlreadyLocked =
+ dunning?.status === SubscriptionDunningStatus.locked ||
+ user.dashboardBlockReason === DashboardBlockReason.payment_failed ||
+ user.isAccountBillingSuspended
+ const shouldSuspendNow =
+ isAlreadyLocked || (isPaused && (!pausedFrom || pausedFrom <= now))
+ const emailStage = shouldSuspendNow
+ ? BillingDunningEmailStage.locked
+ : finalFailure
+ ? BillingDunningEmailStage.final_warning
+ : BillingDunningEmailStage.payment_failed
+ const updateParams: Partial<SubscriptionDunning> = {
+ id: dunning?.id,
+ userId: user.id,
+ subID,
+ subscriptionPaymentId: paymentId,
+ status: shouldSuspendNow
+ ? SubscriptionDunningStatus.locked
+ : SubscriptionDunningStatus.active,
+ attempt,
+ emailStage,
+ startedAt: dunning?.startedAt || now,
+ lastFailedAt: now,
+ nextRetryAt,
+ suspendsAt: shouldSuspendNow ? now : suspendsAt,
+ metadata: body,
+ }
+
+ if (updateUrl) {
+ await this.userService.update(user.id, { subUpdateURL: updateUrl })
+ }
+
+ if (cancelUrl) {
+ await this.userService.update(user.id, { subCancelURL: cancelUrl })
+ }
+
+ if (shouldSuspendNow) {
+ await this.userService.update(user.id, {
+ dashboardBlockReason: DashboardBlockReason.payment_failed,
+ isAccountBillingSuspended: true,
+ })
+ }
+
+ await this.userService.saveSubscriptionDunning(updateParams)
+ await this.projectService.clearProjectsRedisCache(user.id)
+
+ const billingUrl = updateUrl || this.getBillingUrl(user)
+
+ if (shouldSuspendNow) {
+ if (dunning?.emailStage !== BillingDunningEmailStage.locked) {
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.DashboardLockedPaymentFailure,
+ { billingUrl },
+ )
+ }
+
+ return
+ }
+
+ if (emailStage === BillingDunningEmailStage.final_warning) {
+ const alreadySentFinalNotice =
+ dunning?.emailStage &&
+ [
+ BillingDunningEmailStage.final_warning,
+ BillingDunningEmailStage.locked,
+ ].includes(dunning.emailStage)
+
+ if (!alreadySentFinalNotice) {
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.SubscriptionPaymentFinalWarning,
+ {
+ billingUrl,
+ suspendsAtFormatted: this.formatDateForEmail(suspendsAt),
+ },
+ )
+ }
+
+ return
+ }
+
+ const isNewFailure =
+ dunning?.subscriptionPaymentId !== paymentId ||
+ dunning?.attempt !== attempt ||
+ dunning?.emailStage !== BillingDunningEmailStage.payment_failed
+
+ if (isNewFailure) {
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.SubscriptionPaymentFailed,
+ {
+ billingUrl,
+ attempt,
+ amountFormatted: this.formatPaymentAmount(body),
+ nextRetryAtFormatted: this.formatDateForEmail(nextRetryAt),
+ },
+ )
+ }
+ }
+
+ private async notifyPaymentRecovered(
+ user: User,
+ dunning?: SubscriptionDunning | null,
+ ): Promise<void> {
+ const hadBillingIssue =
+ !!dunning ||
+ user.dashboardBlockReason === DashboardBlockReason.payment_failed ||
+ user.isAccountBillingSuspended
+
+ if (!hadBillingIssue) {
+ return
+ }
+
+ await this.mailerService.sendEmail(
+ user.email,
+ LetterTemplate.SubscriptionPaymentRecovered,
+ {
+ billingUrl: this.getBillingUrl(user),
+ },
+ )
+ }
+
private getSwetrixRevenueTransactionId(
body: Record<string, unknown>,
type: RevenueType,
@@ -363,24 +670,30 @@ export class WebhookController {
}
const isTrialing = status === 'trialing'
+ const isPaymentIssueStatus = ['past_due', 'paused'].includes(status)
const shouldUnlock =
status === 'active' ||
body.alert_name === 'subscription_created' ||
isNextPlan(currentUser.planCode, plan.id)
+ const currentDunning = isPaymentIssueStatus
+ ? null
+ : await this.userService.getOpenSubscriptionDunning(currentUser.id)
+ const shouldNotifyRecovered =
+ !isPaymentIssueStatus &&
+ (shouldUnlock || isTrialing) &&
+ (!!currentDunning ||
+ currentUser.dashboardBlockReason ===
+ DashboardBlockReason.payment_failed ||
+ currentUser.isAccountBillingSuspended)
const statusParams =
- status === 'paused'
+ !isPaymentIssueStatus && (shouldUnlock || isTrialing)
? {
- dashboardBlockReason: DashboardBlockReason.payment_failed,
- isAccountBillingSuspended: true,
+ dashboardBlockReason: null,
+ planExceedContactedAt: null,
+ isAccountBillingSuspended: false,
}
- : shouldUnlock || isTrialing
- ? {
- dashboardBlockReason: null,
- planExceedContactedAt: null,
- isAccountBillingSuspended: false,
- }
- : {}
+ : {}
const planType =
requestedPlanType === resolvedPlanType
@@ -410,14 +723,14 @@ export class WebhookController {
)
await this.projectService.clearProjectsRedisCache(currentUser.id)
- if (status === 'paused') {
- await this.mailerService.sendEmail(
- currentUser.email,
- LetterTemplate.DashboardLockedPaymentFailure,
- {
- billingUrl: 'https://swetrix.com/user-settings?tab=billing',
- },
+ if (isPaymentIssueStatus) {
+ await this.handlePaddlePaymentIssue(body, currentUser)
+ } else if (shouldNotifyRecovered) {
+ await this.userService.resolveOpenSubscriptionDunnings(
+ currentUser.id,
+ SubscriptionDunningStatus.recovered,
)
+ await this.notifyPaymentRecovered(currentUser, currentDunning)
}
break
@@ -433,6 +746,10 @@ export class WebhookController {
nextBillDate: null,
cancellationEffectiveDate,
})
+ await this.userService.resolveSubscriptionDunningsBySubID(
+ subID,
+ SubscriptionDunningStatus.cancelled,
+ )
const user = await this.userService.findOne({
where: { subID },
@@ -470,6 +787,12 @@ export class WebhookController {
break
}
+ case 'subscription_payment_failed': {
+ await this.handlePaddlePaymentIssue(body)
+
+ break
+ }
+
case 'subscription_payment_succeeded': {
const {
passthrough,
@@ -509,7 +832,15 @@ export class WebhookController {
return
}
+ const dunning = await this.userService.getOpenSubscriptionDunning(
+ subscriber.id,
+ )
const updateParams: Record<string, any> = {}
+ const shouldNotifyRecovered =
+ !!dunning ||
+ subscriber.dashboardBlockReason ===
+ DashboardBlockReason.payment_failed ||
+ subscriber.isAccountBillingSuspended
if (nextBillDate) {
updateParams.nextBillDate = nextBillDate
@@ -531,6 +862,14 @@ export class WebhookController {
await this.projectService.clearProjectsRedisCache(subscriber.id)
}
+ if (shouldNotifyRecovered) {
+ await this.userService.resolveOpenSubscriptionDunnings(
+ subscriber.id,
+ SubscriptionDunningStatus.recovered,
+ )
+ await this.notifyPaymentRecovered(subscriber, dunning)
+ }
+
break
}
diff --git a/backend/migrations/mysql/2026_06_18_billing_dunning.sql b/backend/migrations/mysql/2026_06_18_billing_dunning.sql
new file mode 100644
index 000000000..5ac5a6f95
--- /dev/null
+++ b/backend/migrations/mysql/2026_06_18_billing_dunning.sql
@@ -0,0 +1,23 @@
+CREATE TABLE `subscription_dunning` (
+ `id` varchar(36) NOT NULL,
+ `userId` varchar(36) NOT NULL,
+ `subID` varchar(32) DEFAULT NULL,
+ `subscriptionPaymentId` varchar(80) DEFAULT NULL,
+ `status` enum('active','recovered','locked','cancelled') NOT NULL DEFAULT 'active',
+ `attempt` int NOT NULL DEFAULT '1',
+ `emailStage` enum('payment_failed','final_warning','locked') DEFAULT NULL,
+ `startedAt` timestamp NULL DEFAULT NULL,
+ `lastFailedAt` timestamp NULL DEFAULT NULL,
+ `nextRetryAt` timestamp NULL DEFAULT NULL,
+ `suspendsAt` timestamp NULL DEFAULT NULL,
+ `resolvedAt` timestamp NULL DEFAULT NULL,
+ `metadata` json DEFAULT NULL,
+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ `updatedAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
+ PRIMARY KEY (`id`),
+ KEY `IDX_subscription_dunning_user_status` (`userId`,`status`),
+ KEY `IDX_subscription_dunning_sub_status` (`subID`,`status`),
+ KEY `IDX_subscription_dunning_payment` (`subscriptionPaymentId`),
+ KEY `IDX_subscription_dunning_suspends_status` (`suspendsAt`,`status`),
+ CONSTRAINT `FK_subscription_dunning_user` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;