📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Fallback if Paddle fails to load
Blue Mouse9ece5db870ab
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsxindex 47a549568..5d8bedc79 100644--- a/web/app/components/pricing/BillingPricing.tsx+++ b/web/app/components/pricing/BillingPricing.tsx@@ -183,7 +183,7 @@ const BillingPricing = ({})if (!opened) {- toast.error(t('billing.paddleStillLoading'))+ toast.error(t('billing.checkoutPreparationError'))setSelectionLoading(null)}diff --git a/web/app/hooks/usePaddle.ts b/web/app/hooks/usePaddle.tsindex a73387669..882909431 100644--- a/web/app/hooks/usePaddle.ts+++ b/web/app/hooks/usePaddle.ts@@ -1,16 +1,15 @@import { useCallback, 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 = 500 // 100 seconds+const LOAD_TIMEOUT_MS = 15_000type PaddleListener = (eventData: any) => voidlet initStarted = falselet paddleReady = falselet paddleError = false+let initializedPaddle: any = nullconst listeners = new Set<PaddleListener>()const stateSubscribers = new Set<() => void>()@@ -19,34 +18,60 @@ function notifyStateSubscribers() {}function initPaddle() {- if (initStarted) return+ if (initStarted || (paddleReady && initializedPaddle === window.Paddle))+ returninitStarted = true+ paddleReady = false+ paddleError = false+ notifyStateSubscribers()++ const script = document.createElement('script')+ script.src = PADDLE_JS_URL+ script.async = true++ const finish = (ready: boolean) => {+ clearTimeout(timeout)+ script.onload = null+ script.onerror = null+ initStarted = false+ paddleReady = ready+ paddleError = !ready+ if (!ready) script.remove()+ notifyStateSubscribers()+ }++ const timeout = setTimeout(() => finish(false), LOAD_TIMEOUT_MS)++ script.onload = () => {+ try {+ const paddle = window.Paddle+ if (+ typeof paddle?.Setup !== 'function' ||+ typeof paddle?.Checkout?.open !== 'function'+ ) {+ finish(false)+ return+ }- loadScript(PADDLE_JS_URL)-- let attempts = 0- const interval = setInterval(() => {- attempts += 1-- if ((window as any)?.Paddle) {- ;(window as any).Paddle.Setup({+ paddle.Setup({vendor: PADDLE_VENDOR_ID,eventCallback: (eventData: any) => {for (const listener of listeners) listener(eventData)},})- paddleReady = true- notifyStateSubscribers()- clearInterval(interval)- return- }-- if (attempts >= MAX_ATTEMPTS) {- paddleError = true- notifyStateSubscribers()- clearInterval(interval)+ initializedPaddle = paddle+ finish(true)+ } catch {+ finish(false)}- }, POLL_INTERVAL_MS)+ }+ script.onerror = () => finish(false)++ try {+ document.body.appendChild(script)+ } catch {+ finish(false)+ }}interface UsePaddleOptions {@@ -77,7 +102,6 @@ export function usePaddle(options: UsePaddleOptions = {}): UsePaddleResult {}stateSubscribers.add(stateSubscriber)- // Sync state in case init already completed before this effect ranstateSubscriber()initPaddle()@@ -90,10 +114,32 @@ export function usePaddle(options: UsePaddleOptions = {}): UsePaddleResult {const openCheckout = useCallback((checkoutOptions: Record<string, any>): boolean => {- if (!(window as any)?.Paddle) return false+ if (typeof window === 'undefined') return false++ try {+ if (paddleReady && initializedPaddle === window.Paddle) {+ initializedPaddle.Checkout.open(checkoutOptions)+ return true+ }+ } catch {+ paddleReady = false+ paddleError = true+ notifyStateSubscribers()+ }try {- ;(window as any).Paddle.Checkout.open(checkoutOptions)+ const url = new URL(checkoutOptions.override)+ if (+ url.protocol !== 'https:' ||+ (url.hostname !== 'paddle.com' &&+ !url.hostname.endsWith('.paddle.com')) ||+ url.username ||+ url.password+ ) {+ return false+ }++ window.location.assign(url.href)return true} catch {return falsediff --git a/web/app/pages/Subscribe/Subscribe.tsx b/web/app/pages/Subscribe/Subscribe.tsxindex 6b351247b..991dfd044 100644--- a/web/app/pages/Subscribe/Subscribe.tsx+++ b/web/app/pages/Subscribe/Subscribe.tsx@@ -162,7 +162,7 @@ const Subscribe = () => {})if (!opened) {- toast.error(t('billing.paddleStillLoading'))+ toast.error(t('billing.checkoutPreparationError'))checkoutInProgressRef.current = falsesetSelectionLoading(null)}@@ -220,18 +220,6 @@ const Subscribe = () => {return}- if (paddleLoadError) {- toast.error(t('billing.paddleLoadError'))- checkoutInProgressRef.current = false- return- }-- if (!isPaddleLoaded || !(window as any).Paddle) {- toast.error(t('billing.paddleStillLoading'))- checkoutInProgressRef.current = false- return- }-setSelectionLoading(selection)const attribution = await getRevenueAttribution()diff --git a/web/scripts/tests/paddle-checkout.test.mjs b/web/scripts/tests/paddle-checkout.test.mjsnew file mode 100644index 000000000..8921135a1--- /dev/null+++ b/web/scripts/tests/paddle-checkout.test.mjs@@ -0,0 +1,227 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import { test } from 'node:test'+import { runInNewContext } from 'node:vm'+import ts from 'typescript'++const source = readFileSync(+ new URL('../../app/hooks/usePaddle.ts', import.meta.url),+ 'utf8',+)+const { outputText } = ts.transpileModule(source, {+ compilerOptions: {+ module: ts.ModuleKind.CommonJS,+ target: ts.ScriptTarget.ES2022,+ },+})+const checkoutOptions = {+ override: 'https://checkout.paddle.com/checkout/custom/test-checkout',+ email: '[email protected]',+ locale: 'en',+}++function createHarness() {+ const scripts = []+ const redirects = []+ const timers = new Map()+ let currentMount+ const window = { location: { assign: (url) => redirects.push(url) } }+ const module = { exports: {} }+ runInNewContext(outputText, {+ exports: module.exports,+ window,+ URL,+ document: {+ createElement: () => ({+ remove() {+ this.removed = true+ },+ }),+ body: { appendChild: (script) => scripts.push(script) },+ },+ setTimeout: (callback, delay) => {+ timers.set(callback, delay)+ return callback+ },+ clearTimeout: (callback) => timers.delete(callback),+ require: (name) => {+ if (name === '~/lib/constants') {+ return {+ PADDLE_JS_URL: 'https://cdn.paddle.com/paddle/paddle.js',+ PADDLE_VENDOR_ID: 139393,+ }+ }+ assert.equal(name, 'react')+ return {+ useCallback: (callback) => callback,+ useRef: (value) => ({ current: value }),+ useState: (value) => {+ const state = currentMount.state+ const index = state.push(value) - 1+ return [+ value,+ (next) => {+ state[index] = next+ },+ ]+ },+ useEffect: (effect) => {+ currentMount.effect = effect+ },+ }+ },+ })+ return {+ window,+ scripts,+ redirects,+ timers,+ mount(options) {+ currentMount = { state: [] }+ const hook = module.exports.usePaddle(options)+ const unmount = currentMount.effect()+ return { ...hook, state: currentMount.state, unmount }+ },+ }+}++test('a checkout requested before Paddle loads opens the generated hosted link', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ assert.deepEqual(checkout.state, [false, false])+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(harness.redirects, [checkoutOptions.override])+})++test('a blocked script fails immediately and does not prevent checkout', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ harness.scripts[0].onerror()+ assert.deepEqual(checkout.state, [false, true])+ assert.equal(harness.timers.size, 0)+ assert.equal(harness.scripts[0].removed, true)+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(harness.redirects, [checkoutOptions.override])+})++test('a stalled script times out and a later mount retries initialization', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ const [[timeout, delay]] = harness.timers+ assert.equal(delay, 15_000)+ timeout()+ assert.deepEqual(checkout.state, [false, true])+ assert.equal(harness.timers.size, 0)+ checkout.unmount()+ const retry = harness.mount()+ assert.equal(harness.scripts.length, 2)+ assert.deepEqual(retry.state, [false, false])+ harness.window.Paddle = { Setup() {}, Checkout: { open() {} } }+ harness.scripts[1].onload()+ assert.deepEqual(retry.state, [true, false])+})++test('successful initialization is shared, opens the overlay and forwards events to mounted listeners', () => {+ const harness = createHarness()+ const events = []+ const opened = []+ let setup+ const checkout = harness.mount({ onEvent: (event) => events.push(event) })+ const second = harness.mount()+ assert.equal(harness.scripts.length, 1)+ harness.window.Paddle = {+ Setup(options) {+ setup = options+ },+ Checkout: { open: (options) => opened.push(options) },+ }+ harness.scripts[0].onload()+ assert.equal(setup.vendor, 139393)+ assert.deepEqual(checkout.state, [true, false])+ assert.deepEqual(second.state, [true, false])+ assert.equal(harness.timers.size, 0)+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(opened, [checkoutOptions])+ assert.deepEqual(harness.redirects, [])+ const completed = { event: 'Checkout.Complete' }+ setup.eventCallback(completed)+ assert.deepEqual(events, [completed])+ checkout.unmount()+ setup.eventCallback({ event: 'Checkout.Close' })+ assert.deepEqual(events, [completed])+ harness.mount()+ assert.equal(harness.scripts.length, 1)+})++test('setup errors and an incompatible SDK fail cleanly and use hosted checkout', () => {+ for (const paddle of [+ undefined,+ { Initialize() {} },+ {+ Setup() {+ throw new Error('Setup failed')+ },+ Checkout: { open() {} },+ },+ ]) {+ const harness = createHarness()+ const checkout = harness.mount()+ harness.window.Paddle = paddle+ harness.scripts[0].onload()+ assert.deepEqual(checkout.state, [false, true])+ assert.equal(harness.timers.size, 0)+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(harness.redirects, [checkoutOptions.override])+ }+})++test('overlay errors fall back to the same generated payment link', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ harness.window.Paddle = {+ Setup() {},+ Checkout: {+ open() {+ throw new Error('Checkout failed')+ },+ },+ }+ harness.scripts[0].onload()+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(checkout.state, [false, true])+ assert.deepEqual(harness.redirects, [checkoutOptions.override])+})++test('replacing the SDK after initialization cannot open a Classic checkout with the wrong SDK', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ harness.window.Paddle = { Setup() {}, Checkout: { open() {} } }+ harness.scripts[0].onload()+ harness.window.Paddle = {+ Checkout: {+ open() {+ assert.fail('Wrong SDK')+ },+ },+ }+ assert.equal(checkout.openCheckout(checkoutOptions), true)+ assert.deepEqual(harness.redirects, [checkoutOptions.override])+})++test('missing, malformed and non-Paddle fallback links fail without navigation', () => {+ const harness = createHarness()+ const checkout = harness.mount()+ for (const override of [+ undefined,+ '',+ 'not a URL',+ 'javascript:alert(1)',+ 'http://checkout.paddle.com/test',+ 'https://paddle.com.example.com/test',+ 'https://example.com/test',+ 'https://user:[email protected]/test',+ ]) {+ assert.equal(checkout.openCheckout({ override }), false)+ }+ assert.deepEqual(harness.redirects, [])+})