Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

First stab at stripe integration.

Matt Roberts731c7e5ac424
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 45dbb35c9..0b159da21 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -77,6 +77,12 @@ func routes(r *web.Engine) *web.Engine {
}
}
+ // Stripe webhooks (before CSRF middleware)
+ stripeWh := r.Group()
+ {
+ stripeWh.Post("/webhooks/stripe", webhooks.IncomingStripeWebhook())
+ }
+
r.Use(middlewares.CSRF())
r.Get("/terms", handlers.LegalPage("Terms of Service", "terms.md"))
@@ -201,6 +207,11 @@ func routes(r *web.Engine) *web.Engine {
ui.Get("/admin/billing", handlers.ManageBilling())
ui.Post("/_api/billing/checkout-link", handlers.GenerateCheckoutLink())
}
+
+ // Stripe billing (experimental)
+ ui.Get("/admin/billing2", handlers.ManageBilling2())
+ ui.Post("/_api/admin/billing2/portal", handlers.CreateStripePortalSession())
+ ui.Post("/_api/admin/billing2/checkout", handlers.CreateStripeCheckoutSession())
}
// Public operations
diff --git a/app/handlers/billing2.go b/app/handlers/billing2.go
new file mode 100644
index 000000000..51019e134
--- /dev/null
+++ b/app/handlers/billing2.go
@@ -0,0 +1,104 @@
+package handlers
+
+import (
+ "fmt"
+ "net/http"
+
+ "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"
+ "github.com/stripe/stripe-go/v83"
+ portalsession "github.com/stripe/stripe-go/v83/billingportal/session"
+ checkoutsession "github.com/stripe/stripe-go/v83/checkout/session"
+)
+
+// ManageBilling2 is the page used by administrators for Stripe billing settings
+func ManageBilling2() web.HandlerFunc {
+ return func(c *web.Context) error {
+ billingState := &query.GetStripeBillingState{}
+ if err := bus.Dispatch(c, billingState); err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Page(http.StatusOK, web.Props{
+ Page: "Administration/pages/ManageBilling2.page",
+ Title: "Manage Billing · Site Settings",
+ Data: web.Map{
+ "stripeCustomerID": billingState.Result.CustomerID,
+ "stripeSubscriptionID": billingState.Result.SubscriptionID,
+ },
+ })
+ }
+}
+
+// CreateStripePortalSession creates a Stripe customer portal session
+func CreateStripePortalSession() web.HandlerFunc {
+ return func(c *web.Context) error {
+ billingState := &query.GetStripeBillingState{}
+ if err := bus.Dispatch(c, billingState); err != nil {
+ return c.Failure(err)
+ }
+
+ if billingState.Result.CustomerID == "" {
+ return c.BadRequest(web.Map{"message": "No Stripe customer found"})
+ }
+
+ stripe.Key = env.Config.Stripe.SecretKey
+
+ returnURL := c.BaseURL() + "/admin/billing2"
+
+ params := &stripe.BillingPortalSessionParams{
+ Customer: stripe.String(billingState.Result.CustomerID),
+ ReturnURL: stripe.String(returnURL),
+ }
+
+ s, err := portalsession.New(params)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{
+ "url": s.URL,
+ })
+ }
+}
+
+// CreateStripeCheckoutSession creates a Stripe checkout session for new subscriptions
+func CreateStripeCheckoutSession() web.HandlerFunc {
+ return func(c *web.Context) error {
+ stripe.Key = env.Config.Stripe.SecretKey
+
+ returnURL := c.BaseURL() + "/admin/billing2"
+ tenantID := c.Tenant().ID
+
+ params := &stripe.CheckoutSessionParams{
+ Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
+ LineItems: []*stripe.CheckoutSessionLineItemParams{
+ {
+ Price: stripe.String(env.Config.Stripe.PriceID),
+ Quantity: stripe.Int64(1),
+ },
+ },
+ SuccessURL: stripe.String(returnURL + "?checkout=success"),
+ CancelURL: stripe.String(returnURL + "?checkout=cancelled"),
+ Metadata: map[string]string{
+ "tenant_id": fmt.Sprintf("%d", tenantID),
+ },
+ SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
+ Metadata: map[string]string{
+ "tenant_id": fmt.Sprintf("%d", tenantID),
+ },
+ },
+ }
+
+ s, err := checkoutsession.New(params)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{
+ "url": s.URL,
+ })
+ }
+}
diff --git a/app/handlers/webhooks/stripe.go b/app/handlers/webhooks/stripe.go
new file mode 100644
index 000000000..bce7e3bea
--- /dev/null
+++ b/app/handlers/webhooks/stripe.go
@@ -0,0 +1,109 @@
+package webhooks
+
+import (
+ "encoding/json"
+ "strconv"
+
+ "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"
+ "github.com/stripe/stripe-go/v83"
+ "github.com/stripe/stripe-go/v83/webhook"
+)
+
+// IncomingStripeWebhook handles all incoming requests from Stripe Webhooks
+func IncomingStripeWebhook() web.HandlerFunc {
+ return func(c *web.Context) error {
+ payload := []byte(c.Request.Body)
+ sigHeader := c.Request.GetHeader("Stripe-Signature")
+ event, err := webhook.ConstructEvent(payload, sigHeader, env.Config.Stripe.WebhookSecret)
+ if err != nil {
+ return c.Failure(errors.Wrap(err, "failed to verify stripe webhook signature"))
+ }
+
+ switch event.Type {
+ case "checkout.session.completed":
+ return handleCheckoutSessionCompleted(c, event)
+ case "customer.subscription.deleted":
+ return handleSubscriptionDeleted(c, event)
+ default:
+ log.Debugf(c, "Ignoring Stripe webhook event: '@{EventType}'", dto.Props{
+ "EventType": event.Type,
+ })
+ return c.Ok(web.Map{})
+ }
+ }
+}
+
+func handleCheckoutSessionCompleted(c *web.Context, event stripe.Event) error {
+ var session stripe.CheckoutSession
+ if err := json.Unmarshal(event.Data.Raw, &session); err != nil {
+ return c.Failure(errors.Wrap(err, "failed to parse checkout session"))
+ }
+
+ // Get tenant ID from metadata
+ tenantIDStr, ok := session.Metadata["tenant_id"]
+ if !ok {
+ return c.Failure(errors.New("tenant_id not found in session metadata"))
+ }
+
+ tenantID, err := strconv.Atoi(tenantIDStr)
+ if err != nil {
+ return c.Failure(errors.Wrap(err, "failed to parse tenant_id"))
+ }
+
+ activate := &cmd.ActivateStripeSubscription{
+ TenantID: tenantID,
+ CustomerID: session.Customer.ID,
+ SubscriptionID: session.Subscription.ID,
+ }
+
+ if err := bus.Dispatch(c, activate); err != nil {
+ return c.Failure(err)
+ }
+
+ log.Infof(c, "Stripe subscription activated for tenant @{TenantID}", dto.Props{
+ "TenantID": tenantID,
+ })
+
+ return c.Ok(web.Map{})
+}
+
+func handleSubscriptionDeleted(c *web.Context, event stripe.Event) error {
+ var subscription stripe.Subscription
+ if err := json.Unmarshal(event.Data.Raw, &subscription); err != nil {
+ return c.Failure(errors.Wrap(err, "failed to parse subscription"))
+ }
+
+ // Get tenant ID from metadata
+ tenantIDStr, ok := subscription.Metadata["tenant_id"]
+ if !ok {
+ log.Warnf(c, "tenant_id not found in subscription metadata for subscription @{SubscriptionID}", dto.Props{
+ "SubscriptionID": subscription.ID,
+ })
+ return c.Ok(web.Map{})
+ }
+
+ tenantID, err := strconv.Atoi(tenantIDStr)
+ if err != nil {
+ return c.Failure(errors.Wrap(err, "failed to parse tenant_id"))
+ }
+
+ cancel := &cmd.CancelStripeSubscription{
+ TenantID: tenantID,
+ }
+
+ if err := bus.Dispatch(c, cancel); err != nil {
+ return c.Failure(err)
+ }
+
+ log.Infof(c, "Stripe subscription cancelled for tenant @{TenantID}", dto.Props{
+ "TenantID": tenantID,
+ })
+
+ return c.Ok(web.Map{})
+}
diff --git a/app/models/cmd/billing.go b/app/models/cmd/billing.go
index d211fb3d8..735b25528 100644
--- a/app/models/cmd/billing.go
+++ b/app/models/cmd/billing.go
@@ -30,3 +30,13 @@ type LockExpiredTenants struct {
NumOfTenantsLocked int64
TenantsLocked []int
}
+
+type ActivateStripeSubscription struct {
+ TenantID int
+ CustomerID string
+ SubscriptionID string
+}
+
+type CancelStripeSubscription struct {
+ TenantID int
+}
diff --git a/app/models/entity/billing.go b/app/models/entity/billing.go
index f862cf5cb..660869de2 100644
--- a/app/models/entity/billing.go
+++ b/app/models/entity/billing.go
@@ -34,3 +34,8 @@ type BillingPayment struct {
Currency string `json:"currency"`
Date string `json:"date"`
}
+
+type StripeBillingState struct {
+ CustomerID string `json:"customerID"`
+ SubscriptionID string `json:"subscriptionID"`
+}
diff --git a/app/models/query/billing.go b/app/models/query/billing.go
index 7114c85a1..1a2b6a88f 100644
--- a/app/models/query/billing.go
+++ b/app/models/query/billing.go
@@ -15,3 +15,8 @@ type GetBillingSubscription struct {
// Output
Result *entity.BillingSubscription
}
+
+type GetStripeBillingState struct {
+ // Output
+ Result *entity.StripeBillingState
+}
diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go
index bea432651..e49ed89dc 100644
--- a/app/pkg/env/env.go
+++ b/app/pkg/env/env.go
@@ -56,7 +56,7 @@ type config struct {
JWTSecret string `env:"JWT_SECRET,required"`
PostCreationWithTagsEnabled bool `env:"POST_CREATION_WITH_TAGS_ENABLED,default=false"`
AllowAllowedSchemes bool `env:"ALLOW_ALLOWED_SCHEMES,default=true"`
- Paddle struct {
+ Paddle struct {
IsSandbox bool `env:"PADDLE_SANDBOX,default=false"`
VendorID string `env:"PADDLE_VENDOR_ID"`
VendorAuthCode string `env:"PADDLE_VENDOR_AUTHCODE"`
@@ -64,6 +64,11 @@ type config struct {
YearlyPlanID string `env:"PADDLE_YEARLY_PLAN_ID"`
PublicKey string `env:"PADDLE_PUBLIC_KEY"`
}
+ Stripe struct {
+ SecretKey string `env:"STRIPE_SECRET_KEY"`
+ WebhookSecret string `env:"STRIPE_WEBHOOK_SECRET"`
+ PriceID string `env:"STRIPE_PRICE_ID"`
+ }
Metrics struct {
Enabled bool `env:"METRICS_ENABLED,default=false"`
Port string `env:"METRICS_PORT,default=4000"`
diff --git a/app/services/sqlstore/dbEntities/billing.go b/app/services/sqlstore/dbEntities/billing.go
index 6619bfa8a..918848679 100644
--- a/app/services/sqlstore/dbEntities/billing.go
+++ b/app/services/sqlstore/dbEntities/billing.go
@@ -16,6 +16,11 @@ type BillingState struct {
SubscriptionEndsAt dbx.NullTime `db:"subscription_ends_at"`
}
+type StripeBillingState struct {
+ StripeCustomerID dbx.NullString `db:"stripe_customer_id"`
+ StripeSubscriptionID dbx.NullString `db:"stripe_subscription_id"`
+}
+
func (s *BillingState) ToModel(ctx context.Context) *entity.BillingState {
model := &entity.BillingState{
Status: enum.BillingStatus(s.Status),
diff --git a/app/services/sqlstore/postgres/billing.go b/app/services/sqlstore/postgres/billing.go
index 6d2c2cf34..d945da8db 100644
--- a/app/services/sqlstore/postgres/billing.go
+++ b/app/services/sqlstore/postgres/billing.go
@@ -4,6 +4,7 @@ import (
"context"
"time"
+ "github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
@@ -151,3 +152,57 @@ func getTrialingTenantContacts(ctx context.Context, q *query.GetTrialingTenantCo
return nil
})
}
+
+func getStripeBillingState(ctx context.Context, q *query.GetStripeBillingState) error {
+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {
+ state := dbEntities.StripeBillingState{}
+ err := trx.Get(&state,
+ `SELECT stripe_customer_id, stripe_subscription_id
+ FROM tenants_billing
+ WHERE tenant_id = $1`, tenant.ID)
+
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ // No billing record for this tenant, return empty state
+ q.Result = &entity.StripeBillingState{}
+ return nil
+ }
+ return err
+ }
+
+ q.Result = &entity.StripeBillingState{
+ CustomerID: state.StripeCustomerID.String,
+ SubscriptionID: state.StripeSubscriptionID.String,
+ }
+ return nil
+ })
+}
+
+func activateStripeSubscription(ctx context.Context, c *cmd.ActivateStripeSubscription) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
+ _, err := trx.Execute(`
+ INSERT INTO tenants_billing (tenant_id, trial_ends_at, paddle_subscription_id, paddle_plan_id, status, stripe_customer_id, stripe_subscription_id)
+ VALUES ($1, NOW(), '', '', 0, $2, $3)
+ ON CONFLICT (tenant_id) DO UPDATE
+ SET stripe_customer_id = $2, stripe_subscription_id = $3
+ `, c.TenantID, c.CustomerID, c.SubscriptionID)
+ if err != nil {
+ return errors.Wrap(err, "failed to activate stripe subscription")
+ }
+ return nil
+ })
+}
+
+func cancelStripeSubscription(ctx context.Context, c *cmd.CancelStripeSubscription) error {
+ return using(ctx, func(trx *dbx.Trx, _ *entity.Tenant, _ *entity.User) error {
+ _, err := trx.Execute(`
+ UPDATE tenants_billing
+ SET stripe_subscription_id = NULL
+ WHERE tenant_id = $1
+ `, c.TenantID)
+ if err != nil {
+ return errors.Wrap(err, "failed to cancel stripe subscription")
+ }
+ return nil
+ })
+}
diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.go
index 2925d284b..613ff18a9 100644
--- a/app/services/sqlstore/postgres/postgres.go
+++ b/app/services/sqlstore/postgres/postgres.go
@@ -142,6 +142,9 @@ func (s Service) Init() {
bus.AddHandler(cancelBillingSubscription)
bus.AddHandler(lockExpiredTenants)
bus.AddHandler(getTrialingTenantContacts)
+ bus.AddHandler(getStripeBillingState)
+ bus.AddHandler(activateStripeSubscription)
+ bus.AddHandler(cancelStripeSubscription)
bus.AddHandler(setSystemSettings)
bus.AddHandler(getSystemSettings)
diff --git a/go.mod b/go.mod
index bdc3e3d6b..cc9783e5e 100644
--- a/go.mod
+++ b/go.mod
@@ -185,6 +185,7 @@ require (
github.com/stbenjam/no-sprintf-host-port v0.1.1 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/stretchr/testify v1.9.0 // indirect
+ github.com/stripe/stripe-go/v83 v83.2.1 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c // indirect
github.com/tdakkota/asciicheck v0.2.0 // indirect
diff --git a/go.sum b/go.sum
index c565fe631..3086e20d9 100644
--- a/go.sum
+++ b/go.sum
@@ -583,6 +583,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/stripe/stripe-go/v83 v83.2.1 h1:8WPhpMjr8VyMWKUsCMoVvlWxYazuL5edajKX/RulfbA=
+github.com/stripe/stripe-go/v83 v83.2.1/go.mod h1:nRyDcLrJtwPPQUnKAFs9Bt1NnQvNhNiF6V19XHmPISE=
github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs=
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c h1:+aPplBwWcHBo6q9xrfWdMrT9o4kltkmmvpemgIjep/8=
diff --git a/migrations/202511211400_add_stripe_fields.sql b/migrations/202511211400_add_stripe_fields.sql
new file mode 100644
index 000000000..8eae7b5b7
--- /dev/null
+++ b/migrations/202511211400_add_stripe_fields.sql
@@ -0,0 +1,2 @@
+ALTER TABLE tenants_billing ADD COLUMN stripe_customer_id VARCHAR(255) NULL;
+ALTER TABLE tenants_billing ADD COLUMN stripe_subscription_id VARCHAR(255) NULL;
diff --git a/public/pages/Administration/pages/ManageBilling2.page.tsx b/public/pages/Administration/pages/ManageBilling2.page.tsx
new file mode 100644
index 000000000..ce6e7010e
--- /dev/null
+++ b/public/pages/Administration/pages/ManageBilling2.page.tsx
@@ -0,0 +1,61 @@
+import React, { useState } from "react"
+import { Button } from "@fider/components"
+import { VStack } from "@fider/components/layout"
+import { AdminPageContainer } from "../components/AdminBasePage"
+import { http } from "@fider/services"
+
+interface ManageBilling2PageProps {
+ stripeCustomerID: string
+ stripeSubscriptionID: string
+}
+
+const ManageBilling2Page = (props: ManageBilling2PageProps) => {
+ const [isLoading, setIsLoading] = useState(false)
+ const hasSubscription = !!props.stripeSubscriptionID
+
+ const openPortal = async () => {
+ setIsLoading(true)
+ const result = await http.post<{ url: string }>("/_api/admin/billing2/portal")
+ if (result.ok) {
+ window.location.href = result.data.url
+ } else {
+ setIsLoading(false)
+ }
+ }
+
+ const startCheckout = async () => {
+ setIsLoading(true)
+ const result = await http.post<{ url: string }>("/_api/admin/billing2/checkout")
+ if (result.ok) {
+ window.location.href = result.data.url
+ } else {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <AdminPageContainer id="p-admin-billing2" name="billing" title="Billing" subtitle="Manage your billing settings">
+ {hasSubscription ? (
+ <VStack spacing={4}>
+ <h3 className="text-display">Pro Plan</h3>
+ <p>You are currently on the Pro plan.</p>
+ <p>Click the button below to manage your subscription, update payment methods, or view billing history.</p>
+ <Button variant="primary" onClick={openPortal} disabled={isLoading}>
+ {isLoading ? "Loading..." : "Manage Billing"}
+ </Button>
+ </VStack>
+ ) : (
+ <VStack spacing={4}>
+ <h3 className="text-display">Free Plan</h3>
+ <p>You are currently on the Free plan.</p>
+ <p>Upgrade to Pro to unlock additional features and support the development of Fider.</p>
+ <Button variant="primary" onClick={startCheckout} disabled={isLoading}>
+ {isLoading ? "Loading..." : "Upgrade to Pro"}
+ </Button>
+ </VStack>
+ )}
+ </AdminPageContainer>
+ )
+}
+
+export default ManageBilling2Page