Open platform to collect and prioritize feedback
feat(billing): charge UK VAT on subscriptions via Stripe Tax Rates
Matt Robertseb9b56d42492
diff --git a/app/handlers/billing.go b/app/handlers/billing.goindex 1b2c84efe..3dda4c5b2 100644--- a/app/handlers/billing.go+++ b/app/handlers/billing.go@@ -66,29 +66,35 @@ func CreateStripePortalSession() web.HandlerFunc {}}-// createCheckoutSession creates a Stripe checkout session for the given price ID+// createCheckoutSession creates a Stripe checkout session for the given price ID.+// Uses setup mode so we can collect a billing address before the first invoice is+// generated — the subscription itself is created in the webhook handler, where we+// can attach the UK VAT tax rate if the customer's address country is GB.func createCheckoutSession(c *web.Context, priceID string) error {stripe.Key = env.Config.Stripe.SecretKeyreturnURL := c.BaseURL() + "/admin/billing"- tenantID := c.Tenant().ID+ tenantIDStr := fmt.Sprintf("%d", c.Tenant().ID)++ metadata := map[string]string{+ "tenant_id": tenantIDStr,+ "price_id": priceID,+ }params := &stripe.CheckoutSessionParams{- Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),- LineItems: []*stripe.CheckoutSessionLineItemParams{- {- Price: stripe.String(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),+ Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),+ PaymentMethodTypes: stripe.StringSlice([]string{"card"}),+ BillingAddressCollection: stripe.String(string(stripe.CheckoutSessionBillingAddressCollectionRequired)),+ CustomerCreation: stripe.String(string(stripe.CheckoutSessionCustomerCreationAlways)),+ SuccessURL: stripe.String(returnURL + "?checkout=success"),+ CancelURL: stripe.String(returnURL + "?checkout=cancelled"),+ Metadata: metadata,+ SetupIntentData: &stripe.CheckoutSessionSetupIntentDataParams{+ Metadata: metadata,},- SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{- Metadata: map[string]string{- "tenant_id": fmt.Sprintf("%d", tenantID),+ CustomText: &stripe.CheckoutSessionCustomTextParams{+ Submit: &stripe.CheckoutSessionCustomTextSubmitParams{+ Message: stripe.String("By submitting, you'll be subscribed to Pro at the price shown on the previous page. Your subscription starts immediately."),},},}diff --git a/app/handlers/webhooks/stripe.go b/app/handlers/webhooks/stripe.goindex 6e013c010..06dbaae64 100644--- a/app/handlers/webhooks/stripe.go+++ b/app/handlers/webhooks/stripe.go@@ -15,6 +15,9 @@ import ("github.com/getfider/fider/app/pkg/web""github.com/getfider/fider/app/tasks""github.com/stripe/stripe-go/v83"+ "github.com/stripe/stripe-go/v83/customer"+ "github.com/stripe/stripe-go/v83/setupintent"+ stripesub "github.com/stripe/stripe-go/v83/subscription""github.com/stripe/stripe-go/v83/webhook")@@ -48,7 +51,15 @@ func handleCheckoutSessionCompleted(c *web.Context, event stripe.Event) error {return c.Failure(errors.Wrap(err, "failed to parse checkout session"))}- // Get tenant ID from metadata+ if session.Mode == stripe.CheckoutSessionModeSetup {+ return handleSetupCheckoutCompleted(c, &session)+ }+ return handleSubscriptionCheckoutCompleted(c, &session)+}++// handleSubscriptionCheckoutCompleted handles the legacy mode=subscription flow.+// Kept to drain any in-flight sessions created before the switch to setup mode.+func handleSubscriptionCheckoutCompleted(c *web.Context, session *stripe.CheckoutSession) error {tenantIDStr, ok := session.Metadata["tenant_id"]if !ok {return c.Failure(errors.New("tenant_id not found in session metadata"))@@ -73,21 +84,125 @@ func handleCheckoutSessionCompleted(c *web.Context, event stripe.Event) error {"TenantID": tenantID,})- // Update UserList with new plan- if env.Config.UserList.Enabled {- getTenant := &query.GetTenantByDomain{Domain: strconv.Itoa(tenantID)}- if err := bus.Dispatch(c, getTenant); err == nil && getTenant.Result != nil {- c.Enqueue(tasks.UserListUpdateCompany(&dto.UserListUpdateCompany{- TenantID: tenantID,- Name: getTenant.Result.Name,- Plan: enum.PlanPro,- }))+ updateUserListPlan(c, tenantID, enum.PlanPro)++ return c.Ok(web.Map{})+}++// handleSetupCheckoutCompleted creates the Stripe Subscription server-side once the+// customer has supplied a payment method and billing address via Checkout. The address+// determines whether the UK VAT tax rate is attached, so VAT lands on the first invoice.+func handleSetupCheckoutCompleted(c *web.Context, session *stripe.CheckoutSession) error {+ if session.Customer == nil {+ return c.Failure(errors.New("setup-mode checkout session has no customer"))+ }+ if session.SetupIntent == nil {+ return c.Failure(errors.New("setup-mode checkout session has no setup intent"))+ }++ 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"))+ }++ priceID, ok := session.Metadata["price_id"]+ if !ok {+ return c.Failure(errors.New("price_id not found in session metadata"))+ }++ stripe.Key = env.Config.Stripe.SecretKey++ // In setup mode the address lives on the Customer, not on session.CustomerDetails.+ cus, err := customer.Get(session.Customer.ID, nil)+ if err != nil {+ return c.Failure(errors.Wrap(err, "failed to fetch customer"))+ }+ country := ""+ if cus.Address != nil {+ country = cus.Address.Country+ }++ si, err := setupintent.Get(session.SetupIntent.ID, nil)+ if err != nil {+ return c.Failure(errors.Wrap(err, "failed to fetch setup intent"))+ }+ if si.PaymentMethod == nil {+ return c.Failure(errors.New("setup intent has no payment method"))+ }++ subParams := &stripe.SubscriptionParams{+ Customer: stripe.String(session.Customer.ID),+ DefaultPaymentMethod: stripe.String(si.PaymentMethod.ID),+ Items: []*stripe.SubscriptionItemsParams{+ {Price: stripe.String(priceID)},+ },+ Metadata: map[string]string{+ "tenant_id": tenantIDStr,+ },+ }+ if country == "GB" {+ if env.Config.Stripe.UKVATTaxRateID == "" {+ return c.Failure(errors.New("UK customer detected but STRIPE_UK_VAT_TAX_RATE_ID is not configured"))}+ subParams.DefaultTaxRates = stripe.StringSlice([]string{env.Config.Stripe.UKVATTaxRateID})+ }+ // session.ID is stable per Checkout session, so a retried webhook returns the same subscription.+ subParams.SetIdempotencyKey(session.ID)++ newSub, err := stripesub.New(subParams)+ if err != nil {+ return c.Failure(errors.Wrap(err, "failed to create subscription"))}+ // Only activate the tenant if Stripe successfully collected payment on the first invoice.+ // allow_incomplete (the default) leaves the sub in `incomplete` if the charge failed (e.g. SCA+ // challenge on off-session payment) — in that case Stripe will keep retrying and eventually+ // fire subscription.deleted, which the existing handler already handles.+ if newSub.Status != stripe.SubscriptionStatusActive && newSub.Status != stripe.SubscriptionStatusTrialing {+ log.Warnf(c, "Stripe subscription created in non-active state '@{Status}' for tenant @{TenantID}", dto.Props{+ "Status": string(newSub.Status),+ "TenantID": tenantID,+ "SubscriptionID": newSub.ID,+ })+ return c.Ok(web.Map{})+ }++ activate := &cmd.ActivateStripeSubscription{+ TenantID: tenantID,+ CustomerID: session.Customer.ID,+ SubscriptionID: newSub.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,+ })++ updateUserListPlan(c, tenantID, enum.PlanPro)+return c.Ok(web.Map{})}+func updateUserListPlan(c *web.Context, tenantID int, plan enum.Plan) {+ if !env.Config.UserList.Enabled {+ return+ }+ getTenant := &query.GetTenantByDomain{Domain: strconv.Itoa(tenantID)}+ if err := bus.Dispatch(c, getTenant); err == nil && getTenant.Result != nil {+ c.Enqueue(tasks.UserListUpdateCompany(&dto.UserListUpdateCompany{+ TenantID: tenantID,+ Name: getTenant.Result.Name,+ Plan: plan,+ }))+ }+}+func handleSubscriptionDeleted(c *web.Context, event stripe.Event) error {var subscription stripe.Subscriptionif err := json.Unmarshal(event.Data.Raw, &subscription); err != nil {@@ -120,17 +235,7 @@ func handleSubscriptionDeleted(c *web.Context, event stripe.Event) error {"TenantID": tenantID,})- // Update UserList with new plan- if env.Config.UserList.Enabled {- getTenant := &query.GetTenantByDomain{Domain: strconv.Itoa(tenantID)}- if err := bus.Dispatch(c, getTenant); err == nil && getTenant.Result != nil {- c.Enqueue(tasks.UserListUpdateCompany(&dto.UserListUpdateCompany{- TenantID: tenantID,- Name: getTenant.Result.Name,- Plan: enum.PlanFree,- }))- }- }+ updateUserListPlan(c, tenantID, enum.PlanFree)return c.Ok(web.Map{})}diff --git a/app/pkg/env/env.go b/app/pkg/env/env.goindex fdf91b81c..a6ad8d84b 100644--- a/app/pkg/env/env.go+++ b/app/pkg/env/env.go@@ -57,10 +57,11 @@ type config struct {PostCreationWithTagsEnabled bool `env:"POST_CREATION_WITH_TAGS_ENABLED,default=false"`AllowAllowedSchemes bool `env:"ALLOW_ALLOWED_SCHEMES,default=true"`Stripe struct {- SecretKey string `env:"STRIPE_SECRET_KEY"`- WebhookSecret string `env:"STRIPE_WEBHOOK_SECRET"`- PriceID string `env:"STRIPE_PRICE_ID"`- AnnualPriceID string `env:"STRIPE_ANNUAL_PRICE_ID"`+ SecretKey string `env:"STRIPE_SECRET_KEY"`+ WebhookSecret string `env:"STRIPE_WEBHOOK_SECRET"`+ PriceID string `env:"STRIPE_PRICE_ID"`+ AnnualPriceID string `env:"STRIPE_ANNUAL_PRICE_ID"`+ UKVATTaxRateID string `env:"STRIPE_UK_VAT_TAX_RATE_ID"`}Metrics struct {Enabled bool `env:"METRICS_ENABLED,default=false"`