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!

Track Swetrix revenue with Swetrix

Blue Mouse05747bd3de0d
diff --git a/backend/apps/cloud/src/user/dto/change-plan.dto.ts b/backend/apps/cloud/src/user/dto/change-plan.dto.ts
index 55380b84e..0e4d1cb63 100644
--- a/backend/apps/cloud/src/user/dto/change-plan.dto.ts
+++ b/backend/apps/cloud/src/user/dto/change-plan.dto.ts
@@ -1,5 +1,11 @@
import { ApiProperty } from '@nestjs/swagger'
-import { IsIn, IsNumber, IsOptional } from 'class-validator'
+import {
+ IsIn,
+ IsNumber,
+ IsOptional,
+ IsString,
+ MaxLength,
+} from 'class-validator'
const PLAN_TYPES = ['standard', 'plus', 'enterprise'] as const
const EVENT_TIERS = [
@@ -31,4 +37,16 @@ export class IChangePlanDTO {
@IsOptional()
@IsIn(EVENT_TIERS)
eventTier?: string
+
+ @ApiProperty({ example: 'usr_12345', required: false })
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ swetrixProfileId?: string
+
+ @ApiProperty({ example: '123456789', required: false })
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ swetrixSessionId?: string
}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 26e6eccf1..f85233267 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -869,10 +869,23 @@ export class UserController {
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
): Promise<void> {
- this.logger.log({ body, id }, 'POST /change-plan')
- const { planId, planType } = body
+ const { planId, planType, swetrixProfileId, swetrixSessionId } = body
+
+ this.logger.log(
+ {
+ id,
+ planId,
+ planType,
+ hasSwetrixProfileId: !!swetrixProfileId,
+ hasSwetrixSessionId: !!swetrixSessionId,
+ },
+ 'POST /change-plan',
+ )
- await this.userService.updateSubscription(id, planId, planType)
+ await this.userService.updateSubscription(id, planId, planType, {
+ swetrixProfileId,
+ swetrixSessionId,
+ })
await this.projectService.clearProjectsRedisCache(id)
}
@@ -882,12 +895,26 @@ export class UserController {
@CurrentUserId() id: string,
@Body() body: IChangePlanDTO,
): Promise<any> {
- this.logger.log({ body, id }, 'POST /generate-pay-link')
- const { planId, planType, eventTier } = body
+ const { planId, planType, eventTier, swetrixProfileId, swetrixSessionId } =
+ body
+
+ this.logger.log(
+ {
+ id,
+ planId,
+ planType,
+ eventTier,
+ hasSwetrixProfileId: !!swetrixProfileId,
+ hasSwetrixSessionId: !!swetrixSessionId,
+ },
+ 'POST /generate-pay-link',
+ )
return this.userService.generatePayLink(id, planId, {
planType,
eventTier,
+ swetrixProfileId,
+ swetrixSessionId,
})
}
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index f28f9c46f..1216368ba 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -2640,6 +2640,10 @@ export class UserService {
id: string,
planID: number,
requestedPlanType?: string | null,
+ context: {
+ swetrixProfileId?: string | null
+ swetrixSessionId?: string | null
+ } = {},
) {
const user = await this.findOne({ where: { id } })
const plan = this.getPlanById(planID, requestedPlanType)
@@ -2684,6 +2688,8 @@ export class UserService {
passthrough: JSON.stringify({
uid: id,
planType,
+ swetrix_profile_id: context.swetrixProfileId || null,
+ swetrix_session_id: context.swetrixSessionId || null,
}),
}),
})
@@ -2724,7 +2730,12 @@ export class UserService {
async generatePayLink(
id: string,
productId: number,
- context: { planType?: string | null; eventTier?: string | null } = {},
+ context: {
+ planType?: string | null
+ eventTier?: string | null
+ swetrixProfileId?: string | null
+ swetrixSessionId?: string | null
+ } = {},
) {
const user = await this.findOne({ where: { id } })
if (!user) {
@@ -2755,6 +2766,8 @@ export class UserService {
uid: id,
planType: plan.planType,
eventTier: context.eventTier || null,
+ swetrix_profile_id: context.swetrixProfileId || null,
+ swetrix_session_id: context.swetrixSessionId || null,
}),
...(isTrial
? {
diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.ts
index 8b71f5691..df83a9f12 100644
--- a/backend/apps/cloud/src/webhook/webhook.controller.ts
+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts
@@ -23,6 +23,13 @@ import { AppLoggerService } from '../logger/logger.service'
import { WebhookService } from './webhook.service'
import { LetterTemplate } from '../mailer/letter'
import { MailerService } from '../mailer/mailer.service'
+import { RevenueService } from '../revenue/revenue.service'
+import { CurrencyService } from '../revenue/currency.service'
+import {
+ RevenueProvider,
+ RevenueStatus,
+ RevenueType,
+} from '../revenue/interfaces/revenue.interface'
@ApiTags('Webhook')
@Controller('webhook')
@@ -33,8 +40,221 @@ export class WebhookController {
private readonly webhookService: WebhookService,
private readonly projectService: ProjectService,
private readonly mailerService: MailerService,
+ private readonly revenueService: RevenueService,
+ private readonly currencyService: CurrencyService,
) {}
+ private getPaddleField(
+ body: Record<string, unknown>,
+ fields: string[],
+ ): string | null {
+ for (const field of fields) {
+ const value = body[field]
+
+ if (value !== undefined && value !== null && String(value) !== '') {
+ return String(value)
+ }
+ }
+
+ return null
+ }
+
+ private getPaddleAmount(
+ body: Record<string, unknown>,
+ fields: string[],
+ ): number | null {
+ const rawAmount = this.getPaddleField(body, fields)
+
+ if (!rawAmount) {
+ return null
+ }
+
+ const amount = Number(rawAmount.replace(/,/g, ''))
+
+ return Number.isFinite(amount) && amount !== 0 ? Math.abs(amount) : null
+ }
+
+ private getPaddlePassthrough(
+ body: Record<string, unknown>,
+ ): Record<string, unknown> {
+ const passthrough = this.getPaddleField(body, ['passthrough'])
+
+ if (!passthrough) {
+ return {}
+ }
+
+ try {
+ const parsed = JSON.parse(passthrough)
+
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? parsed
+ : {}
+ } catch {
+ return {}
+ }
+ }
+
+ private getPaddleCreatedAt(body: Record<string, unknown>): Date {
+ const eventTime = this.getPaddleField(body, ['event_time'])
+
+ if (!eventTime) {
+ return new Date()
+ }
+
+ const date = new Date(
+ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(eventTime)
+ ? `${eventTime.replace(' ', 'T')}Z`
+ : eventTime,
+ )
+
+ return isNaN(date.getTime()) ? new Date() : date
+ }
+
+ private getSwetrixRevenueTransactionId(
+ body: Record<string, unknown>,
+ type: RevenueType,
+ ): string | null {
+ const id =
+ type === RevenueType.REFUND
+ ? this.getPaddleField(body, [
+ 'alert_id',
+ 'refund_id',
+ 'subscription_payment_id',
+ 'payment_id',
+ 'order_id',
+ 'checkout_id',
+ ])
+ : this.getPaddleField(body, [
+ 'subscription_payment_id',
+ 'payment_id',
+ 'order_id',
+ 'checkout_id',
+ 'alert_id',
+ ])
+
+ if (!id) {
+ return null
+ }
+
+ return `paddle:${body.alert_name}:${id}`
+ }
+
+ private async trackSwetrixRevenue(
+ body: Record<string, unknown>,
+ type: RevenueType,
+ ): Promise<void> {
+ const pid = process.env.SWETRIX_PID
+
+ if (!pid) {
+ return
+ }
+
+ try {
+ const amount = this.getPaddleAmount(
+ body,
+ type === RevenueType.REFUND
+ ? ['amount', 'refund_amount', 'sale_gross', 'balance_gross']
+ : ['sale_gross', 'amount', 'balance_gross', 'unit_price'],
+ )
+ const originalCurrency = this.getPaddleField(body, [
+ 'currency',
+ 'balance_currency',
+ ])?.toUpperCase()
+ const transactionId = this.getSwetrixRevenueTransactionId(body, type)
+
+ if (!amount || !originalCurrency || !transactionId) {
+ this.logger.warn(
+ {
+ alertName: body.alert_name,
+ hasAmount: !!amount,
+ hasCurrency: !!originalCurrency,
+ hasTransactionId: !!transactionId,
+ },
+ 'Skipping Swetrix revenue tracking for Paddle webhook',
+ )
+ return
+ }
+
+ const project = await this.projectService.getFullProject(pid)
+
+ if (!project) {
+ this.logger.warn({ pid }, 'Skipping Swetrix revenue tracking')
+ return
+ }
+
+ if (project.paddleApiKeyEnc || project.stripeApiKeyEnc) {
+ this.logger.warn(
+ { pid, alertName: body.alert_name },
+ 'Skipping Swetrix revenue webhook because a revenue provider is already connected',
+ )
+ return
+ }
+
+ const targetCurrency = project.revenueCurrency || originalCurrency
+
+ if (!project.revenueApiEnabled) {
+ const result = await this.revenueService.connectApi(pid, targetCurrency)
+
+ if (!result.success) {
+ this.logger.warn(
+ { pid, reason: result.message },
+ 'Failed to enable Swetrix API revenue tracking',
+ )
+ return
+ }
+ }
+
+ const passthrough = this.getPaddlePassthrough(body)
+ const convertedAmount = await this.currencyService.convert(
+ amount,
+ originalCurrency,
+ targetCurrency,
+ )
+ const isRefund = type === RevenueType.REFUND
+
+ await this.revenueService.insertTransaction({
+ pid,
+ transactionId,
+ provider: RevenueProvider.API,
+ type,
+ status: isRefund ? RevenueStatus.REFUNDED : RevenueStatus.COMPLETED,
+ amount: isRefund ? -Math.abs(convertedAmount) : convertedAmount,
+ originalAmount: isRefund ? -Math.abs(amount) : amount,
+ originalCurrency,
+ currency: targetCurrency,
+ profileId:
+ this.getPaddleField(passthrough, ['swetrix_profile_id']) || null,
+ sessionId:
+ this.getPaddleField(passthrough, ['swetrix_session_id']) || null,
+ productId: this.getPaddleField(body, ['subscription_plan_id']) || null,
+ productName:
+ this.getPaddleField(body, [
+ 'plan_name',
+ 'product_name',
+ 'checkout_title',
+ ]) || (isRefund ? 'Refund' : 'Swetrix subscription'),
+ metadata: {
+ alertName: body.alert_name,
+ checkoutId: body.checkout_id,
+ orderId: body.order_id,
+ subscriptionId: body.subscription_id,
+ subscriptionPlanId: body.subscription_plan_id,
+ userId: body.user_id,
+ passthrough,
+ },
+ created: this.getPaddleCreatedAt(body),
+ syncedAt: new Date(),
+ })
+
+ await this.revenueService.updateLastSyncAt(pid)
+ } catch (error) {
+ this.logger.error(
+ { error, alertName: body.alert_name },
+ 'Failed to track Swetrix revenue from Paddle webhook',
+ )
+ }
+ }
+
// AWS SNS webhook
@Post('/sns')
@HttpCode(200)
@@ -251,6 +471,12 @@ export class WebhookController {
break
}
+ case 'payment_succeeded': {
+ await this.trackSwetrixRevenue(body, RevenueType.SALE)
+
+ break
+ }
+
case 'subscription_payment_succeeded': {
const {
passthrough,
@@ -267,6 +493,8 @@ export class WebhookController {
)
}
+ await this.trackSwetrixRevenue(body, RevenueType.SUBSCRIPTION)
+
let subscriber = await this.userService.findOne({
where: { subID },
})
@@ -313,6 +541,13 @@ export class WebhookController {
break
}
+ case 'payment_refunded':
+ case 'subscription_payment_refunded': {
+ await this.trackSwetrixRevenue(body, RevenueType.REFUND)
+
+ break
+ }
+
default:
throw new BadRequestException('Unexpected event type')
}
diff --git a/backend/apps/cloud/src/webhook/webhook.module.ts b/backend/apps/cloud/src/webhook/webhook.module.ts
index 3c0de4690..89102ac08 100644
--- a/backend/apps/cloud/src/webhook/webhook.module.ts
+++ b/backend/apps/cloud/src/webhook/webhook.module.ts
@@ -6,6 +6,7 @@ import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
import { MailerModule } from '../mailer/mailer.module'
import { WebhookService } from './webhook.service'
+import { RevenueModule } from '../revenue/revenue.module'
@Module({
imports: [
@@ -13,6 +14,7 @@ import { WebhookService } from './webhook.service'
ProjectModule,
AppLoggerModule,
MailerModule,
+ RevenueModule,
],
providers: [WebhookService],
exports: [WebhookService],
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsx
index c8aaaf53d..c227584af 100644
--- a/web/app/components/pricing/BillingPricing.tsx
+++ b/web/app/components/pricing/BillingPricing.tsx
@@ -36,6 +36,7 @@ import { Link } from '~/ui/Link'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
+import { getRevenueAttribution } from '~/utils/analytics'
import routes from '~/utils/routes'
interface BillingPricingProps {
@@ -264,6 +265,23 @@ const BillingPricing = ({
}
}
+ const submitWithRevenueAttribution = (
+ formData: FormData,
+ submit: (formData: FormData) => void,
+ ) => {
+ getRevenueAttribution().then((attribution) => {
+ if (attribution.swetrixProfileId) {
+ formData.set('swetrixProfileId', attribution.swetrixProfileId)
+ }
+
+ if (attribution.swetrixSessionId) {
+ formData.set('swetrixSessionId', attribution.swetrixSessionId)
+ }
+
+ submit(formData)
+ })
+ }
+
const submitSelection = (
intent:
| 'preview-subscription-update'
@@ -284,14 +302,18 @@ const BillingPricing = ({
action: '/user-settings',
})
} else if (intent === 'change-subscription-plan') {
- changePlanFetcher.submit(formData, {
- method: 'POST',
- action: '/user-settings',
+ submitWithRevenueAttribution(formData, (formData) => {
+ changePlanFetcher.submit(formData, {
+ method: 'POST',
+ action: '/user-settings',
+ })
})
} else {
- generatePayLinkFetcher.submit(formData, {
- method: 'POST',
- action: '/user-settings',
+ submitWithRevenueAttribution(formData, (formData) => {
+ generatePayLinkFetcher.submit(formData, {
+ method: 'POST',
+ action: '/user-settings',
+ })
})
}
}
diff --git a/web/app/pages/Subscribe/Subscribe.tsx b/web/app/pages/Subscribe/Subscribe.tsx
index ef6527c61..d8a5cf364 100644
--- a/web/app/pages/Subscribe/Subscribe.tsx
+++ b/web/app/pages/Subscribe/Subscribe.tsx
@@ -22,7 +22,7 @@ import type { SubscribeLoaderData } from '~/routes/subscribe'
import type { UserSettingsActionData } from '~/routes/user-settings'
import { FAQ } from '~/ui/FAQ'
import { Text } from '~/ui/Text'
-import { trackCustom } from '~/utils/analytics'
+import { getRevenueAttribution, trackCustom } from '~/utils/analytics'
import routes from '~/utils/routes'
import { TrialTimeline } from './TrialTimeline'
@@ -173,7 +173,7 @@ const Subscribe = () => {
theme,
])
- const handlePlanSelection = (selection: MarketingPricingSelection) => {
+ const handlePlanSelection = async (selection: MarketingPricingSelection) => {
if (
checkoutInProgressRef.current ||
selectionLoading ||
@@ -220,6 +220,8 @@ const Subscribe = () => {
}
setSelectionLoading(selection)
+ const attribution = await getRevenueAttribution()
+
generatePayLinkFetcher.submit(
{
intent: 'generate-pay-link',
@@ -227,6 +229,7 @@ const Subscribe = () => {
eventTier: selection.eventTier,
billingFrequency: selection.billingFrequency,
currency: selection.currency,
+ ...attribution,
},
{ method: 'POST', action: '/user-settings' },
)
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index 263cadb35..604a15569 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -210,6 +210,16 @@ const resolveCatalogSelection = (formData: FormData) => {
return { planId }
}
+const resolveRevenueAttribution = (formData: FormData) => {
+ const swetrixProfileId = formData.get('swetrixProfileId')?.toString()
+ const swetrixSessionId = formData.get('swetrixSessionId')?.toString()
+
+ return {
+ ...(swetrixProfileId ? { swetrixProfileId } : {}),
+ ...(swetrixSessionId ? { swetrixSessionId } : {}),
+ }
+}
+
export async function action({ request }: ActionFunctionArgs) {
redirectIfNotAuthenticated(request)
@@ -755,7 +765,10 @@ export async function action({ request }: ActionFunctionArgs) {
'user/generate-pay-link',
{
method: 'POST',
- body: selection,
+ body: {
+ ...selection,
+ ...resolveRevenueAttribution(formData),
+ },
},
)
@@ -784,7 +797,10 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await serverFetch(request, 'user/change-plan', {
method: 'POST',
- body: selection,
+ body: {
+ ...selection,
+ ...resolveRevenueAttribution(formData),
+ },
})
if (result.error) {
diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.ts
index 4eb9acf7d..5d5f9b5bb 100644
--- a/web/app/utils/analytics.ts
+++ b/web/app/utils/analytics.ts
@@ -1,6 +1,8 @@
import _includes from 'lodash/includes'
import {
init,
+ getProfileId,
+ getSessionId,
startSessionReplay,
track,
trackError as swetrixTrackError,
@@ -228,3 +230,27 @@ export const trackCustom = (ev: string, meta?: TrackEventOptions['meta']) => {
console.error('Failed to track custom event:', reason)
})
}
+
+export const getRevenueAttribution = async (): Promise<{
+ swetrixProfileId?: string
+ swetrixSessionId?: string
+}> => {
+ if (isSelfhosted || !isBrowser || isIframe) {
+ return {}
+ }
+
+ try {
+ const [profileId, sessionId] = await Promise.all([
+ getProfileId(),
+ getSessionId(),
+ ])
+
+ return {
+ ...(profileId ? { swetrixProfileId: profileId } : {}),
+ ...(sessionId ? { swetrixSessionId: sessionId } : {}),
+ }
+ } catch (reason) {
+ console.error('Failed to get revenue attribution:', reason)
+ return {}
+ }
+}