Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: use overlay checkout integration (#1039)

Guilherme Oenning920219b2bfef
diff --git a/README.md b/README.md
index ab145cd5c..b8244a61d 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@
</div>
<div align="center">
- <sub>Built with ❤︎ by <a href="https://github.com/goenning">Guilherme Oenning</a> and <a href="https://github.com/getfider/fider/graphs/contributors">contributors</a></sub>
+ <sub>Built with ❤️ by <a href="https://github.com/goenning">Guilherme Oenning</a> and <a href="https://github.com/getfider/fider/graphs/contributors">contributors</a></sub>
</div>
<br />
@@ -34,7 +34,7 @@
There are two options on how to get started with Fider
- **Self-Hosted**: You can install Fider on any cloud providers. There is no fee associated and you are responsible for managing it. [Learn how](https://getfider.com/#get-started)
-- **Cloud**: Cloud Fider is a fully managed services where you get started in minutes. It's a Pay What You Can model where you contribute financially to support this project and we'll host Fider for you. [Sign up now](https://getfider.com/#get-started)
+- **Cloud**: Cloud Fider is a fully managed services where you get started in minutes. Forget about managing software updates and patches, we do it all for you! [Sign up now](https://getfider.com/#get-started)
## Contributors
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index c296e908c..ff8571c0a 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "fmt"
"net/http"
"github.com/getfider/fider/app/models/cmd"
@@ -8,12 +9,20 @@ import (
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
)
// ManageBilling is the page used by administrators for billing settings
func ManageBilling() web.HandlerFunc {
return func(c *web.Context) error {
+
+ // It's not possible to use custom domains on billing page, so redirect to Fider url
+ if c.Request.IsCustomDomain() {
+ url := fmt.Sprintf("https://%s.%s/admin/billing", c.Tenant().Subdomain, env.Config.HostDomain)
+ return c.Redirect(url)
+ }
+
billingState := &query.GetBillingState{}
if err := bus.Dispatch(c, billingState); err != nil {
return c.Failure(err)
@@ -32,6 +41,11 @@ func ManageBilling() web.HandlerFunc {
Page: "Administration/pages/ManageBilling.page",
Title: "Manage Billing · Site Settings",
Data: web.Map{
+ "paddle": web.Map{
+ "isSandbox": env.Config.Paddle.IsSandbox,
+ "vendorId": env.Config.Paddle.VendorID,
+ "planId": env.Config.Paddle.PlanID,
+ },
"status": billingState.Result.Status,
"trialEndsAt": billingState.Result.TrialEndsAt,
"subscriptionEndsAt": billingState.Result.SubscriptionEndsAt,
@@ -45,7 +59,6 @@ func ManageBilling() web.HandlerFunc {
func GenerateCheckoutLink() web.HandlerFunc {
return func(c *web.Context) error {
generateLink := &cmd.GenerateCheckoutLink{
- ReturnURL: c.BaseURL() + "/admin/billing",
Passthrough: dto.PaddlePassthrough{
TenantID: c.Tenant().ID,
},
diff --git a/app/handlers/billing_test.go b/app/handlers/billing_test.go
index f16811457..92dd2ccd4 100644
--- a/app/handlers/billing_test.go
+++ b/app/handlers/billing_test.go
@@ -19,6 +19,20 @@ import (
"github.com/getfider/fider/app/handlers"
)
+func TestManageBillingHandler_RedirectWhenUsingCNAME(t *testing.T) {
+ RegisterT(t)
+
+ server := mock.NewServer()
+ code, response := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.JonSnow).
+ WithURL("https://feedback.demo.com/admin/billing").
+ Execute(handlers.ManageBilling())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("https://demo.test.fider.io/admin/billing")
+}
+
func TestManageBillingHandler_ReturnsCorrectBillingInformation(t *testing.T) {
RegisterT(t)
@@ -58,6 +72,7 @@ func TestManageBillingHandler_ReturnsCorrectBillingInformation(t *testing.T) {
code, page := server.
OnTenant(mock.DemoTenant).
AsUser(mock.JonSnow).
+ WithURL("https://demo.test.fider.io/admin/billing").
ExecuteAsPage(handlers.ManageBilling())
Expect(code).Equals(http.StatusOK)
@@ -76,12 +91,10 @@ func TestManageBillingHandler_ReturnsCorrectBillingInformation(t *testing.T) {
ExpectHandler(&query.GetBillingSubscription{}).CalledOnce()
}
-func TestGenerateCheckoutLinkHandler_SendsCorrectReturnUrl(t *testing.T) {
+func TestGenerateCheckoutLinkHandler(t *testing.T) {
RegisterT(t)
bus.AddHandler(func(ctx context.Context, c *cmd.GenerateCheckoutLink) error {
- Expect(c.ReturnURL).Equals("http://demo.test.fider.io/admin/billing")
-
c.URL = "https://paddle.com/fake-checkout-url"
return nil
})
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index 4c159a50b..3ebe802c5 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -37,7 +37,7 @@ func TestSecureWithoutCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com ; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com ; img-src 'self' https: data: ; font-src 'self' https://fonts.gstatic.com data: ; object-src 'none'; media-src 'none'; connect-src 'self' https://mygeo.vercel.app https://www.google-analytics.com ; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://*.paddle.com ; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com ; img-src 'self' https: data: ; font-src 'self' https://fonts.gstatic.com data: ; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com ; frame-src 'self' https://*.paddle.com"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -60,7 +60,7 @@ func TestSecureWithCDN(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' https://fonts.gstatic.com data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://mygeo.vercel.app https://www.google-analytics.com *.test.fider.io; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://*.paddle.com *.test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com *.test.fider.io; img-src 'self' https: data: *.test.fider.io; font-src 'self' https://fonts.gstatic.com data: *.test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com *.test.fider.io; frame-src 'self' https://*.paddle.com"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
@@ -83,7 +83,7 @@ func TestSecureWithCDN_SingleHost(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' https://fonts.gstatic.com data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://mygeo.vercel.app https://www.google-analytics.com test.fider.io; frame-src 'self'"
+ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://*.paddle.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://www.google-analytics.com https://*.paddle.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' https://fonts.gstatic.com data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com test.fider.io; frame-src 'self' https://*.paddle.com"
Expect(status).Equals(http.StatusOK)
Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)
diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.go
index 8c6ff0ac1..799dea566 100644
--- a/app/models/cmd/billing.go
+++ b/app/models/cmd/billing.go
@@ -7,7 +7,6 @@ import (
)
type GenerateCheckoutLink struct {
- ReturnURL string
Passthrough dto.PaddlePassthrough
// Output
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index fdaa918b8..0170d2826 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -28,14 +28,14 @@ import (
var (
cspBase = "base-uri 'self'"
cspDefault = "default-src 'self'"
- cspStyle = "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com %[2]s"
- cspScript = "script-src 'self' 'nonce-%[1]s' https://www.google-analytics.com %[2]s"
+ cspStyle = "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://*.paddle.com %[2]s"
+ cspScript = "script-src 'self' 'nonce-%[1]s' https://www.google-analytics.com https://*.paddle.com %[2]s"
cspFont = "font-src 'self' https://fonts.gstatic.com data: %[2]s"
cspImage = "img-src 'self' https: data: %[2]s"
cspObject = "object-src 'none'"
- cspFrame = "frame-src 'self'"
+ cspFrame = "frame-src 'self' https://*.paddle.com"
cspMedia = "media-src 'none'"
- cspConnect = "connect-src 'self' https://mygeo.vercel.app https://www.google-analytics.com %[2]s"
+ cspConnect = "connect-src 'self' https://www.google-analytics.com %[2]s"
//CspPolicyTemplate is the template used to generate the policy
CspPolicyTemplate = fmt.Sprintf("%s; %s; %s; %s; %s; %s; %s; %s; %s; %s", cspBase, cspDefault, cspStyle, cspScript, cspImage, cspFont, cspObject, cspMedia, cspConnect, cspFrame)
diff --git a/app/pkg/web/request.go b/app/pkg/web/request.go
index 6d2d41a04..87807ff51 100644
--- a/app/pkg/web/request.go
+++ b/app/pkg/web/request.go
@@ -8,6 +8,7 @@ import (
"strings"
"time"
+ "github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
)
@@ -95,6 +96,11 @@ func (r *Request) IsCrawler() bool {
return crawlerRegex.MatchString(r.GetHeader("User-Agent"))
}
+// IsCustomDomain returns true if the request was made using a custom domain (CNAME)
+func (r *Request) IsCustomDomain() bool {
+ return !strings.HasSuffix(r.URL.Hostname(), env.Config.HostDomain)
+}
+
//BaseURL returns base URL
func (r *Request) BaseURL() string {
address := r.URL.Scheme + "://" + r.URL.Hostname()
diff --git a/app/pkg/web/request_test.go b/app/pkg/web/request_test.go
index 297b3a9e6..84d5d022b 100644
--- a/app/pkg/web/request_test.go
+++ b/app/pkg/web/request_test.go
@@ -17,9 +17,9 @@ func TestRequest_Basic(t *testing.T) {
req := web.WrapRequest(
&http.Request{
- Method: "GET",
- Header: header,
- Host: "helloworld.com",
+ Method: "GET",
+ Header: header,
+ Host: "helloworld.com",
},
)
@@ -78,7 +78,7 @@ func TestRequest_BehindTLSTerminationProxy(t *testing.T) {
Expect(req.IsAPI()).IsFalse()
}
-func TestRequest_FullURL(t *testing.T) {
+func TestIsCustomDomain(t *testing.T) {
RegisterT(t)
req := web.WrapRequest(
@@ -97,6 +97,19 @@ func TestRequest_FullURL(t *testing.T) {
Expect(req.IsAPI()).IsTrue()
}
+func TestRequest_FullURL(t *testing.T) {
+ RegisterT(t)
+
+ req1 := web.WrapRequest(&http.Request{Host: "demo.test.fider.io:3000"})
+ Expect(req1.IsCustomDomain()).IsFalse()
+
+ req2 := web.WrapRequest(&http.Request{Host: "demo.test.fider.io"})
+ Expect(req2.IsCustomDomain()).IsFalse()
+
+ req3 := web.WrapRequest(&http.Request{Host: "feedback.demo.com"})
+ Expect(req3.IsCustomDomain()).IsTrue()
+}
+
func TestRequest_IsCrawler(t *testing.T) {
RegisterT(t)
diff --git a/app/services/billing/paddle/paddle.go b/app/services/billing/paddle/paddle.go
index 6ceee2de5..448193683 100644
--- a/app/services/billing/paddle/paddle.go
+++ b/app/services/billing/paddle/paddle.go
@@ -48,9 +48,6 @@ func getApiBasePath() string {
}
// generateCheckoutLink generates a checkout link using Paddle API
-// It's a 2-steps process:
-// 1. Create a "Custom Checkout Create URL
-// 2. Use that URL to generate a Checkout Link and return it
func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) error {
passthrough, err := json.Marshal(c.Passthrough)
if err != nil {
@@ -61,7 +58,6 @@ func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) erro
params.Set("vendor_id", env.Config.Paddle.VendorID)
params.Set("vendor_auth_code", env.Config.Paddle.VendorAuthCode)
params.Set("product_id", env.Config.Paddle.PlanID)
- params.Set("return_url", c.ReturnURL)
params.Set("passthrough", string(passthrough))
req := &cmd.HTTPRequest{
@@ -90,35 +86,7 @@ func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) erro
return errors.New("failed to generate paddle checkout link with '%s (%d)'", res.Error.Message, res.Error.Code)
}
- // the "url" here is the "Custom Checkout Create URL", we need to append some extra QueryString parameters
- u, err := url.Parse(jsonq.New(string(res.Response)).String("url"))
- if err != nil {
- return errors.Wrap(err, "generated paddle checkout url is invalid")
- }
-
- // parent_url and parentURL must match one of the approved domains in Paddle.com
- q := u.Query()
- q.Set("parent_url", fmt.Sprintf("https://%s", env.Config.HostDomain))
- q.Set("parentURL", fmt.Sprintf("https://%s", env.Config.HostDomain))
- u.RawQuery = q.Encode()
-
- req = &cmd.HTTPRequest{
- URL: u.String(),
- Method: http.MethodGet,
- }
-
- if err := bus.Dispatch(ctx, req); err != nil {
- return errors.Wrap(err, "failed to generate paddle checkout link")
- }
-
- if req.ResponseStatusCode <= 299 || req.ResponseStatusCode >= 400 {
- return errors.New("unexpected status code while generating a paddle checkout link: %d", req.ResponseStatusCode)
- }
-
- c.URL = req.ResponseHeader.Get("location")
- if c.URL == "" {
- return errors.New("response is missing 'location' header")
- }
+ c.URL = jsonq.New(string(res.Response)).String("url")
return nil
}
diff --git a/index.d.ts b/index.d.ts
index 6fb28a5f6..d9b4cd615 100644
--- a/index.d.ts
+++ b/index.d.ts
@@ -1,6 +1,27 @@
+interface GetPriceResponse {
+ price: { net: string }
+ error?: {
+ message: string
+ }
+}
+
+interface PaddleSdk {
+ isReady: boolean
+ Setup(params: { vendor: number }): void
+ Environment: {
+ set(envName: "sandbox"): void
+ }
+ Checkout: {
+ open(params: { override: string; closeCallback: () => void }): void
+ }
+ Product: {
+ Prices(planId: number, callback: (resp: GetPriceResponse) => void): void
+ }
+}
declare interface Window {
ga?: (cmd: string, evt: string, args?: any) => void
set: (key: string, value: any) => void
+ Paddle: PaddleSdk
}
interface SpriteSymbol {
diff --git a/public/AsyncPages.tsx b/public/AsyncPages.tsx
index 227655b84..2e62909b9 100644
--- a/public/AsyncPages.tsx
+++ b/public/AsyncPages.tsx
@@ -2,10 +2,10 @@ import { lazy, ComponentType } from "react"
type LazyImport = () => Promise<{ default: ComponentType<any> }>
-const MAX_RETRIES = 10
-const INTERVAL = 500
+const MAX_RETRIES = 6
+const INTERVAL = 1000
-const retry = (fn: LazyImport, retriesLeft = MAX_RETRIES): Promise<{ default: ComponentType<any> }> => {
+const retry = (fn: LazyImport, retriesLeft = MAX_RETRIES, waitMs = INTERVAL): Promise<{ default: ComponentType<any> }> => {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
@@ -15,8 +15,8 @@ const retry = (fn: LazyImport, retriesLeft = MAX_RETRIES): Promise<{ default: Co
reject(new Error(`${err} after ${MAX_RETRIES} retries`))
return
}
- retry(fn, retriesLeft - 1).then(resolve, reject)
- }, INTERVAL)
+ retry(fn, retriesLeft - 1, INTERVAL + INTERVAL).then(resolve, reject)
+ }, waitMs)
})
})
}
diff --git a/public/hooks/index.ts b/public/hooks/index.ts
index 71e608ba6..963ac6b13 100644
--- a/public/hooks/index.ts
+++ b/public/hooks/index.ts
@@ -1,2 +1,4 @@
export * from "./use-timeout"
export * from "./use-fider"
+export * from "./use-script"
+export * from "./use-cache"
diff --git a/public/hooks/use-cache.ts b/public/hooks/use-cache.ts
new file mode 100644
index 000000000..1b096b94b
--- /dev/null
+++ b/public/hooks/use-cache.ts
@@ -0,0 +1,25 @@
+import { Dispatch, useEffect, useState } from "react"
+
+const isClient = typeof window !== "undefined"
+
+export function useCache(key: string, defaultValue: string): [string, Dispatch<string>] {
+ const [value, setValue] = useState(defaultValue)
+
+ const setCachedValue = (newValue: string) => {
+ if (isClient && window.sessionStorage) {
+ window.sessionStorage.setItem(key, newValue)
+ }
+ setValue(newValue)
+ }
+
+ useEffect(() => {
+ if (isClient) {
+ const cachedValue = window.sessionStorage?.getItem(key)
+ if (cachedValue) {
+ setValue(cachedValue)
+ }
+ }
+ }, [key, setValue])
+
+ return [value, setCachedValue]
+}
diff --git a/public/hooks/use-script.ts b/public/hooks/use-script.ts
new file mode 100644
index 000000000..d49cb85e2
--- /dev/null
+++ b/public/hooks/use-script.ts
@@ -0,0 +1,66 @@
+import { useEffect, useState } from "react"
+
+type ScriptStatus = "loading" | "idle" | "ready" | "error"
+
+// Hook
+export function useScript(src: string) {
+ const [status, setStatus] = useState<ScriptStatus>(src ? "loading" : "idle")
+
+ useEffect(
+ () => {
+ // Allow falsy src value if waiting on other data needed for
+ // constructing the script URL passed to this hook.
+ if (!src) {
+ setStatus("idle")
+ return
+ }
+
+ // Fetch existing script element by src
+ // It may have been added by another intance of this hook
+ let script: HTMLScriptElement | null = document.querySelector(`script[src="${src}"]`)
+ if (!script) {
+ // Create script
+ script = document.createElement("script")
+ script.src = src
+ script.async = true
+ script.setAttribute("data-status", "loading")
+ // Add script to document body
+ document.body.appendChild(script)
+ // Store status in attribute on script
+ // This can be read by other instances of this hook
+ const setAttributeFromEvent = (event: Event) => {
+ if (!script) return
+
+ script.setAttribute("data-status", event.type === "load" ? "ready" : "error")
+ }
+ script.addEventListener("load", setAttributeFromEvent)
+ script.addEventListener("error", setAttributeFromEvent)
+ } else {
+ // Grab existing script status from attribute and set to state.
+ const status = script.getAttribute("data-status") as ScriptStatus
+ if (status) {
+ setStatus(status)
+ }
+ }
+
+ // Script event handler to update status in state
+ // Note: Even if the script already exists we still need to add
+ // event handlers to update the state for *this* hook instance.
+ const setStateFromEvent = (event: Event) => {
+ setStatus(event.type === "load" ? "ready" : "error")
+ }
+ // Add event listeners
+ script.addEventListener("load", setStateFromEvent)
+ script.addEventListener("error", setStateFromEvent)
+ // Remove event listeners on cleanup
+ return () => {
+ if (script) {
+ script.removeEventListener("load", setStateFromEvent)
+ script.removeEventListener("error", setStateFromEvent)
+ }
+ }
+ },
+ [src] // Only re-run effect if script src changes
+ )
+ return status
+}
diff --git a/public/pages/Administration/components/billing/SubscribeButton.tsx b/public/pages/Administration/components/billing/SubscribeButton.tsx
deleted file mode 100644
index d2f57ca67..000000000
--- a/public/pages/Administration/components/billing/SubscribeButton.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import React, { useEffect, useState } from "react"
-import { Button, Loader } from "@fider/components"
-import { getCurrencyCode } from "@fider/services"
-
-interface SubscribeButtonProps {
- onClick: () => void
-}
-
-const usePricing = (): string | undefined => {
- const prices: { [code: string]: string } = {
- USD: "$30",
- EUR: "€28",
- GBP: "£26",
- }
-
- const [price, setPrice] = useState<string>()
- useEffect(() => {
- getCurrencyCode().then((currencyCode) => setPrice(prices[currencyCode]))
- }, [])
-
- return price
-}
-
-export const SubscribeButton = (props: SubscribeButtonProps) => {
- const price = usePricing()
-
- if (!price) {
- return <Loader className="w-12" />
- }
-
- return (
- <p>
- <Button variant="primary" onClick={props.onClick}>
- Subscribe for {price}/mo
- </Button>
-
- <span className="block text-muted">VAT/Tax may be added during checkout.</span>
- </p>
- )
-}
diff --git a/public/pages/Administration/hooks/use-paddle.ts b/public/pages/Administration/hooks/use-paddle.ts
new file mode 100644
index 000000000..c44e96b5e
--- /dev/null
+++ b/public/pages/Administration/hooks/use-paddle.ts
@@ -0,0 +1,50 @@
+import { useCache, useScript } from "@fider/hooks"
+import { actions } from "@fider/services"
+import { useEffect, useState } from "react"
+
+interface UsePaddleParams {
+ isSandbox: boolean
+ vendorId: string
+ planId: string
+}
+
+export function usePaddle(params: UsePaddleParams) {
+ const status = useScript("https://cdn.paddle.com/paddle/paddle.js")
+ const [price, setPrice] = useCache("price", "$30")
+ const [isReady, setIsReady] = useState(false)
+
+ useEffect(() => {
+ if (status !== "ready" || !params) return
+
+ if (params.isSandbox) {
+ window.Paddle.Environment.set("sandbox")
+ }
+
+ const vendor = parseInt(params.vendorId, 10)
+ window.Paddle.Setup({ vendor })
+ setIsReady(true)
+
+ const id = parseInt(params.planId, 10)
+ window.Paddle.Product.Prices(id, (resp) => {
+ setPrice(resp.price.net.replace(/\.00/g, ""))
+ })
+ }, [status])
+
+ const openUrl = (url: string) => {
+ window.Paddle.Checkout.open({
+ override: url,
+ closeCallback: () => {
+ location.reload()
+ },
+ })
+ }
+
+ const openCheckoutUrl = async () => {
+ const result = await actions.generateCheckoutLink()
+ if (result.ok) {
+ openUrl(result.data.url)
+ }
+ }
+
+ return { isReady, price, openUrl, openCheckoutUrl }
+}
diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsx
index 83e6e8e1d..26e8245db 100644
--- a/public/pages/Administration/pages/ManageBilling.page.tsx
+++ b/public/pages/Administration/pages/ManageBilling.page.tsx
@@ -1,14 +1,18 @@
-import { Moment, Money } from "@fider/components"
+import React from "react"
+import { Button, Moment, Money } from "@fider/components"
import { VStack } from "@fider/components/layout"
import { useFider } from "@fider/hooks"
import { BillingStatus } from "@fider/models"
-import { actions } from "@fider/services"
-import React from "react"
import { AdminPageContainer } from "../components/AdminBasePage"
import { CardDetails } from "../components/billing/CardDetails"
-import { SubscribeButton } from "../components/billing/SubscribeButton"
+import { usePaddle } from "../hooks/use-paddle"
interface ManageBillingPageProps {
+ paddle: {
+ isSandbox: boolean
+ vendorId: string
+ planId: string
+ }
status: BillingStatus
trialEndsAt: string
subscriptionEndsAt: string
@@ -29,15 +33,27 @@ interface ManageBillingPageProps {
}
}
-const subscribe = async () => {
- const result = await actions.generateCheckoutLink()
- if (result.ok) {
- location.href = result.data.url
- }
+const SubscribeButton = (props: { price: string; onClick: () => void }) => {
+ return (
+ <p>
+ <Button variant="primary" onClick={props.onClick}>
+ Subscribe for {props.price}/mo
+ </Button>
+
+ <span className="block text-muted">VAT/Tax may be added during checkout.</span>
+ </p>
+ )
}
const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {
const fider = useFider()
+ const { isReady, openUrl } = usePaddle({ ...props.paddle })
+
+ const open = (url: string) => () => {
+ if (isReady) {
+ openUrl(url)
+ }
+ }
return (
<VStack>
@@ -56,11 +72,11 @@ const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {
</p>
<p>
You can{" "}
- <a rel="noopener" target="_blank" className="text-link" href={props.subscription.updateURL}>
+ <a href="#" rel="noopener" className="text-link" onClick={open(props.subscription.updateURL)}>
update
</a>{" "}
your payment information or{" "}
- <a rel="noopener" target="_blank" className="text-link" href={props.subscription.cancelURL}>
+ <a href="#" rel="noopener" className="text-link" onClick={open(props.subscription.cancelURL)}>
cancel
</a>{" "}
your subscription.
@@ -71,6 +87,7 @@ const ActiveSubscriptionInformation = (props: ManageBillingPageProps) => {
const CancelledSubscriptionInformation = (props: ManageBillingPageProps) => {
const fider = useFider()
+ const { price, openCheckoutUrl } = usePaddle({ ...props.paddle })
const isExpired = new Date(props.subscriptionEndsAt) <= new Date()
@@ -94,13 +111,14 @@ const CancelledSubscriptionInformation = (props: ManageBillingPageProps) => {
. <br /> Resubscribe to avoid a service interruption.
</p>
)}
- <SubscribeButton onClick={subscribe} />
+ <SubscribeButton onClick={openCheckoutUrl} price={price} />
</VStack>
)
}
const TrialInformation = (props: ManageBillingPageProps) => {
const fider = useFider()
+ const { price, openCheckoutUrl } = usePaddle({ ...props.paddle })
const isExpired = new Date(props.trialEndsAt) <= new Date()
@@ -126,7 +144,7 @@ const TrialInformation = (props: ManageBillingPageProps) => {
</p>
)}
- <SubscribeButton onClick={subscribe} />
+ <SubscribeButton onClick={openCheckoutUrl} price={price} />
</VStack>
)
}
diff --git a/public/services/geo.ts b/public/services/geo.ts
deleted file mode 100644
index 8de4b3336..000000000
--- a/public/services/geo.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { cache } from "./cache"
-
-const CACHE_CURRENCYCODE_KEY = "CurrencyCode"
-
-export const getCurrencyCode = async (): Promise<string> => {
- const currencyCode = cache.session.get(CACHE_CURRENCYCODE_KEY)
- if (currencyCode) {
- return currencyCode
- }
-
- try {
- const response = await fetch("https://mygeo.vercel.app")
- if (response.status === 200) {
- const data = await response.json()
- cache.session.set(CACHE_CURRENCYCODE_KEY, data.currencyCode)
- return data.currencyCode
- }
- } catch (err) {
- console.error(err)
- }
-
- return "USD"
-}
diff --git a/public/services/index.ts b/public/services/index.ts
index 09dc3097e..d941c04fc 100644
--- a/public/services/index.ts
+++ b/public/services/index.ts
@@ -3,7 +3,6 @@ export * from "./cache"
export * from "./analytics"
export * from "./fider"
export * from "./jwt"
-export * from "./geo"
export * from "./utils"
export * from "./i18n"
import * as markdown from "./markdown"