Skip to content

Commit

Permalink
feat: cancel subscription after trial (#843)
Browse files Browse the repository at this point in the history
* feat: set EndBehavior to cancel in trialing

* feat: add config to set trial sub end behaviour

* chore: update config as per pr review
  • Loading branch information
rsbh authored Jan 6, 2025
1 parent e065480 commit 1d22b1f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 2 additions & 0 deletions billing/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ type PlanChangeConfig struct {
}

type SubscriptionConfig struct {
// BehaviorAfterTrial as `cancel` will cancel the subscription after trial end and will not generate invoice.
BehaviorAfterTrial string `yaml:"behavior_after_trial" mapstructure:"behavior_after_trial" default:"release"`
}

type ProductConfig struct {
Expand Down
10 changes: 8 additions & 2 deletions billing/subscription/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,7 @@ func (s *Service) getPlanFromSchedule(ctx context.Context, stripeSchedule *strip

// CancelUpcomingPhase cancels the scheduled phase of the subscription
func (s *Service) CancelUpcomingPhase(ctx context.Context, sub Subscription) error {
_, stripeSchedule, err := s.createOrGetSchedule(ctx, sub)
stripeSub, stripeSchedule, err := s.createOrGetSchedule(ctx, sub)
if err != nil {
return err
}
Expand All @@ -988,6 +988,12 @@ func (s *Service) CancelUpcomingPhase(ctx context.Context, sub Subscription) err
var currency = string(stripeSchedule.Phases[0].Currency)
var prorationBehavior = s.config.PlanChangeConfig.ProrationBehavior

var endBehavior = stripe.SubscriptionScheduleEndBehaviorRelease

if stripeSub.Status == stripe.SubscriptionStatusTrialing && s.config.SubscriptionConfig.BehaviorAfterTrial == "cancel" {
endBehavior = stripe.SubscriptionScheduleEndBehaviorCancel
}

// update the phases
_, err = s.stripeClient.SubscriptionSchedules.Update(stripeSchedule.ID, &stripe.SubscriptionScheduleParams{
Params: stripe.Params{
Expand All @@ -1005,7 +1011,7 @@ func (s *Service) CancelUpcomingPhase(ctx context.Context, sub Subscription) err
},
},
},
EndBehavior: stripe.String("release"),
EndBehavior: stripe.String(string(endBehavior)),
ProrationBehavior: stripe.String(prorationBehavior),
DefaultSettings: &stripe.SubscriptionScheduleDefaultSettingsParams{
CollectionMethod: stripe.String(s.config.PlanChangeConfig.CollectionMethod),
Expand Down
2 changes: 2 additions & 0 deletions config/sample.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,5 @@ billing:
subscription: 1m
invoice: 5m
checkout: 1m
subscription:
cancel_after_trial: true

0 comments on commit 1d22b1f

Please sign in to comment.