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!

Generate payment links server-side

Blue Mouseaef890ce403a
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index 72e22c6cb..d689dfdf6 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -27,11 +27,7 @@ import {
import { ActionTokensService } from '../action-tokens/action-tokens.service'
import { LetterTemplate } from '../mailer/letter'
import { MailerService } from '../mailer/mailer.service'
-import {
- MAX_EMAIL_REQUESTS,
- User,
- TRIAL_DURATION,
-} from '../user/entities/user.entity'
+import { MAX_EMAIL_REQUESTS, User } from '../user/entities/user.entity'
import { UserService } from '../user/user.service'
import { ProjectService } from '../project/project.service'
import {
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 4af25a192..22d7d0185 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -44,8 +44,6 @@ interface PlanSignature {
legacy?: boolean
pid?: string
ypid?: string
- legacyPids?: string[]
- legacyYpids?: string[]
}
export const ACCOUNT_PLANS = {
@@ -75,8 +73,6 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 10000,
pid: '813694',
ypid: '813695',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode['50k']]: {
@@ -84,8 +80,6 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 50000,
pid: '918109',
ypid: '918110',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode.freelancer]: {
@@ -93,44 +87,34 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 100000,
pid: '752316',
ypid: '776469',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode['100k']]: {
id: PlanCode['100k'],
monthlyUsageLimit: 100000,
- pid: '922473',
- ypid: '922474',
- legacyPids: ['916455'],
- legacyYpids: ['916456'],
+ pid: '916455',
+ ypid: '916456',
maxAlerts: 50,
},
[PlanCode['200k']]: {
id: PlanCode['200k'],
monthlyUsageLimit: 200000,
- pid: '922471',
- ypid: '922472',
- legacyPids: ['854654'],
- legacyYpids: ['854655'],
+ pid: '854654',
+ ypid: '854655',
maxAlerts: 50,
},
[PlanCode['500k']]: {
id: PlanCode['500k'],
monthlyUsageLimit: 500000,
- pid: '922470',
+ pid: '854656',
ypid: '854657',
- legacyPids: ['854656'],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode.startup]: {
id: PlanCode.startup,
monthlyUsageLimit: 1000000,
- pid: '922469',
+ pid: '752317',
ypid: '776470',
- legacyPids: ['752317'],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode['2m']]: {
@@ -138,26 +122,20 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 2000000,
pid: '854663',
ypid: '854664',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode.enterprise]: {
id: PlanCode.enterprise,
monthlyUsageLimit: 5000000,
- pid: '922468',
+ pid: '752318',
ypid: '776471',
- legacyPids: ['752318'],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode['10m']]: {
id: PlanCode['10m'],
monthlyUsageLimit: 10000000,
pid: '854665',
- ypid: '922467',
- legacyPids: [],
- legacyYpids: ['854666'],
+ ypid: '854666',
maxAlerts: 50,
},
[PlanCode['15m']]: {
@@ -165,8 +143,6 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 15000000,
pid: '916451',
ypid: '916452',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
[PlanCode['20m']]: {
@@ -174,8 +150,6 @@ export const ACCOUNT_PLANS = {
monthlyUsageLimit: 20000000,
pid: '916453',
ypid: '916454',
- legacyPids: [],
- legacyYpids: [],
maxAlerts: 50,
},
}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 1a1edb006..e37e9463d 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -723,6 +723,18 @@ export class UserController {
await this.projectService.clearProjectsRedisCache(id)
}
+ @ApiBearerAuth()
+ @Post('generate-pay-link')
+ async generatePayLink(
+ @CurrentUserId() id: string,
+ @Body() body: IChangePlanDTO,
+ ): Promise<any> {
+ this.logger.log({ body, id }, 'POST /generate-pay-link')
+ const { planId } = body
+
+ return this.userService.generatePayLink(id, planId)
+ }
+
@ApiBearerAuth()
@Post('preview-plan')
async previewPlan(
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 50c93d69e..8cab7f517 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -341,11 +341,7 @@ export class UserService {
// @ts-ignore
tier.pid === stringifiedPlanId ||
// @ts-ignore
- tier.ypid === stringifiedPlanId ||
- // @ts-ignore
- tier.legacyPids?.includes(stringifiedPlanId) ||
- // @ts-ignore
- tier.legacyYpids?.includes(stringifiedPlanId),
+ tier.ypid === stringifiedPlanId,
)
// @ts-ignore
@@ -354,9 +350,7 @@ export class UserService {
// @ts-ignore
const isMonthly =
// @ts-ignore
- plan.pid === stringifiedPlanId ||
- // @ts-ignore
- plan.legacyPids?.includes(stringifiedPlanId)
+ plan.pid === stringifiedPlanId
const billingFrequency = isMonthly
? BillingFrequency.Monthly
@@ -566,6 +560,43 @@ export class UserService {
await this.update(id, updateParams)
}
+ async generatePayLink(id: string, productId: number) {
+ const user = await this.findOne({ where: { id } })
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ const url = 'https://vendors.paddle.com/api/2.0/product/generate_pay_link'
+
+ let result: any = {}
+
+ try {
+ result = await axios.post(url, {
+ vendor_id: Number(PADDLE_VENDOR_ID),
+ vendor_auth_code: PADDLE_API_KEY,
+ product_id: productId,
+ customer_email: user.email,
+ passthrough: JSON.stringify({ uid: id }),
+ ...(user.trialEndDate ? {} : { trial_days: TRIAL_DURATION }),
+ })
+ } catch (error) {
+ console.error(
+ '[ERROR] (generatePayLink):',
+ error?.response?.data?.error?.message || error,
+ )
+ throw new BadRequestException('Something went wrong')
+ }
+
+ const { data } = result
+
+ if (!data.success) {
+ console.error('[ERROR] (generatePayLink) success -> false:', result.data)
+ throw new InternalServerErrorException('Something went wrong')
+ }
+
+ return { url: data.response.url }
+ }
+
createUnsubscribeKey(userId: string): string {
const base64 = CryptoJS.Rabbit.encrypt(
userId,
diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.ts
index 52244748f..27928352d 100644
--- a/backend/apps/cloud/src/webhook/webhook.controller.ts
+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts
@@ -113,23 +113,11 @@ export class WebhookController {
let monthlyBilling = true
let plan = _find(ACCOUNT_PLANS, ({ pid }) => pid === subscriptionPlanId)
- if (!plan) {
- plan = _find(ACCOUNT_PLANS, (tier) =>
- (tier as any).legacyPids?.includes(subscriptionPlanId),
- )
- }
-
if (!plan) {
monthlyBilling = false
plan = _find(ACCOUNT_PLANS, ({ ypid }) => ypid === subscriptionPlanId)
}
- if (!plan) {
- plan = _find(ACCOUNT_PLANS, (tier) =>
- (tier as any).legacyYpids?.includes(subscriptionPlanId),
- )
- }
-
if (!plan) {
throw new NotFoundException(
`The selected account plan (${subscriptionPlanId}) is not available`,
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsx
index ac06a70d4..fd677c0ff 100644
--- a/web/app/components/pricing/BillingPricing.tsx
+++ b/web/app/components/pricing/BillingPricing.tsx
@@ -54,8 +54,10 @@ const BillingPricing = ({
const previewFetcher = useFetcher<UserSettingsActionData>()
const changePlanFetcher = useFetcher<UserSettingsActionData>()
+ const generatePayLinkFetcher = useFetcher<UserSettingsActionData>()
const [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)
+ const [loadingTier, setLoadingTier] = useState<any>(null)
const [
isNewPlanConfirmationModalOpened,
setIsNewPlanConfirmationModalOpened,
@@ -131,6 +133,42 @@ const BillingPricing = ({
}
}, [previewFetcher.data?.error])
+ // Handle generate pay link fetcher response
+ useEffect(() => {
+ if (
+ generatePayLinkFetcher.data?.success &&
+ generatePayLinkFetcher.data?.data
+ ) {
+ const url = (generatePayLinkFetcher.data.data as any).url
+
+ const opened = openCheckout({
+ override: url,
+ locale: paddleLanguageMapping[language] || language,
+ title: loadingTier?.name,
+ displayModeTheme: theme,
+ country: metainfo.country,
+ })
+
+ if (!opened) {
+ toast.error(t('billing.paddleStillLoading'))
+ setPlanCodeLoading(null)
+ setLoadingTier(null)
+ }
+
+ // Clear data to prevent infinite loops if re-rendering occurs
+ generatePayLinkFetcher.data = undefined
+ } else if (generatePayLinkFetcher.data?.error) {
+ console.error(
+ '[ERROR] An error occured while generating pay link:',
+ generatePayLinkFetcher.data.error,
+ )
+ toast.error('An error occured while preparing checkout')
+ setPlanCodeLoading(null)
+ setLoadingTier(null)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [generatePayLinkFetcher.data])
+
const PLAN_CODES_ARRAY = useMemo(() => {
let basePlans = STANDARD_PLANS
@@ -209,23 +247,16 @@ const BillingPricing = ({
}
setPlanCodeLoading(tier.planCode)
+ setLoadingTier(tier)
- const opened = openCheckout({
- product:
- billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
- email: user.email,
- passthrough: JSON.stringify({ uid: user.id }),
- locale: paddleLanguageMapping[language] || language,
- title: tier.name,
- displayModeTheme: theme,
- country: metainfo.country,
- })
-
- if (!opened) {
- toast.error(t('billing.paddleStillLoading'))
- setPlanCodeLoading(null)
- return
- }
+ const planId = Number(
+ billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
+ )
+
+ generatePayLinkFetcher.submit(
+ { intent: 'generate-pay-link', planId: String(planId) },
+ { method: 'POST', action: '/user-settings' },
+ )
}
const closeUpdateModal = (force?: boolean) => {
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 3dd931904..a7c1eed4d 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -641,8 +641,6 @@ export const PLAN_LIMITS = {
},
pid: 813694, // plan ID
ypid: 813695, // yearly plan ID
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
'50k': {
@@ -666,8 +664,6 @@ export const PLAN_LIMITS = {
},
pid: 918109,
ypid: 918110,
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
freelancer: {
@@ -691,8 +687,6 @@ export const PLAN_LIMITS = {
},
pid: 752316,
ypid: 776469,
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
'100k': {
@@ -714,10 +708,8 @@ export const PLAN_LIMITS = {
yearly: 150,
},
},
- pid: 922473,
- ypid: 922474,
- legacyPids: [916455] as number[],
- legacyYpids: [916456] as number[],
+ pid: 916455,
+ ypid: 916456,
maxAlerts: 50,
},
'200k': {
@@ -739,10 +731,8 @@ export const PLAN_LIMITS = {
yearly: 230,
},
},
- pid: 922471,
- ypid: 922472,
- legacyPids: [854654] as number[],
- legacyYpids: [854655] as number[],
+ pid: 854654,
+ ypid: 854655,
maxAlerts: 50,
},
'500k': {
@@ -764,10 +754,8 @@ export const PLAN_LIMITS = {
yearly: 390,
},
},
- pid: 922470,
+ pid: 854656,
ypid: 854657,
- legacyPids: [854656] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
startup: {
@@ -789,10 +777,8 @@ export const PLAN_LIMITS = {
yearly: 590,
},
},
- pid: 922469,
+ pid: 752317,
ypid: 776470,
- legacyPids: [752317] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
'2m': {
@@ -816,8 +802,6 @@ export const PLAN_LIMITS = {
},
pid: 854663,
ypid: 854664,
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
enterprise: {
@@ -839,10 +823,8 @@ export const PLAN_LIMITS = {
yearly: 1390,
},
},
- pid: 922468,
+ pid: 752318,
ypid: 776471,
- legacyPids: [752318] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
'10m': {
@@ -865,9 +847,7 @@ export const PLAN_LIMITS = {
},
},
pid: 854665,
- ypid: 922467,
- legacyPids: [] as number[],
- legacyYpids: [854666] as number[],
+ ypid: 854666,
maxAlerts: 50,
},
'15m': {
@@ -891,8 +871,6 @@ export const PLAN_LIMITS = {
},
pid: 916451,
ypid: 916452,
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
'20m': {
@@ -916,8 +894,6 @@ export const PLAN_LIMITS = {
},
pid: 916453,
ypid: 916454,
- legacyPids: [] as number[],
- legacyYpids: [] as number[],
maxAlerts: 50,
},
}
diff --git a/web/app/pages/Subscribe/Subscribe.tsx b/web/app/pages/Subscribe/Subscribe.tsx
index c1129fb4e..330c72a40 100644
--- a/web/app/pages/Subscribe/Subscribe.tsx
+++ b/web/app/pages/Subscribe/Subscribe.tsx
@@ -7,7 +7,7 @@ import {
} from '@phosphor-icons/react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import { useNavigate, useLoaderData } from 'react-router'
+import { useFetcher, useNavigate, useLoaderData } from 'react-router'
import { toast } from 'sonner'
import { usePaddle } from '~/hooks/usePaddle'
@@ -104,6 +104,41 @@ const Subscribe = () => {
}
}, [hasCompletedCheckout, navigate, loadUser])
+ const generatePayLinkFetcher = useFetcher<any>()
+
+ // Handle generate pay link fetcher response
+ useEffect(() => {
+ if (
+ generatePayLinkFetcher.data?.success &&
+ generatePayLinkFetcher.data?.data
+ ) {
+ const url = generatePayLinkFetcher.data.data.url
+
+ const opened = openCheckout({
+ override: url,
+ locale: paddleLanguageMapping[i18n.language] || i18n.language,
+ displayModeTheme: theme,
+ country: metainfo.country,
+ })
+
+ if (!opened) {
+ toast.error(t('apiNotifications.somethingWentWrong'))
+ }
+
+ // Clear data
+ generatePayLinkFetcher.data = undefined
+ } else if (generatePayLinkFetcher.data?.error) {
+ toast.error('An error occured while preparing checkout')
+ }
+ }, [
+ generatePayLinkFetcher.data,
+ openCheckout,
+ i18n.language,
+ theme,
+ metainfo.country,
+ t,
+ ])
+
const handleStartCheckout = () => {
if (paddleLoadError) {
toast.error(t('billing.paddleLoadError'))
@@ -134,18 +169,10 @@ const Subscribe = () => {
return
}
- const opened = openCheckout({
- product,
- email: user?.email,
- passthrough: JSON.stringify({ uid: user?.id }),
- locale: paddleLanguageMapping[i18n.language] || i18n.language,
- displayModeTheme: theme,
- country: metainfo.country,
- })
-
- if (!opened) {
- toast.error(t('apiNotifications.somethingWentWrong'))
- }
+ generatePayLinkFetcher.submit(
+ { intent: 'generate-pay-link', planId: String(product) },
+ { method: 'POST', action: '/user-settings' },
+ )
}
const trialEndDate = user?.trialEndDate
@@ -353,6 +380,8 @@ const Subscribe = () => {
onClick={handleStartCheckout}
primary
giant
+ loading={generatePayLinkFetcher.state !== 'idle'}
+ disabled={generatePayLinkFetcher.state !== 'idle'}
>
{t('checkout.next')}
</Button>
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 185c3f1af..1b77e84b6 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -289,7 +289,6 @@ const UserSettings = () => {
planCode,
subUpdateURL,
trialEndDate,
- timeFormat: userTimeFormat,
cancellationEffectiveDate,
subCancelURL,
maxEventsCount = 0,
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index 22f471c3c..8c761f39e 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -503,6 +503,42 @@ export async function action({ request }: ActionFunctionArgs) {
)
}
+ case 'generate-pay-link': {
+ const planId = Number(formData.get('planId'))
+
+ if (
+ !Number.isFinite(planId) ||
+ planId <= 0 ||
+ !Number.isInteger(planId)
+ ) {
+ return data<UserSettingsActionData>(
+ { intent, error: 'Invalid planId' },
+ { status: 400 },
+ )
+ }
+
+ const result = await serverFetch<{ url: string }>(
+ request,
+ 'user/generate-pay-link',
+ {
+ method: 'POST',
+ body: { planId },
+ },
+ )
+
+ if (result.error) {
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
case 'change-subscription-plan': {
const planId = Number(formData.get('planId'))