Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: move some pricing and stripe code (#19742)

ecmadaoef8238c41cd9
diff --git a/backend/enterprise/pricing/plan.go b/backend/enterprise/pricing/plan.go
new file mode 100644
index 0000000000..c26b2c921d
--- /dev/null
+++ b/backend/enterprise/pricing/plan.go
@@ -0,0 +1,40 @@
+// Package pricing defines plan limits and price calculation for SaaS subscriptions.
+package pricing
+
+import (
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// PlanLimitConfig defines pricing and limits for a plan.
+type PlanLimitConfig struct {
+ Plan storepb.SubscriptionPayload_Plan
+ SelfServicePurchase bool
+ FreeSeatCount int32
+ MaximumSeatCount int32 // -1 = unlimited
+ PricePerSeatPerMonth int64 // USD cents
+ InstanceCount int32 // fixed instance count included in the plan
+}
+
+var planLimits = map[storepb.SubscriptionPayload_Plan]*PlanLimitConfig{
+ storepb.SubscriptionPayload_TEAM: {
+ Plan: storepb.SubscriptionPayload_TEAM,
+ SelfServicePurchase: true,
+ FreeSeatCount: 0,
+ MaximumSeatCount: -1, // unlimited
+ PricePerSeatPerMonth: 2000, // $20/user/month
+ InstanceCount: 10,
+ },
+ storepb.SubscriptionPayload_ENTERPRISE: {
+ Plan: storepb.SubscriptionPayload_ENTERPRISE,
+ SelfServicePurchase: false,
+ FreeSeatCount: 0,
+ MaximumSeatCount: -1,
+ PricePerSeatPerMonth: 0, // custom pricing
+ InstanceCount: 0,
+ },
+}
+
+// GetPlanLimit returns the limit config for a plan, or nil if not found.
+func GetPlanLimit(plan storepb.SubscriptionPayload_Plan) *PlanLimitConfig {
+ return planLimits[plan]
+}
diff --git a/backend/enterprise/pricing/pricing.go b/backend/enterprise/pricing/pricing.go
new file mode 100644
index 0000000000..820683a26c
--- /dev/null
+++ b/backend/enterprise/pricing/pricing.go
@@ -0,0 +1,75 @@
+package pricing
+
+import (
+ "github.com/pkg/errors"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// PriceModel holds the inputs for price calculation.
+type PriceModel struct {
+ Plan *PlanLimitConfig
+ Interval storepb.SubscriptionPayload_BillingInterval
+ Seats int32
+}
+
+// NewPriceModel validates inputs and returns a PriceModel.
+func NewPriceModel(plan storepb.SubscriptionPayload_Plan, interval storepb.SubscriptionPayload_BillingInterval, seats int32) (*PriceModel, error) {
+ limit := GetPlanLimit(plan)
+ if limit == nil {
+ return nil, errors.Errorf("unknown plan %v", plan)
+ }
+ if !limit.SelfServicePurchase {
+ return nil, errors.Errorf("plan %v does not support self-service purchase", plan)
+ }
+ if interval == storepb.SubscriptionPayload_BILLING_INTERVAL_UNSPECIFIED {
+ return nil, errors.New("billing interval is required")
+ }
+ if seats < 1 {
+ return nil, errors.Errorf("seats must be at least 1, got %d", seats)
+ }
+ if limit.MaximumSeatCount >= 0 && seats > limit.MaximumSeatCount {
+ return nil, errors.Errorf("seats %d exceeds maximum %d for plan %v", seats, limit.MaximumSeatCount, plan)
+ }
+ return &PriceModel{
+ Plan: limit,
+ Interval: interval,
+ Seats: seats,
+ }, nil
+}
+
+// GetPrice returns the total price in USD cents.
+func (m *PriceModel) GetPrice() int64 {
+ billableSeats := m.Seats - m.Plan.FreeSeatCount
+ if billableSeats < 0 {
+ billableSeats = 0
+ }
+ monthlyPrice := int64(billableSeats) * m.Plan.PricePerSeatPerMonth
+
+ switch m.Interval {
+ case storepb.SubscriptionPayload_YEAR:
+ return monthlyPrice * 12
+ default:
+ return monthlyPrice
+ }
+}
+
+// GetStripeInterval returns the Stripe recurring interval string.
+func (m *PriceModel) GetStripeInterval() string {
+ if m.Interval == storepb.SubscriptionPayload_YEAR {
+ return "year"
+ }
+ return "month"
+}
+
+// GetPlanText returns a display name for the plan.
+func (m *PriceModel) GetPlanText() string {
+ switch m.Plan.Plan {
+ case storepb.SubscriptionPayload_TEAM:
+ return "Pro Plan"
+ case storepb.SubscriptionPayload_ENTERPRISE:
+ return "Enterprise Plan"
+ default:
+ return "Free Plan"
+ }
+}
diff --git a/backend/enterprise/pricing/pricing_test.go b/backend/enterprise/pricing/pricing_test.go
new file mode 100644
index 0000000000..9445d9973b
--- /dev/null
+++ b/backend/enterprise/pricing/pricing_test.go
@@ -0,0 +1,123 @@
+package pricing
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+func TestNewPriceModel(t *testing.T) {
+ tests := []struct {
+ name string
+ plan storepb.SubscriptionPayload_Plan
+ interval storepb.SubscriptionPayload_BillingInterval
+ seats int32
+ wantErr bool
+ }{
+ {
+ name: "valid TEAM monthly",
+ plan: storepb.SubscriptionPayload_TEAM,
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 5,
+ },
+ {
+ name: "valid TEAM yearly",
+ plan: storepb.SubscriptionPayload_TEAM,
+ interval: storepb.SubscriptionPayload_YEAR,
+ seats: 1,
+ },
+ {
+ name: "enterprise not self-service",
+ plan: storepb.SubscriptionPayload_ENTERPRISE,
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 5,
+ wantErr: true,
+ },
+ {
+ name: "unknown plan",
+ plan: storepb.SubscriptionPayload_PLAN_UNSPECIFIED,
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 5,
+ wantErr: true,
+ },
+ {
+ name: "zero seats",
+ plan: storepb.SubscriptionPayload_TEAM,
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 0,
+ wantErr: true,
+ },
+ {
+ name: "unspecified interval",
+ plan: storepb.SubscriptionPayload_TEAM,
+ interval: storepb.SubscriptionPayload_BILLING_INTERVAL_UNSPECIFIED,
+ seats: 5,
+ wantErr: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := NewPriceModel(tc.plan, tc.interval, tc.seats)
+ if tc.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
+
+func TestGetPrice(t *testing.T) {
+ tests := []struct {
+ name string
+ interval storepb.SubscriptionPayload_BillingInterval
+ seats int32
+ wantCents int64
+ }{
+ {
+ name: "1 user monthly",
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 1,
+ wantCents: 2000, // $20
+ },
+ {
+ name: "5 users monthly",
+ interval: storepb.SubscriptionPayload_MONTH,
+ seats: 5,
+ wantCents: 10000, // $100
+ },
+ {
+ name: "1 user yearly",
+ interval: storepb.SubscriptionPayload_YEAR,
+ seats: 1,
+ wantCents: 24000, // $240
+ },
+ {
+ name: "10 users yearly",
+ interval: storepb.SubscriptionPayload_YEAR,
+ seats: 10,
+ wantCents: 240000, // $2400
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ m, err := NewPriceModel(storepb.SubscriptionPayload_TEAM, tc.interval, tc.seats)
+ require.NoError(t, err)
+ require.Equal(t, tc.wantCents, m.GetPrice())
+ })
+ }
+}
+
+func TestGetStripeInterval(t *testing.T) {
+ m, err := NewPriceModel(storepb.SubscriptionPayload_TEAM, storepb.SubscriptionPayload_MONTH, 1)
+ require.NoError(t, err)
+ require.Equal(t, "month", m.GetStripeInterval())
+
+ m, err = NewPriceModel(storepb.SubscriptionPayload_TEAM, storepb.SubscriptionPayload_YEAR, 1)
+ require.NoError(t, err)
+ require.Equal(t, "year", m.GetStripeInterval())
+}
diff --git a/backend/plugin/stripe/stripe.go b/backend/plugin/stripe/stripe.go
new file mode 100644
index 0000000000..eefd8d409b
--- /dev/null
+++ b/backend/plugin/stripe/stripe.go
@@ -0,0 +1,381 @@
+// Package stripe provides Stripe integration for SaaS subscription management.
+package stripe
+
+import (
+ "fmt"
+ "log/slog"
+ "strconv"
+
+ "github.com/pkg/errors"
+ stripego "github.com/stripe/stripe-go/v82"
+ billingportalsession "github.com/stripe/stripe-go/v82/billingportal/session"
+ "github.com/stripe/stripe-go/v82/charge"
+ checkoutsession "github.com/stripe/stripe-go/v82/checkout/session"
+ "github.com/stripe/stripe-go/v82/invoice"
+ "github.com/stripe/stripe-go/v82/price"
+ "github.com/stripe/stripe-go/v82/promotioncode"
+ "github.com/stripe/stripe-go/v82/refund"
+ stripesubscription "github.com/stripe/stripe-go/v82/subscription"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/enterprise/pricing"
+)
+
+// WebhookSource is used to filter webhook events from our checkout sessions.
+const WebhookSource = "bytebase"
+
+// Init sets the Stripe API key. Must be called before any other Stripe operations.
+func Init(apiKey string) {
+ stripego.Key = apiKey
+}
+
+// CheckoutParams contains the parameters for creating a Stripe Checkout Session.
+type CheckoutParams struct {
+ Workspace string
+ PriceModel *pricing.PriceModel
+ SuccessURL string
+ CancelURL string
+ PromotionCode string // optional promotion code string
+}
+
+// CreateCheckoutSession creates a Stripe Checkout Session and returns the checkout URL.
+func CreateCheckoutSession(params *CheckoutParams) (string, error) {
+ priceInCents := params.PriceModel.GetPrice()
+ metadata := GetMetadata(params.Workspace, params.PriceModel)
+
+ checkoutParams := &stripego.CheckoutSessionParams{
+ AutomaticTax: &stripego.CheckoutSessionAutomaticTaxParams{
+ Enabled: stripego.Bool(false),
+ },
+ Mode: stripego.String(string(stripego.CheckoutSessionModeSubscription)),
+ LineItems: []*stripego.CheckoutSessionLineItemParams{
+ {
+ PriceData: &stripego.CheckoutSessionLineItemPriceDataParams{
+ ProductData: &stripego.CheckoutSessionLineItemPriceDataProductDataParams{
+ Name: stripego.String(fmt.Sprintf("%s License", params.PriceModel.GetPlanText())),
+ Description: stripego.String(fmt.Sprintf(
+ "%d Instances, %d Users",
+ params.PriceModel.Plan.InstanceCount,
+ params.PriceModel.Seats,
+ )),
+ },
+ UnitAmount: stripego.Int64(priceInCents),
+ Currency: stripego.String(string(stripego.CurrencyUSD)),
+ Recurring: &stripego.CheckoutSessionLineItemPriceDataRecurringParams{
+ Interval: stripego.String(params.PriceModel.GetStripeInterval()),
+ IntervalCount: stripego.Int64(1),
+ },
+ },
+ Quantity: stripego.Int64(1),
+ },
+ },
+ SuccessURL: stripego.String(params.SuccessURL),
+ CancelURL: stripego.String(params.CancelURL),
+ SubscriptionData: &stripego.CheckoutSessionSubscriptionDataParams{
+ Metadata: metadata,
+ },
+ PaymentMethodCollection: stripego.String(stripego.CheckoutSessionPaymentMethodCollectionAlways),
+ }
+
+ if params.PromotionCode != "" {
+ promo := GetPromotionByCode(params.PromotionCode, priceInCents)
+ if promo != nil {
+ checkoutParams.Discounts = []*stripego.CheckoutSessionDiscountParams{
+ {PromotionCode: stripego.String(promo.ID)},
+ }
+ }
+ }
+
+ s, err := checkoutsession.New(checkoutParams)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to create checkout session")
+ }
+ return s.URL, nil
+}
+
+// CancelSubscription cancels a Stripe subscription.
+// If prorate is true, cancels immediately with proration and processes refund.
+// If prorate is false, schedules cancellation at the end of the current billing period.
+func CancelSubscription(stripeSubID string, workspace string, prorate bool) (*stripego.Subscription, error) {
+ if !prorate {
+ // Schedule cancellation at period end — subscription remains active until then.
+ sub, err := stripesubscription.Update(stripeSubID, &stripego.SubscriptionParams{
+ CancelAtPeriodEnd: stripego.Bool(true),
+ })
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to schedule cancellation for stripe subscription %s", stripeSubID)
+ }
+ return sub, nil
+ }
+
+ // Immediate cancellation with proration.
+ sub, err := stripesubscription.Cancel(stripeSubID, &stripego.SubscriptionCancelParams{
+ InvoiceNow: stripego.Bool(true),
+ Prorate: stripego.Bool(true),
+ Expand: []*string{stripego.String("customer")},
+ })
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to cancel stripe subscription %s", stripeSubID)
+ }
+
+ if err := RefundFromSubscription(sub, workspace); err != nil {
+ slog.Error("failed to refund after cancellation",
+ log.BBError(err),
+ slog.String("stripe_subscription_id", stripeSubID),
+ slog.String("workspace", workspace),
+ )
+ // Don't fail the cancellation itself
+ }
+
+ return sub, nil
+}
+
+// DirectSubscriptionParams contains the parameters for creating a Stripe subscription directly.
+type DirectSubscriptionParams struct {
+ CustomerID string
+ PaymentMethodID string // optional, from old subscription
+ PriceModel *pricing.PriceModel
+ Metadata map[string]string
+}
+
+// CreateSubscriptionDirect creates a new Stripe subscription using an existing customer's payment method.
+func CreateSubscriptionDirect(params *DirectSubscriptionParams) (*stripego.Subscription, error) {
+ priceInCents := params.PriceModel.GetPrice()
+
+ newPrice, err := price.New(&stripego.PriceParams{
+ ProductData: &stripego.PriceProductDataParams{
+ Name: stripego.String(fmt.Sprintf("%s License", params.PriceModel.GetPlanText())),
+ },
+ UnitAmount: stripego.Int64(priceInCents),
+ Currency: stripego.String(string(stripego.CurrencyUSD)),
+ Recurring: &stripego.PriceRecurringParams{
+ Interval: stripego.String(params.PriceModel.GetStripeInterval()),
+ IntervalCount: stripego.Int64(1),
+ },
+ })
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create stripe price")
+ }
+
+ subParams := &stripego.SubscriptionParams{
+ Customer: stripego.String(params.CustomerID),
+ Items: []*stripego.SubscriptionItemsParams{
+ {
+ Price: stripego.String(newPrice.ID),
+ Quantity: stripego.Int64(1),
+ },
+ },
+ Metadata: params.Metadata,
+ PaymentBehavior: stripego.String("allow_incomplete"),
+ Expand: []*string{stripego.String("customer")},
+ }
+
+ if params.PaymentMethodID != "" {
+ subParams.DefaultPaymentMethod = stripego.String(params.PaymentMethodID)
+ }
+
+ sub, err := stripesubscription.New(subParams)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create stripe subscription")
+ }
+ return sub, nil
+}
+
+// GetSubscription retrieves a Stripe subscription by ID with optional expand fields.
+func GetSubscription(stripeSubID string, expand []string) (*stripego.Subscription, error) {
+ params := &stripego.SubscriptionParams{}
+ for _, e := range expand {
+ params.AddExpand(e)
+ }
+ sub, err := stripesubscription.Get(stripeSubID, params)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get stripe subscription %s", stripeSubID)
+ }
+ return sub, nil
+}
+
+// UpdateSubscriptionMetadata updates the metadata on a Stripe subscription.
+func UpdateSubscriptionMetadata(stripeSubID string, metadata map[string]string) error {
+ _, err := stripesubscription.Update(stripeSubID, &stripego.SubscriptionParams{
+ Metadata: metadata,
+ })
+ return errors.Wrapf(err, "failed to update stripe subscription metadata %s", stripeSubID)
+}
+
+// GetMetadata builds the metadata map for a Stripe subscription.
+func GetMetadata(workspace string, model *pricing.PriceModel) map[string]string {
+ return map[string]string{
+ "workspace": workspace,
+ "plan": model.Plan.Plan.String(),
+ "interval": model.Interval.String(),
+ "instance_count": strconv.Itoa(int(model.Plan.InstanceCount)),
+ "user_count": strconv.Itoa(int(model.Seats)),
+ "source": WebhookSource,
+ }
+}
+
+// FindLastPaidInvoice finds the last paid invoice for a subscription.
+func FindLastPaidInvoice(sub *stripego.Subscription) (*stripego.Invoice, error) {
+ return findLastInvoiceByStatus(sub, stripego.InvoiceStatusPaid)
+}
+
+func findLastInvoiceByStatus(sub *stripego.Subscription, status stripego.InvoiceStatus) (*stripego.Invoice, error) {
+ if sub.Customer == nil || sub.Customer.ID == "" {
+ return nil, errors.Errorf("no customer in subscription %s", sub.ID)
+ }
+
+ invoices := invoice.List(&stripego.InvoiceListParams{
+ Subscription: stripego.String(sub.ID),
+ Customer: stripego.String(sub.Customer.ID),
+ Status: stripego.String(string(status)),
+ ListParams: stripego.ListParams{Limit: stripego.Int64(1)},
+ })
+ if !invoices.Next() {
+ if err := invoices.Err(); err != nil {
+ return nil, errors.Wrapf(err, "error listing invoices for subscription %s", sub.ID)
+ }
+ return nil, errors.Errorf("no %s invoices found for subscription %s", status, sub.ID)
+ }
+
+ inv := invoices.Invoice()
+ if len(inv.Lines.Data) == 0 {
+ return nil, errors.Errorf("no line items in invoice for subscription %s", sub.ID)
+ }
+ if inv.Lines.Data[0].Period == nil {
+ return nil, errors.Errorf("no period in invoice line item for subscription %s", sub.ID)
+ }
+
+ return inv, nil
+}
+
+// RefundFromSubscription refunds proration credit after subscription cancellation.
+func RefundFromSubscription(sub *stripego.Subscription, workspace string) error {
+ customerID := sub.Customer.ID
+ if customerID == "" {
+ return errors.Errorf("no customer ID in subscription %s", sub.ID)
+ }
+
+ draftInvoice, err := findLastInvoiceByStatus(sub, stripego.InvoiceStatusDraft)
+ if err != nil {
+ return err
+ }
+
+ var refundAmount int64
+ for _, line := range draftInvoice.Lines.Data {
+ if line.Amount < 0 {
+ refundAmount += -line.Amount
+ }
+ }
+
+ if refundAmount < 100 { // Skip refunds under $1
+ return nil
+ }
+
+ slog.Info("processing proration refund",
+ slog.String("stripe_subscription_id", sub.ID),
+ slog.String("workspace", workspace),
+ slog.Int64("refund_amount_cents", refundAmount),
+ )
+
+ return refundCustomerBalance(customerID, refundAmount, workspace, sub.ID)
+}
+
+// refundCustomerBalance refunds a credit balance across multiple charges.
+func refundCustomerBalance(customerID string, totalRefundAmount int64, workspace string, stripeSubID string) error {
+ charges := charge.List(&stripego.ChargeListParams{
+ Customer: stripego.String(customerID),
+ ListParams: stripego.ListParams{Limit: stripego.Int64(20)},
+ })
+
+ remaining := totalRefundAmount
+ refundCount := 0
+
+ for charges.Next() && remaining > 0 {
+ ch := charges.Charge()
+ if !ch.Paid || ch.Refunded {
+ continue
+ }
+ available := ch.Amount - ch.AmountRefunded
+ if available <= 0 {
+ continue
+ }
+
+ amount := min(remaining, available)
+ result, err := refund.New(&stripego.RefundParams{
+ Charge: stripego.String(ch.ID),
+ Amount: stripego.Int64(amount),
+ Reason: stripego.String(string(stripego.RefundReasonRequestedByCustomer)),
+ Metadata: map[string]string{
+ "workspace": workspace,
+ "stripe_subscription": stripeSubID,
+ "refund_reason": "subscription_cancellation_proration",
+ "total_balance_refund": fmt.Sprintf("%d", totalRefundAmount),
+ "partial_refund_amount": fmt.Sprintf("%d", amount),
+ },
+ })
+ if err != nil {
+ slog.Error("failed to create partial refund",
+ slog.String("charge_id", ch.ID),
+ slog.Int64("refund_amount", amount),
+ log.BBError(err),
+ )
+ continue
+ }
+
+ slog.Info("created partial refund",
+ slog.String("refund_id", result.ID),
+ slog.String("charge_id", ch.ID),
+ slog.Int64("amount_cents", amount),
+ )
+ remaining -= amount
+ refundCount++
+ }
+
+ if err := charges.Err(); err != nil {
+ return errors.Wrap(err, "error listing charges for refund")
+ }
+
+ if remaining > 0 {
+ return errors.Errorf("incomplete refund for workspace %s: %d of %d cents remain unrefunded after %d charges",
+ workspace, remaining, totalRefundAmount, refundCount)
+ }
+
+ slog.Info("refund complete",
+ slog.String("workspace", workspace),
+ slog.Int64("total_refunded_cents", totalRefundAmount),
+ slog.Int("refund_count", refundCount),
+ )
+ return nil
+}
+
+// CreateBillingPortalSession creates a Stripe Billing Portal session for invoice management.
+func CreateBillingPortalSession(customerID string, returnURL string) (string, error) {
+ s, err := billingportalsession.New(&stripego.BillingPortalSessionParams{
+ Customer: stripego.String(customerID),
+ ReturnURL: stripego.String(returnURL),
+ })
+ if err != nil {
+ return "", errors.Wrap(err, "failed to create billing portal session")
+ }
+ return s.URL, nil
+}
+
+// GetPromotionByCode looks up an active promotion code eligible for first-time customers.
+func GetPromotionByCode(code string, priceInCents int64) *stripego.PromotionCode {
+ iter := promotioncode.List(&stripego.PromotionCodeListParams{
+ Code: stripego.String(code),
+ Active: stripego.Bool(true),
+ })
+ for iter.Next() {
+ promo := iter.PromotionCode()
+ if v := promo.Restrictions; v != nil {
+ if v.MinimumAmount <= priceInCents && v.FirstTimeTransaction {
+ return promo
+ }
+ }
+ }
+ if err := iter.Err(); err != nil {
+ slog.Error("failed to get promotion", log.BBError(err), slog.String("code", code))
+ }
+ return nil
+}
diff --git a/backend/store/subscription.go b/backend/store/subscription.go
new file mode 100644
index 0000000000..bb7ffc88f3
--- /dev/null
+++ b/backend/store/subscription.go
@@ -0,0 +1,89 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "time"
+
+ "github.com/pkg/errors"
+ "google.golang.org/protobuf/encoding/protojson"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// SubscriptionMessage is the message for a workspace subscription.
+type SubscriptionMessage struct {
+ Workspace string
+ Payload *storepb.SubscriptionPayload
+ Etag string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+// CreateSubscription creates a new subscription.
+func (s *Store) CreateSubscription(ctx context.Context, create *SubscriptionMessage) (*SubscriptionMessage, error) {
+ payload, err := protojson.Marshal(create.Payload)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to marshal payload")
+ }
+
+ if err := s.GetDB().QueryRowContext(ctx,
+ `INSERT INTO subscription (workspace, payload) VALUES ($1, $2) RETURNING created_at, updated_at`,
+ create.Workspace, payload,
+ ).Scan(&create.CreatedAt, &create.UpdatedAt); err != nil {
+ return nil, errors.Wrapf(err, "failed to insert subscription")
+ }
+ create.Etag = generateEtag(create.UpdatedAt)
+
+ return create, nil
+}
+
+// GetSubscriptionByWorkspace gets a subscription by workspace.
+// Returns (nil, nil) if not found.
+func (s *Store) GetSubscriptionByWorkspace(ctx context.Context, workspace string) (*SubscriptionMessage, error) {
+ sub := &SubscriptionMessage{
+ Payload: &storepb.SubscriptionPayload{},
+ }
+ var payload []byte
+ if err := s.GetDB().QueryRowContext(ctx,
+ `SELECT workspace, payload, created_at, updated_at FROM subscription WHERE workspace = $1`,
+ workspace,
+ ).Scan(&sub.Workspace, &payload, &sub.CreatedAt, &sub.UpdatedAt); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return nil, errors.Wrapf(err, "failed to get subscription")
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal(payload, sub.Payload); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal payload")
+ }
+ sub.Etag = generateEtag(sub.UpdatedAt)
+ return sub, nil
+}
+
+// UpdateSubscription updates a subscription by workspace.
+func (s *Store) UpdateSubscription(ctx context.Context, workspace string, payload *storepb.SubscriptionPayload) (*SubscriptionMessage, error) {
+ p, err := protojson.Marshal(payload)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to marshal payload")
+ }
+
+ sub := &SubscriptionMessage{
+ Payload: &storepb.SubscriptionPayload{},
+ }
+ var payloadBytes []byte
+ if err := s.GetDB().QueryRowContext(ctx,
+ `UPDATE subscription SET payload = $1, updated_at = now() WHERE workspace = $2
+ RETURNING workspace, payload, created_at, updated_at`,
+ p, workspace,
+ ).Scan(&sub.Workspace, &payloadBytes, &sub.CreatedAt, &sub.UpdatedAt); err != nil {
+ return nil, errors.Wrapf(err, "failed to update subscription")
+ }
+ if err := common.ProtojsonUnmarshaler.Unmarshal(payloadBytes, sub.Payload); err != nil {
+ return nil, errors.Wrapf(err, "failed to unmarshal payload")
+ }
+ sub.Etag = fmt.Sprintf("%d", sub.UpdatedAt.UnixMilli())
+ return sub, nil
+}
diff --git a/docs/plans/saas/08.in-app-purchase.md b/docs/plans/saas/08.in-app-purchase.md
index 34570e7422..9c7e05c5f7 100644
--- a/docs/plans/saas/08.in-app-purchase.md
+++ b/docs/plans/saas/08.in-app-purchase.md
@@ -41,60 +41,61 @@ Move the purchase workflow from the hub codebase into the Bytebase codebase so S
### 1. Database: `subscription` Table
-Add a new `subscription` table (workspace-scoped). This replaces hub's subscription table with `org` → `workspace`.
+Minimal table — `workspace` is the PK (one subscription per workspace). All subscription data lives in `payload` JSONB so the schema can evolve without DDL migrations. `etag` is derived from `updated_at` (same pattern as IAM policy).
```sql
CREATE TABLE subscription (
- id text NOT NULL,
- workspace text NOT NULL REFERENCES workspace(resource_id),
- status text NOT NULL DEFAULT '', -- 'PENDING', 'ACTIVE', 'PAUSED', 'CANCELED'
- started_at timestamptz NOT NULL DEFAULT now(),
- expires_at timestamptz NOT NULL DEFAULT now(),
- payload jsonb NOT NULL DEFAULT '{}', -- SubscriptionPayload proto
- etag text NOT NULL DEFAULT '',
+ workspace text NOT NULL REFERENCES workspace(resource_id) PRIMARY KEY,
+ -- Stored as SubscriptionPayload (proto/store/store/subscription.proto)
+ payload jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now(),
- updated_at timestamptz NOT NULL DEFAULT now(),
- PRIMARY KEY (id),
- UNIQUE (workspace)
+ updated_at timestamptz NOT NULL DEFAULT now()
);
```
-The table is intentionally minimal — only `status`, `started_at`, `expires_at` are top-level columns because they are queried/filtered on. All billing details live in `payload` JSONB so the schema can evolve without DDL migrations.
-
-**Key differences from hub**:
-- `workspace` FK instead of `org` FK.
-- `seat`, `interval`, `instance_count` moved into `payload` (not top-level columns).
-- One subscription per workspace (unique constraint).
-
**Payload** (proto, stored as JSONB via `protojson.Marshal` → camelCase keys):
```protobuf
-// In proto/store/store/subscription.proto
-
-import "v1/subscription_service.proto";
-
+// proto/store/store/subscription.proto
message SubscriptionPayload {
- // Stripe integration
- string stripe_subscription_id = 1;
- string stripe_customer_id = 2;
+ enum Status {
+ STATUS_UNSPECIFIED = 0;
+ PENDING = 1;
+ ACTIVE = 2;
+ PAUSED = 3;
+ CANCELED = 4;
+ }
- // Billing details — enums reuse the v1 API types
- bytebase.v1.PlanType plan = 3;
- BillingInterval interval = 4;
- int32 seat = 5;
- int32 instance_count = 6; // fixed at 10 for TEAM, but stored for license generation
+ enum Plan {
+ PLAN_UNSPECIFIED = 0;
+ TEAM = 1;
+ ENTERPRISE = 2;
+ }
enum BillingInterval {
BILLING_INTERVAL_UNSPECIFIED = 0;
MONTH = 1;
YEAR = 2;
}
+
+ // Lifecycle
+ Status status = 1;
+ google.protobuf.Timestamp started_at = 2;
+ google.protobuf.Timestamp expires_at = 3;
+
+ // Billing details
+ Plan plan = 4;
+ BillingInterval interval = 5;
+ int32 seat = 6;
+ int32 instance_count = 7;
+
+ // Stripe integration
+ string stripe_subscription_id = 8;
+ string stripe_customer_id = 9;
}
```
-Note: `plan` reuses the existing `bytebase.v1.PlanType` enum (`FREE`, `TEAM`, `ENTERPRISE`) from `subscription_service.proto`. `interval` uses a local `BillingInterval` enum since no equivalent exists in v1 today. `protojson.Marshal` serializes enums as their string names (e.g., `"TEAM"`, `"MONTH"`) in JSONB.
-
-No `DeploymentType` (always SaaS). No `PaddlePayload`. No `Source` enum (always Stripe). Billing fields in the payload keep the table lean and make it easy to add new fields (e.g., future per-instance pricing) without schema changes.
+`Plan` and `BillingInterval` are local enums (store proto does not import v1 proto). `protojson.Marshal` serializes enums as string names (e.g., `"TEAM"`, `"MONTH"`) in JSONB.
### 2. Store Layer
@@ -103,28 +104,20 @@ New file: `backend/store/subscription.go`
```go
type SubscriptionMessage struct {
Workspace string
- Status string // "PENDING", "ACTIVE", "PAUSED", "CANCELED"
- StartedAt time.Time
- ExpiresAt time.Time
- Payload *storepb.SubscriptionPayload // seat, interval, instance_count, plan, stripe IDs
- Etag string
+ Payload *storepb.SubscriptionPayload
+ Etag string // derived from UpdatedAt (unix millis), not stored
CreatedAt time.Time
UpdatedAt time.Time
}
-type UpdateSubscriptionMessage struct {
- Etag *string
- Status *string
- ExpiresAt *time.Time
- Payload *storepb.SubscriptionPayload // updates billing details + stripe IDs atomically
-}
-
-func (s *Store) CreateSubscription(ctx context.Context, create *SubscriptionMessage) (*SubscriptionMessage, error)
-func (s *Store) GetSubscriptionByWorkspace(ctx context.Context, workspace string) (*SubscriptionMessage, error)
-func (s *Store) UpdateSubscription(ctx context.Context, workspace string, update *UpdateSubscriptionMessage) (*SubscriptionMessage, error)
+func (s *Store) CreateSubscription(ctx, create *SubscriptionMessage) (*SubscriptionMessage, error)
+func (s *Store) GetSubscriptionByWorkspace(ctx, workspace string) (*SubscriptionMessage, error)
+func (s *Store) UpdateSubscription(ctx, workspace string, payload *SubscriptionPayload) (*SubscriptionMessage, error)
```
-No `ID` column — `workspace` is the PK (one subscription per workspace). No `FindSubscriptionMessage` — all lookups are by workspace directly.
+- `workspace` is the PK — no separate ID, no find struct.
+- `Etag` derived from `updated_at` via `generateEtag()` (same as IAM policy), not a stored column.
+- `UpdateSubscription` always replaces the full payload atomically.
### 3. Proto Changes
@@ -342,7 +335,7 @@ func CreateSubscriptionDirect(params *DirectSubscriptionParams) (*stripe.Subscri
func RefundFromSubscription(sub *stripe.Subscription, internalSubID string) error { ... }
// GetMetadata builds metadata map for Stripe subscription.
-func GetMetadata(subID string, plan string, interval string, seats int) map[string]string { ... }
+func GetMetadata(workspace string, plan string, interval string, seats int) map[string]string { ... }
// FindLastPaidInvoice finds the last paid invoice for a subscription.
func FindLastPaidInvoice(sub *stripe.Subscription) (*stripe.Invoice, error) { ... }
@@ -377,7 +370,7 @@ type WebhookHandler struct {
func (h *WebhookHandler) HandleCallback(c echo.Context) error {
// 1. Verify Stripe signature
// 2. Parse event
- // 3. Filter by metadata source="bytebase_hub"
+ // 3. Filter by metadata source
// 4. Route to handler by event type
}
```
@@ -386,8 +379,8 @@ func (h *WebhookHandler) HandleCallback(c echo.Context) error {
| Event | Handler |
|-------|---------|
-| `customer.subscription.created` | Extract metadata, update subscription with Stripe IDs |
-| `customer.subscription.updated` | Map Stripe status → internal status |
+| `customer.subscription.created` | Extract metadata, update subscription payload with Stripe IDs |
+| `customer.subscription.updated` | Map Stripe status → `SubscriptionPayload.Status` |
| `customer.subscription.paused` | Set PAUSED, invalidate license cache |
| `customer.subscription.resumed` | Set ACTIVE, regenerate + store license |
| `customer.subscription.deleted` | Set CANCELED, clear license |
@@ -397,12 +390,12 @@ func (h *WebhookHandler) HandleCallback(c echo.Context) error {
```go
func (h *WebhookHandler) activateLicense(ctx context.Context, sub *SubscriptionMessage) error {
- // 1. Build license claims from subscription data
+ // 1. Build license claims from subscription payload
claims := &enterprise.Claims{
- Seats: sub.Seats,
- ActiveInstances: 10, // fixed for TEAM
- Instances: 10,
- Plan: sub.Payload.Plan,
+ Seats: int(sub.Payload.Seat),
+ ActiveInstances: int(sub.Payload.InstanceCount),
+ Instances: int(sub.Payload.InstanceCount),
+ Plan: sub.Payload.Plan.String(),
WorkspaceID: sub.Workspace,
}
// 2. Sign JWT using the license private key
@@ -581,34 +574,38 @@ The `?from=STRIPE` query param triggers the pending payment polling view (same p
## Implementation Plan
-### Phase 1: Backend Foundation
+### Phase 1: Backend Foundation (done)
+
+1. **Database migration** — `0014##add_subscription_table.sql`. Minimal table: `workspace` PK + `payload` + timestamps.
+2. **Store proto** — `proto/store/store/subscription.proto` with `SubscriptionPayload` (enums for `Status`, `Plan`, `BillingInterval`; fields for lifecycle, billing, Stripe IDs).
+3. **Store layer** — `backend/store/subscription.go` with `CreateSubscription`, `GetSubscriptionByWorkspace`, `UpdateSubscription`.
+
+### Phase 2: Pricing & Stripe
-1. **Database migration** — Add `subscription` table. Add `SubscriptionPayload` to `proto/store/`.
-2. **Store layer** — `backend/store/subscription.go` with CRUD methods.
-3. **Pricing module** — `backend/enterprise/pricing/` with plan config and price calculation.
-4. **Stripe plugin** — `backend/plugin/stripe/` with checkout session, cancellation, refund.
+4. **Pricing module** — `backend/enterprise/pricing/` with plan config and price calculation.
+5. **Stripe plugin** — `backend/plugin/stripe/` with checkout session, cancellation, refund.
-### Phase 2: API & Webhooks
+### Phase 3: API & Webhooks
-5. **Proto definitions** — Add new RPCs and messages to `subscription_service.proto`.
-6. **Subscription service** — Implement `CreatePurchase`, `UpdatePurchase`, `CancelPurchase`, `GetPaymentInfo`, `ListPlans`.
-7. **Stripe webhook** — `backend/api/stripe/webhook.go`, register in `echo_routes.go`.
-8. **License signing** — Add `CreateLicense` to `LicenseService`, load private key in SaaS mode.
-9. **SaaS gate** — `UpdateSubscription` blocked in SaaS, purchase APIs blocked in non-SaaS.
+6. **Proto definitions** — Add new RPCs and messages to `subscription_service.proto`.
+7. **Subscription service** — Implement `CreatePurchase`, `UpdatePurchase`, `CancelPurchase`, `GetPaymentInfo`, `ListPlans`.
+8. **Stripe webhook** — `backend/api/stripe/webhook.go`, register in `echo_routes.go`.
+9. **License signing** — Add `CreateLicense` to `LicenseService`, load private key in SaaS mode.
+10. **SaaS gate** — `UpdateSubscription` blocked in SaaS, purchase APIs blocked in non-SaaS.
-### Phase 3: Frontend
+### Phase 4: Frontend
-10. **Subscription store** — Add purchase actions and state.
-11. **Plan selection UI** — `PurchasePlanCard.vue` with seat counter and billing toggle.
-12. **Subscription management** — Status display, payment info, cancel flow.
-13. **Pending payment** — Polling view after Stripe redirect.
-14. **Conditional rendering** — Show purchase UI in SaaS, license upload in self-hosted.
+11. **Subscription store** — Add purchase actions and state.
+12. **Plan selection UI** — `PurchasePlanCard.vue` with seat counter and billing toggle.
+13. **Subscription management** — Status display, payment info, cancel flow.
+14. **Pending payment** — Polling view after Stripe redirect.
+15. **Conditional rendering** — Show purchase UI in SaaS, license upload in self-hosted.
-### Phase 4: Integration & Testing
+### Phase 5: Integration & Testing
-15. **Stripe test mode** — End-to-end testing with Stripe test keys.
-16. **Webhook testing** — Stripe CLI (`stripe listen --forward-to`) for local webhook testing.
-17. **Edge cases** — Expired subscription, failed payment retry, concurrent updates (etag), plan changes mid-billing.
+16. **Stripe test mode** — End-to-end testing with Stripe test keys.
+17. **Webhook testing** — Stripe CLI (`stripe listen --forward-to`) for local webhook testing.
+18. **Edge cases** — Expired subscription, failed payment retry, concurrent updates (etag), plan changes mid-billing.
---
@@ -621,6 +618,8 @@ The `?from=STRIPE` query param triggers the pending payment polling view (same p
| Payment providers | Stripe + Paddle | Stripe only |
| Grace period | +7 days (self-host), +12h (cloud) | None needed (instant activation) |
| Subscription owner | `org` entity | `workspace` directly |
+| Subscription table | Separate `id` PK, many top-level columns | `workspace` PK, everything in `payload` JSONB |
+| Etag | Stored column | Derived from `updated_at` |
---
@@ -629,6 +628,6 @@ The `?from=STRIPE` query param triggers the pending payment polling view (same p
1. **Stripe webhook signature verification** — Must validate `Stripe-Signature` header against `STRIPE_WEBHOOK_SECRET`. Reject unsigned requests.
2. **License private key** — Environment variable only, never embedded in binary. Only loaded in SaaS mode.
3. **SaaS gate** — All purchase APIs must check `profile.SaaS` before proceeding. Non-SaaS deployments must never expose Stripe integration.
-4. **Etag-based optimistic locking** — Prevents race conditions on subscription updates.
-5. **Metadata validation** — Webhook handler must verify `source=bytebase_hub` in metadata to filter out unrelated Stripe events.
+4. **Etag-based optimistic locking** — Prevents race conditions on subscription updates. Derived from `updated_at` timestamp.
+5. **Metadata validation** — Webhook handler must verify `source` in metadata to filter out unrelated Stripe events.
6. **HTTPS only** — Stripe webhooks require HTTPS endpoints.
diff --git a/go.mod b/go.mod
index f668b3b1bd..330be8ac56 100644
--- a/go.mod
+++ b/go.mod
@@ -85,6 +85,7 @@ require (
github.com/sourcegraph/jsonrpc2 v0.2.1
github.com/spf13/cobra v1.10.2
github.com/stretchr/testify v1.11.1
+ github.com/stripe/stripe-go/v82 v82.4.0
github.com/testcontainers/testcontainers-go v0.41.0
github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75
github.com/trinodb/trino-go-client v0.333.0
diff --git a/go.sum b/go.sum
index 1a01bb8d72..58fa13df19 100644
--- a/go.sum
+++ b/go.sum
@@ -993,6 +993,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/stripe/stripe-go/v82 v82.4.0 h1:N0R8qNJb37VaeMUYIy9q5n+oaUJYmIJ+GlqazMVQ9QI=
+github.com/stripe/stripe-go/v82 v82.4.0/go.mod h1:majCQX6AfObAvJiHraPi/5udwHi4ojRvJnnxckvHrX8=
github.com/testcontainers/testcontainers-go v0.41.0 h1:mfpsD0D36YgkxGj2LrIyxuwQ9i2wCKAD+ESsYM1wais=
github.com/testcontainers/testcontainers-go v0.41.0/go.mod h1:pdFrEIfaPl24zmBjerWTTYaY0M6UHsqA1YSvsoU40MI=
github.com/testcontainers/testcontainers-go/modules/mongodb v0.40.0 h1:z/1qHeliTLDKNaJ7uOHOx1FjwghbcbYfga4dTFkF0hU=