Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: checkout and paddle webhook

goenningd7e04541c47e
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index f25c9b755..2f4a5d5c1 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/handlers/apiv1"
+ "github.com/getfider/fider/app/handlers/webhooks"
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/pkg/env"
@@ -61,6 +62,11 @@ func routes(r *web.Engine) *web.Engine {
r.Get("/oauth/:provider", handlers.SignInByOAuth())
r.Get("/oauth/:provider/callback", handlers.OAuthCallback())
+ wh := r.Group()
+ {
+ wh.Post("/webhooks/paddle", webhooks.IncomingPaddleWebhook())
+ }
+
//Starting from this step, a Tenant is required
r.Use(middlewares.RequireTenant())
@@ -177,6 +183,7 @@ func routes(r *web.Engine) *web.Engine {
if env.IsBillingEnabled() {
ui.Get("/admin/billing", handlers.ManageBilling())
+ ui.Post("/_api/billing/checkout-link", handlers.GenerateCheckoutLink())
}
}
@@ -224,10 +231,6 @@ func routes(r *web.Engine) *web.Engine {
api.Post("/api/v1/tags", apiv1.CreateEditTag())
api.Put("/api/v1/tags/:slug", apiv1.CreateEditTag())
api.Delete("/api/v1/tags/:slug", apiv1.DeleteTag())
-
- if env.IsBillingEnabled() {
- api.Post("/_api/billing/checkout-link", handlers.GenerateCheckoutLink())
- }
}
return r
diff --git a/app/handlers/billing.go b/app/handlers/billing.go
index 2aa7940c6..78b4ceacc 100644
--- a/app/handlers/billing.go
+++ b/app/handlers/billing.go
@@ -2,6 +2,7 @@ package handlers
import (
"github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/web"
@@ -19,8 +20,9 @@ func ManageBilling() web.HandlerFunc {
Title: "Manage Billing · Site Settings",
ChunkName: "ManageBilling.page",
Data: web.Map{
- "status": getState.Result.Status,
- "trialEndsAt": getState.Result.TrialEndsAt,
+ "status": getState.Result.Status,
+ "trialEndsAt": getState.Result.TrialEndsAt,
+ "subscriptionEndsAt": getState.Result.SubscriptionEndsAt,
},
})
}
@@ -29,7 +31,14 @@ func ManageBilling() web.HandlerFunc {
// GenerateCheckoutLink generates a Paddle-hosted checkout link for the service subscription
func GenerateCheckoutLink() web.HandlerFunc {
return func(c *web.Context) error {
- generateLink := &cmd.GenerateCheckoutLink{}
+ generateLink := &cmd.GenerateCheckoutLink{
+ Email: c.User().Email,
+ ReturnURL: c.BaseURL() + "/admin/billing",
+ Passthrough: dto.PaddlePassthrough{
+ TenantID: c.Tenant().ID,
+ },
+ }
+
if err := bus.Dispatch(c, generateLink); err != nil {
return c.Failure(err)
}
diff --git a/app/handlers/webhooks/paddle.go b/app/handlers/webhooks/paddle.go
new file mode 100644
index 000000000..e82eb6b16
--- /dev/null
+++ b/app/handlers/webhooks/paddle.go
@@ -0,0 +1,145 @@
+package webhooks
+
+import (
+ "crypto"
+ "crypto/rsa"
+ "crypto/sha1"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "net/url"
+ "sort"
+ "time"
+
+ "github.com/getfider/fider/app/models/cmd"
+ "github.com/getfider/fider/app/models/dto"
+ "github.com/getfider/fider/app/pkg/bus"
+ "github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+// IncomingPaddleWebhook handles all incoming requests from Paddle Webhooks
+func IncomingPaddleWebhook() web.HandlerFunc {
+ return func(c *web.Context) error {
+ params, err := url.ParseQuery(c.Request.Body)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = verifyPaddleSig(params, env.Config.Paddle.PublicKey)
+ if err != nil {
+ return c.Failure(errors.Wrap(err, "failed to verity paddle signature"))
+ }
+
+ action := params.Get("alert_name")
+ switch action {
+ case "subscription_created":
+ return handlePaddleSubscriptionCreated(c, params)
+ case "subscription_cancelled":
+ return handlePaddleSubscriptionCancelled(c, params)
+ default:
+ log.Warnf(c, "Unsupported Paddle webhook action: '@{Action}'", dto.Props{
+ "Action": action,
+ })
+ return c.Ok(web.Map{})
+ }
+ }
+}
+
+func handlePaddleSubscriptionCreated(c *web.Context, params url.Values) error {
+ passthrough := dto.PaddlePassthrough{}
+ if err := json.Unmarshal([]byte(params.Get("passthrough")), &passthrough); err != nil {
+ return c.Failure(err)
+ }
+
+ activate := &cmd.ActivateBillingSubscription{
+ TenantID: passthrough.TenantID,
+ SubscriptionID: params.Get("subscription_id"),
+ PlanID: params.Get("subscription_plan_id"),
+ }
+
+ if err := bus.Dispatch(c, activate); err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{})
+}
+
+func handlePaddleSubscriptionCancelled(c *web.Context, params url.Values) error {
+ passthrough := dto.PaddlePassthrough{}
+ if err := json.Unmarshal([]byte(params.Get("passthrough")), &passthrough); err != nil {
+ return c.Failure(err)
+ }
+
+ cancellationEffectiveDate := params.Get("cancellation_effective_date")
+ subscriptionEndsAt, err := time.Parse("2006-01-02 15:04:05", cancellationEffectiveDate)
+ if err != nil {
+ log.Error(c, errors.Wrap(err, "failed to parse date '%s'", cancellationEffectiveDate))
+ subscriptionEndsAt = time.Now().AddDate(0, 0, 30)
+ }
+
+ cancel := &cmd.CancelBillingSubscription{
+ TenantID: passthrough.TenantID,
+ SubscriptionEndsAt: subscriptionEndsAt,
+ }
+
+ if err := bus.Dispatch(c, cancel); err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{})
+}
+
+// verifyPaddleSig verifies the p_signature parameter sent
+// in Paddle webhooks. 'values' is the decoded form values sent
+// in the webhook response body.
+func verifyPaddleSig(values url.Values, publicKeyPEM string) error {
+ der, _ := pem.Decode([]byte(publicKeyPEM))
+ if der == nil {
+ return errors.New("Could not parse public key pem")
+ }
+
+ pub, err := x509.ParsePKIXPublicKey(der.Bytes)
+ if err != nil {
+ return errors.New("Could not parse public key pem der")
+ }
+
+ signingKey, ok := pub.(*rsa.PublicKey)
+ if !ok {
+ return errors.New("Not the correct key format")
+ }
+
+ sig, err := base64.StdEncoding.DecodeString(values.Get("p_signature"))
+ if err != nil {
+ return err
+ }
+
+ values.Del("p_signature")
+ sha1Sum := sha1.Sum(phpserialize(values))
+ err = rsa.VerifyPKCS1v15(signingKey, crypto.SHA1, sha1Sum[:], sig)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func phpserialize(form url.Values) []byte {
+ var keys []string
+ for k := range form {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+
+ serialized := fmt.Sprintf("a:%d:{", len(keys))
+ for _, k := range keys {
+ serialized += fmt.Sprintf("s:%d:\"%s\";s:%d:\"%s\";", len(k), k, len(form.Get(k)), form.Get(k))
+ }
+ serialized += "}"
+
+ return []byte(serialized)
+}
diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.go
index 46f9d9659..ad9fbf662 100644
--- a/app/models/cmd/billing.go
+++ b/app/models/cmd/billing.go
@@ -1,6 +1,27 @@
package cmd
+import (
+ "time"
+
+ "github.com/getfider/fider/app/models/dto"
+)
+
type GenerateCheckoutLink struct {
+ Email string
+ ReturnURL string
+ Passthrough dto.PaddlePassthrough
+
// Output
URL string
}
+
+type ActivateBillingSubscription struct {
+ TenantID int
+ SubscriptionID string
+ PlanID string
+}
+
+type CancelBillingSubscription struct {
+ TenantID int
+ SubscriptionEndsAt time.Time
+}
diff --git a/app/models/dto/billing.go b/app/models/dto/billing.go
new file mode 100644
index 000000000..b644483b4
--- /dev/null
+++ b/app/models/dto/billing.go
@@ -0,0 +1,5 @@
+package dto
+
+type PaddlePassthrough struct {
+ TenantID int `json:"tenant_id"`
+}
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index b552c80d2..a11e66f03 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -45,6 +45,7 @@ type config struct {
VendorID string `env:"PADDLE_VENDOR_ID"`
VendorAuthCode string `env:"PADDLE_VENDOR_AUTHCODE"`
PlanID string `env:"PADDLE_PLAN_ID"`
+ PublicKey string `env:"PADDLE_PUBLIC_KEY"`
}
Metrics struct {
Enabled bool `env:"METRICS_ENABLED,default=false"`
diff --git a/app/services/billing/paddle/paddle.go b/app/services/billing/paddle/paddle.go
index 50966e60a..e7b25ce74 100644
--- a/app/services/billing/paddle/paddle.go
+++ b/app/services/billing/paddle/paddle.go
@@ -45,10 +45,18 @@ func getApiBasePath() string {
}
func generateCheckoutLink(ctx context.Context, c *cmd.GenerateCheckoutLink) error {
+ passthrough, err := json.Marshal(c.Passthrough)
+ if err != nil {
+ return errors.Wrap(err, "failed to marshal Passthrough object")
+ }
+
params := url.Values{}
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("customer_email", c.Email)
+ params.Set("return_url", c.ReturnURL)
+ params.Set("passthrough", string(passthrough))
req := &cmd.HTTPRequest{
URL: fmt.Sprintf("%s/api/2.0/product/generate_pay_link", getApiBasePath()),
diff --git a/app/services/billing/paddle/response.go b/app/services/billing/paddle/response.go
index 90ded00d7..c00845d1d 100644
--- a/app/services/billing/paddle/response.go
+++ b/app/services/billing/paddle/response.go
@@ -10,3 +10,20 @@ type PaddleResponse struct {
Message string `json:"message"`
}
}
+
+type PaddleSubscriptionItem struct {
+ SignupDate string `json:"signup_date"`
+ UpdateURL string `json:"update_url"`
+ CancelURL string `json:"cancel_url"`
+ PaymentInformation struct {
+ PaymentMethod string `json:"payment_method"`
+ Currency string `json:"card_type"`
+ LastFourDigits string `json:"last_four_digits"`
+ ExpiryDate string `json:"expiry_date"`
+ } `json:"payment_information"`
+ LastPayment struct {
+ Amount float64 `json:"amount"`
+ Currency string `json:"currency"`
+ Date string `json:"date"`
+ } `json:"last_payment"`
+}
diff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.go
index 0f3441c57..223cf2ced 100644
--- a/app/services/sqlstore/postgres/billing.go
+++ b/app/services/sqlstore/postgres/billing.go
@@ -3,10 +3,12 @@ package postgres
import (
"context"
+ "github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
)
type dbBillingState struct {
@@ -58,3 +60,31 @@ func getBillingState(ctx context.Context, q *query.GetBillingState) error {
return nil
})
}
+
+func activateBillingSubscription(ctx context.Context, c *cmd.ActivateBillingSubscription) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
+ _, err := trx.Execute(`
+ UPDATE tenants_billing
+ SET subscription_ends_at = null, paddle_subscription_id = $2, paddle_plan_id = $3, status = $4
+ WHERE tenant_id = $1
+ `, c.TenantID, c.SubscriptionID, c.PlanID, enum.BillingActive)
+ if err != nil {
+ return errors.Wrap(err, "failed activate billing subscription")
+ }
+ return nil
+ })
+}
+
+func cancelBillingSubscription(ctx context.Context, c *cmd.CancelBillingSubscription) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
+ _, err := trx.Execute(`
+ UPDATE tenants_billing
+ SET subscription_ends_at = $2, status = $3
+ WHERE tenant_id = $1
+ `, c.TenantID, c.SubscriptionEndsAt, enum.BillingCancelled)
+ if err != nil {
+ return errors.Wrap(err, "failed cancel billing subscription")
+ }
+ return nil
+ })
+}
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index ef3a6e27c..016856f36 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -127,6 +127,8 @@ func (s Service) Init() {
bus.AddHandler(markWebhookAsFailed)
bus.AddHandler(getBillingState)
+ bus.AddHandler(activateBillingSubscription)
+ bus.AddHandler(cancelBillingSubscription)
}
type SqlHandler func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error
diff --git a/locale/ru/client.json b/locale/ru/client.json
index 538ff7596..b43efc0a6 100644
--- a/locale/ru/client.json
+++ b/locale/ru/client.json
@@ -134,4 +134,4 @@
"signin.message.private.text": "Если у вас есть аккаунт или приглашение, вы можете использовать их для входа.",
"signin.message.private.title": "<0>{0}</0> - приватный сайт. Вам нужно приглашение, чтобы присоединиться к нему.",
"{count, plural, one {# tag} other {# tags}}": "{count, plural, one {# tag} other {# tags}}"
-}
+}
\ No newline at end of file
diff --git a/public/components/common/Moment.tsx b/public/components/common/Moment.tsx
index 754926c43..d154a93b5 100644
--- a/public/components/common/Moment.tsx
+++ b/public/components/common/Moment.tsx
@@ -24,8 +24,10 @@ export const Moment = (props: MomentText) => {
? timeSince(props.locale, now, date)
: formatDate(props.locale, props.date, format)
+ const tooltip = props.format === "full" ? undefined : formatDate(props.locale, props.date, "full")
+
return (
- <span className="date" data-tooltip={formatDate(props.locale, props.date, "full")}>
+ <span className="date" data-tooltip={tooltip}>
{display}
</span>
)
diff --git a/public/pages/Administration/pages/ManageBilling.page.tsx b/public/pages/Administration/pages/ManageBilling.page.tsx
index 76a45c6a3..92e1550ff 100644
--- a/public/pages/Administration/pages/ManageBilling.page.tsx
+++ b/public/pages/Administration/pages/ManageBilling.page.tsx
@@ -8,6 +8,7 @@ import { AdminPageContainer } from "../components/AdminBasePage"
interface ManageBillingPageProps {
status: BillingStatus
trialEndsAt: string
+ subscriptionEndsAt: string
}
const ManageBillingPage = (props: ManageBillingPageProps) => {
@@ -23,18 +24,43 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {
return (
<AdminPageContainer id="p-admin-billing" name="billing" title="Billing" subtitle="Manage your billing settings">
{props.status === BillingStatus.Trial && (
- <p>
- Your account is currently on a trial until{" "}
- <strong>
- <Moment locale={fider.currentLocale} format="full" date={props.trialEndsAt} />
- </strong>
- . <br />
- Subscribe before the end of your trial to avoid a service interruption.
- </p>
+ <>
+ <p>
+ Your account is currently on a trial until{" "}
+ <strong>
+ <Moment locale={fider.currentLocale} format="full" date={props.trialEndsAt} />
+ </strong>
+ . <br />
+ Subscribe before the end of your trial to avoid a service interruption.
+ </p>
+
+ <Button variant="primary" onClick={subscribe}>
+ Subscribe for $30/mo + Tax
+ </Button>
+ </>
+ )}
+
+ {props.status === BillingStatus.Active && (
+ <>
+ <p>Your Fider subscription is currently active.</p>
+ </>
+ )}
+
+ {props.status === BillingStatus.Cancelled && (
+ <>
+ <p>
+ Your Fider subscription is currently cancelled. This site will stay active until{" "}
+ <strong>
+ <Moment locale={fider.currentLocale} format="full" date={props.subscriptionEndsAt} />
+ </strong>
+ . <br /> Resubscribe to avoid a service interruption.
+ </p>
+
+ <Button variant="primary" onClick={subscribe}>
+ Resubscribe for $30/mo + Tax
+ </Button>
+ </>
)}
- <Button variant="primary" onClick={subscribe}>
- Subscribe for $30/mo + tax
- </Button>
<p className="text-muted">
We use{" "}
<strong>
@@ -42,7 +68,7 @@ const ManageBillingPage = (props: ManageBillingPageProps) => {
Paddle
</a>
</strong>{" "}
- as our billing partner. You may see {'"PADDLE.COM FIDER"'} on your credit card after subscribing.
+ as our billing partner. You may see {'"PADDLE.COM FIDER"'} on your credit card.
</p>
</AdminPageContainer>
)