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!

Add usePaddle hook

Blue Mousef0fc2eac7e2d
diff --git a/web/app/hooks/usePaddle.ts b/web/app/hooks/usePaddle.ts
new file mode 100644
index 000000000..afbf8ca96
--- /dev/null
+++ b/web/app/hooks/usePaddle.ts
@@ -0,0 +1,54 @@
+import { useEffect, useRef, useState } from 'react'
+
+import { PADDLE_JS_URL, PADDLE_VENDOR_ID } from '~/lib/constants'
+import { loadScript } from '~/utils/generic'
+
+const POLL_INTERVAL_MS = 200
+const MAX_ATTEMPTS = 50 // 10 seconds
+
+interface UsePaddleOptions {
+ onEvent?: (eventData: any) => void
+}
+
+interface UsePaddleResult {
+ isPaddleLoaded: boolean
+ paddleLoadError: boolean
+}
+
+export function usePaddle(options: UsePaddleOptions = {}): UsePaddleResult {
+ const [isPaddleLoaded, setIsPaddleLoaded] = useState(false)
+ const [paddleLoadError, setPaddleLoadError] = useState(false)
+ const onEventRef = useRef(options.onEvent)
+ onEventRef.current = options.onEvent
+
+ useEffect(() => {
+ loadScript(PADDLE_JS_URL)
+
+ let attempts = 0
+
+ const interval = setInterval(() => {
+ attempts += 1
+
+ if ((window as any)?.Paddle) {
+ ;(window as any).Paddle.Setup({
+ vendor: PADDLE_VENDOR_ID,
+ eventCallback: (eventData: any) => {
+ onEventRef.current?.(eventData)
+ },
+ })
+ setIsPaddleLoaded(true)
+ clearInterval(interval)
+ return
+ }
+
+ if (attempts >= MAX_ATTEMPTS) {
+ setPaddleLoadError(true)
+ clearInterval(interval)
+ }
+ }, POLL_INTERVAL_MS)
+
+ return () => clearInterval(interval)
+ }, [])
+
+ return { isPaddleLoaded, paddleLoadError }
+}
diff --git a/web/app/pages/Checkout/Checkout.tsx b/web/app/pages/Checkout/Checkout.tsx
index 09f0a107d..4a7ef8b67 100644
--- a/web/app/pages/Checkout/Checkout.tsx
+++ b/web/app/pages/Checkout/Checkout.tsx
@@ -5,16 +5,15 @@ import {
ShieldCheckIcon,
CheckIcon,
} from '@phosphor-icons/react'
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { useNavigate, useLoaderData } from 'react-router'
import { toast } from 'sonner'
+import { usePaddle } from '~/hooks/usePaddle'
import {
BillingFrequency,
CURRENCIES,
- PADDLE_JS_URL,
- PADDLE_VENDOR_ID,
paddleLanguageMapping,
PLAN_LIMITS,
STANDARD_PLANS,
@@ -26,7 +25,7 @@ import type { CheckoutLoaderData } from '~/routes/checkout'
import Button from '~/ui/Button'
import { Text } from '~/ui/Text'
import { Switch } from '~/ui/Switch'
-import { cn, loadScript } from '~/utils/generic'
+import { cn } from '~/utils/generic'
import routes from '~/utils/routes'
const INITIAL_VISIBLE_PLANS = 3
@@ -45,10 +44,19 @@ const Checkout = () => {
>('monthly')
const [showAllPlans, setShowAllPlans] = useState(false)
- const [isPaddleLoaded, setIsPaddleLoaded] = useState(false)
const [hasCompletedCheckout, setHasCompletedCheckout] = useState(false)
const [isCheckoutOpen, setIsCheckoutOpen] = useState(false)
+ const onPaddleEvent = useCallback((eventData: any) => {
+ if (eventData?.event === 'Checkout.Complete') {
+ setHasCompletedCheckout(true)
+ }
+ }, [])
+
+ const { isPaddleLoaded, paddleLoadError } = usePaddle({
+ onEvent: onPaddleEvent,
+ })
+
const currencyCode = user?.tierCurrency || metainfo.code
const currency = CURRENCIES[currencyCode] || CURRENCIES.USD
const tier = PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS]
@@ -59,27 +67,6 @@ const Checkout = () => {
const displayPrice =
selectedBillingFrequency === 'yearly' ? yearlyPrice : monthlyPrice
- useEffect(() => {
- loadScript(PADDLE_JS_URL)
-
- const interval = setInterval(() => {
- if ((window as any)?.Paddle) {
- ;(window as any).Paddle.Setup({
- vendor: PADDLE_VENDOR_ID,
- eventCallback: (eventData: any) => {
- if (eventData?.event === 'Checkout.Complete') {
- setHasCompletedCheckout(true)
- }
- },
- })
- setIsPaddleLoaded(true)
- clearInterval(interval)
- }
- }, 200)
-
- return () => clearInterval(interval)
- }, [])
-
useEffect(() => {
if (hasCompletedCheckout) {
const timer = setTimeout(() => {
@@ -90,8 +77,13 @@ const Checkout = () => {
}, [hasCompletedCheckout, navigate])
const handleStartCheckout = () => {
+ if (paddleLoadError) {
+ toast.error(t('billing.paddleLoadError'))
+ return
+ }
+
if (!isPaddleLoaded || !(window as any).Paddle) {
- toast.error('Payment script is still loading. Please try again.')
+ toast.error(t('billing.paddleStillLoading'))
return
}
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 23a1b0af7..af5ead8f3 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -39,12 +39,11 @@ import {
whitelist,
languages,
languageFlag,
- PADDLE_JS_URL,
- PADDLE_VENDOR_ID,
CONTACT_EMAIL,
paddleLanguageMapping,
} from '~/lib/constants'
import BillingPricing from '~/components/pricing/BillingPricing'
+import { usePaddle } from '~/hooks/usePaddle'
import { changeLanguage } from '~/i18n'
import { DEFAULT_METAINFO } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
@@ -70,7 +69,6 @@ import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
import Flag from '~/ui/Flag'
import TimezonePicker from '~/ui/TimezonePicker'
-import { loadScript } from '~/utils/generic'
import { getCookie, setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
import {
@@ -270,6 +268,8 @@ const UserSettings = () => {
useState(false)
const [lastEvent, setLastEvent] = useState<{ event: string } | null>(null)
+ usePaddle({ onEvent: setLastEvent })
+
const metainfo = useMemo(() => {
if (metainfoFetcher.data?.success && metainfoFetcher.data.data) {
return metainfoFetcher.data.data as typeof DEFAULT_METAINFO
@@ -313,26 +313,6 @@ const UserSettings = () => {
})()
const remainingUsage = _round(Math.max(0, 100 - totalUsage), 2)
- useEffect(() => {
- loadScript(PADDLE_JS_URL)
-
- const interval = setInterval(paddleSetup, 200)
-
- function paddleSetup() {
- if ((window as any)?.Paddle) {
- ;(window as any).Paddle.Setup({
- vendor: PADDLE_VENDOR_ID,
- eventCallback: setLastEvent,
- })
- clearInterval(interval)
- }
- }
-
- return () => {
- clearInterval(interval)
- }
- }, [])
-
const isTrialEnded = (() => {
if (!trialEndDate) {
return false
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 0bd09c042..e8d1d2b46 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2034,7 +2034,9 @@
"usageWarningHigh": "You've used {{percentage}}% of your monthly event limit. Consider upgrading your plan to avoid service interruption.",
"usageWarningCritical": "Warning: You've used {{percentage}}% of your monthly event limit! Upgrade now to ensure uninterrupted service.",
"xPercentUsed": "{{percentage}}% used",
- "xPercentRemaining": "{{percentage}}% remaining"
+ "xPercentRemaining": "{{percentage}}% remaining",
+ "paddleLoadError": "Failed to load the payment system. Please refresh the page and try again.",
+ "paddleStillLoading": "Payment system is still loading. Please try again in a moment."
},
"modals": {
"paidFeature": {