-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathservice.go
More file actions
1074 lines (955 loc) · 34.8 KB
/
Copy pathservice.go
File metadata and controls
1074 lines (955 loc) · 34.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package checkout
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"time"
"github.com/robfig/cron/v3"
"github.com/stripe/stripe-go/v79"
"github.com/raystack/frontier/billing"
billingerrors "github.com/raystack/frontier/billing/errors"
"github.com/raystack/frontier/internal/metrics"
"github.com/raystack/frontier/pkg/metadata"
"github.com/raystack/frontier/pkg/utils"
"github.com/spf13/cast"
"github.com/raystack/frontier/core/authenticate"
"github.com/raystack/frontier/billing/credit"
"github.com/google/uuid"
"github.com/raystack/frontier/billing/subscription"
"github.com/raystack/frontier/billing/plan"
"github.com/raystack/frontier/billing/product"
"github.com/raystack/frontier/billing/customer"
"github.com/stripe/stripe-go/v79/client"
)
const (
SessionValidity = time.Hour * 24
MinimumProductQuantity = 1
MaximumProductQuantity = 100000 // max: 999999
// ProductQuantityMetadataKey is the metadata key for the quantity of the product
// it's necessary to cast as this properly because while storing metadata, it's serialized as json
// and when retrieved, it's always an interface{} of float64 type
ProductQuantityMetadataKey = "product_quantity"
// AmountTotalMetadataKey is the metadata key for the total amount of the checkout
// same goes for this as well, it's always an interface{} of float64 type
AmountTotalMetadataKey = "amount_total"
// ProcessedMetadataKey is the metadata key to indicate that the checkout has been processed
// in the system
ProcessedMetadataKey = "processed"
CurrencyMetadataKey = "currency"
ProviderIDSubscriptionMetadataKey = "provider_subscription_id"
InitiatorIDMetadataKey = "initiated_by"
CheckoutIDMetadataKey = "checkout_id"
)
type Repository interface {
GetByID(ctx context.Context, id string) (Checkout, error)
Create(ctx context.Context, ch Checkout) (Checkout, error)
UpdateByID(ctx context.Context, ch Checkout) (Checkout, error)
List(ctx context.Context, filter Filter) ([]Checkout, error)
DeleteByCustomerID(ctx context.Context, customerID string) error
}
type CustomerService interface {
GetByID(ctx context.Context, id string) (customer.Customer, error)
List(ctx context.Context, filter customer.Filter) ([]customer.Customer, error)
RegisterToProviderIfRequired(ctx context.Context, customerID string) (customer.Customer, error)
}
type PlanService interface {
List(ctx context.Context, filter plan.Filter) ([]plan.Plan, error)
GetByID(ctx context.Context, id string) (plan.Plan, error)
}
type SubscriptionService interface {
List(ctx context.Context, filter subscription.Filter) ([]subscription.Subscription, error)
Create(ctx context.Context, sub subscription.Subscription) (subscription.Subscription, error)
GetByProviderID(ctx context.Context, id string) (subscription.Subscription, error)
Cancel(ctx context.Context, id string, immediate bool) (subscription.Subscription, error)
HasUserSubscribedBefore(ctx context.Context, customerID string, planID string) (bool, error)
}
type ProductService interface {
GetByID(ctx context.Context, id string) (product.Product, error)
}
type CreditService interface {
Add(ctx context.Context, cred credit.Credit) error
}
type OrganizationService interface {
MemberCount(ctx context.Context, orgID string) (int64, error)
}
type AuthnService interface {
GetPrincipal(ctx context.Context, assertions ...authenticate.ClientAssertion) (authenticate.Principal, error)
}
type Service struct {
log *slog.Logger
stripeAutoTax bool
stripeClient *client.API
repository Repository
customerService CustomerService
planService PlanService
subscriptionService SubscriptionService
creditService CreditService
productService ProductService
orgService OrganizationService
authnService AuthnService
defaultCurrency string
paymentMethodConfig []billing.PaymentMethodConfig
syncJob *cron.Cron
syncJobMu sync.Mutex
mu sync.Mutex
syncDelay time.Duration
}
func NewService(logger *slog.Logger, stripeClient *client.API, cfg billing.Config, repository Repository,
customerService CustomerService, planService PlanService,
subscriptionService SubscriptionService, productService ProductService,
creditService CreditService, orgService OrganizationService,
authnService AuthnService) *Service {
s := &Service{
log: logger,
stripeClient: stripeClient,
stripeAutoTax: cfg.StripeAutoTax,
repository: repository,
customerService: customerService,
planService: planService,
subscriptionService: subscriptionService,
creditService: creditService,
productService: productService,
orgService: orgService,
authnService: authnService,
syncDelay: cfg.RefreshInterval.Checkout,
defaultCurrency: cfg.DefaultCurrency,
paymentMethodConfig: cfg.PaymentMethodConfig,
}
return s
}
func (s *Service) Init(ctx context.Context) error {
if s.syncDelay == time.Duration(0) {
return nil
}
s.syncJobMu.Lock()
defer s.syncJobMu.Unlock()
if s.syncJob != nil {
<-s.syncJob.Stop().Done()
}
s.syncJob = cron.New(cron.WithChain(
cron.SkipIfStillRunning(cron.DefaultLogger),
cron.Recover(cron.DefaultLogger),
))
_, err := s.syncJob.AddFunc(fmt.Sprintf("@every %s", s.syncDelay.String()), func() {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
s.backgroundSync(ctx)
})
if err != nil {
return err
}
s.syncJob.Start()
return nil
}
func (s *Service) Close() error {
s.syncJobMu.Lock()
defer s.syncJobMu.Unlock()
if s.syncJob != nil {
<-s.syncJob.Stop().Done()
}
return nil
}
func (s *Service) backgroundSync(ctx context.Context) {
start := time.Now()
if metrics.BillingSyncLatency != nil {
record := metrics.BillingSyncLatency("checkout")
defer record()
}
customers, err := s.customerService.List(ctx, customer.Filter{
State: customer.ActiveState,
})
if err != nil {
s.log.ErrorContext(ctx, "checkout.backgroundSync", "error", err)
return
}
for _, customer := range customers {
if ctx.Err() != nil {
// stop processing if context is done
break
}
if !customer.IsActive() || customer.IsOffline() {
continue
}
if err := s.SyncWithProvider(ctx, customer.ID); err != nil {
s.log.ErrorContext(ctx, "checkout.SyncWithProvider", "error", err, "customer_id", customer.ID)
}
}
s.log.InfoContext(ctx, "checkout.backgroundSync finished", "duration", time.Since(start))
}
func (s *Service) Create(ctx context.Context, ch Checkout) (Checkout, error) {
// need to make it register itself to provider first if needed
billingCustomer, err := s.customerService.RegisterToProviderIfRequired(ctx, ch.CustomerID)
if err != nil {
return Checkout{}, err
}
checkoutID := uuid.New().String()
ch = s.templatizeUrls(ch, checkoutID)
currentPrincipal, err := s.authnService.GetPrincipal(ctx)
if err != nil {
return Checkout{}, err
}
// Determine address collection setting based on whether customer already has minimum required address
addressCollectionParam := string(stripe.CheckoutSessionBillingAddressCollectionAuto)
if billingCustomer.HasMinimumRequiredAddress() {
addressCollectionParam = "never"
}
// checkout could be for a plan or a product
if ch.PlanID != "" {
plan, err := s.planService.GetByID(ctx, ch.PlanID)
if err != nil {
return Checkout{}, err
}
// ensure we use uuid
ch.PlanID = plan.ID
// if already subscribed to the plan, return
if subID, err := s.checkIfAlreadySubscribed(ctx, ch); err != nil {
return Checkout{}, err
} else if subID != "" {
return Checkout{}, fmt.Errorf("already subscribed to the plan")
}
// create subscription items
var subsItems []*stripe.CheckoutSessionLineItemParams
userCount, err := s.orgService.MemberCount(ctx, billingCustomer.OrgID)
if err != nil {
return Checkout{}, fmt.Errorf("failed to get member count: %w", err)
}
hasBillableProduct := false
for _, planProduct := range plan.Products {
// if it's credit, skip
if planProduct.Behavior == product.CreditBehavior {
continue
}
hasBillableProduct = true
// if per seat, check if there is a limit of seats, if it breaches limit, fail
if planProduct.IsSeatLimitBreached(userCount) {
return Checkout{}, fmt.Errorf("member count exceeds allowed limit of the plan: %w", product.ErrPerSeatLimitReached)
}
for _, productPrice := range planProduct.Prices {
// skip inactive prices; they cannot be used for a new checkout
if !productPrice.IsActive() {
continue
}
// only work with plan interval prices
if productPrice.Interval != plan.Interval {
continue
}
var quantity int64 = 1
if productPrice.IsLicensed() && planProduct.HasPerSeatBehavior() {
quantity = userCount
}
itemParams := &stripe.CheckoutSessionLineItemParams{
Price: new(productPrice.ProviderID),
Quantity: new(quantity),
}
subsItems = append(subsItems, itemParams)
}
}
if hasBillableProduct && len(subsItems) == 0 {
return Checkout{}, fmt.Errorf("plan %s has no active prices for interval %s", plan.Name, plan.Interval)
}
var trialDays *int64 = nil
// if trial is enabled and user has not trialed before, set trial days
userHasTrialedBefore, err := s.subscriptionService.HasUserSubscribedBefore(ctx, billingCustomer.ID, plan.ID)
if err != nil {
return Checkout{}, err
}
if plan.TrialDays > 0 && !ch.SkipTrial && !userHasTrialedBefore {
trialDays = new(plan.TrialDays)
}
// create subscription checkout link
stripeCheckout, err := s.stripeClient.CheckoutSessions.New(&stripe.CheckoutSessionParams{
Params: stripe.Params{
Context: ctx,
},
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
Enabled: new(s.stripeAutoTax),
},
Currency: new(billingCustomer.Currency),
Customer: new(billingCustomer.ProviderID),
LineItems: subsItems,
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
"plan_id": ch.PlanID,
CheckoutIDMetadataKey: checkoutID,
InitiatorIDMetadataKey: currentPrincipal.ID,
"managed_by": "frontier",
},
CustomerUpdate: &stripe.CheckoutSessionCustomerUpdateParams{
Address: new(addressCollectionParam),
},
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{
Description: new(fmt.Sprintf("Checkout for %s", plan.Name)),
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
CheckoutIDMetadataKey: checkoutID,
subscription.InitiatorIDMetadataKey: currentPrincipal.ID,
"managed_by": "frontier",
},
TrialPeriodDays: trialDays,
TrialSettings: &stripe.CheckoutSessionSubscriptionDataTrialSettingsParams{
EndBehavior: &stripe.CheckoutSessionSubscriptionDataTrialSettingsEndBehaviorParams{
MissingPaymentMethod: stripe.String(string(stripe.SubscriptionScheduleEndBehaviorCancel)),
},
},
},
AllowPromotionCodes: new(true),
CancelURL: new(ch.CancelUrl),
SuccessURL: new(ch.SuccessUrl),
ExpiresAt: new(time.Now().Add(SessionValidity).Unix()),
PaymentMethodCollection: stripe.String(string(stripe.PaymentLinkPaymentMethodCollectionIfRequired)),
})
if err != nil {
return Checkout{}, fmt.Errorf("failed to create subscription at billing provider: %w", billingerrors.TranslateStripeError(err))
}
return s.repository.Create(ctx, Checkout{
ID: checkoutID,
ProviderID: stripeCheckout.ID,
CustomerID: billingCustomer.ID,
PlanID: plan.ID,
SkipTrial: ch.SkipTrial,
CancelAfterTrial: ch.CancelAfterTrial,
CancelUrl: ch.CancelUrl,
SuccessUrl: ch.SuccessUrl,
CheckoutUrl: stripeCheckout.URL,
State: string(stripeCheckout.Status),
PaymentStatus: string(stripeCheckout.PaymentStatus),
Metadata: map[string]any{
"plan_name": plan.Name,
InitiatorIDMetadataKey: currentPrincipal.ID,
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
})
}
if ch.ProductID != "" {
chProduct, err := s.productService.GetByID(ctx, ch.ProductID)
if err != nil {
return Checkout{}, fmt.Errorf("failed to get product: %w", err)
}
if len(chProduct.Prices) == 0 {
return Checkout{}, fmt.Errorf("invalid product, no prices found")
}
var subsItems []*stripe.CheckoutSessionLineItemParams
var minQ int64 = MinimumProductQuantity
var maxQ int64 = MaximumProductQuantity
var adjustableQuantity = true
if chProduct.Config.MinQuantity > 0 {
minQ = chProduct.Config.MinQuantity
}
if chProduct.Config.MaxQuantity > 0 {
maxQ = chProduct.Config.MaxQuantity
}
if maxQ == 1 {
adjustableQuantity = false
}
var defaultQ int64 = 1
if ch.Quantity > 0 && ch.Quantity <= maxQ && ch.Quantity >= minQ {
defaultQ = ch.Quantity
adjustableQuantity = false
}
amountSubtotal := int64(0)
for _, productPrice := range chProduct.Prices {
// skip inactive prices; they cannot be used for a new checkout
if !productPrice.IsActive() {
continue
}
itemParams := &stripe.CheckoutSessionLineItemParams{
Price: new(productPrice.ProviderID),
AdjustableQuantity: &stripe.CheckoutSessionLineItemAdjustableQuantityParams{
Enabled: new(adjustableQuantity),
},
}
if adjustableQuantity {
itemParams.AdjustableQuantity.Minimum = new(minQ)
itemParams.AdjustableQuantity.Maximum = new(maxQ)
}
if productPrice.UsageType == product.PriceUsageTypeLicensed {
itemParams.Quantity = new(defaultQ)
}
if productPrice.Currency == s.defaultCurrency {
amountSubtotal += productPrice.Amount * defaultQ
}
subsItems = append(subsItems, itemParams)
}
if len(subsItems) == 0 {
return Checkout{}, fmt.Errorf("product %s has no active prices", chProduct.Name)
}
// plan payment methods on the basis of amount subtotal
var paymentMethodTypes []*string
for _, paymentMethodConfig := range s.paymentMethodConfig {
if paymentMethodConfig.IsAllowedForAmount(amountSubtotal) {
paymentMethodTypes = append(paymentMethodTypes, new(paymentMethodConfig.Type))
}
}
// create one time checkout link
stripeCheckout, err := s.stripeClient.CheckoutSessions.New(&stripe.CheckoutSessionParams{
Params: stripe.Params{
Context: ctx,
},
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
Enabled: new(s.stripeAutoTax),
},
Currency: new(s.defaultCurrency),
Customer: new(billingCustomer.ProviderID),
InvoiceCreation: &stripe.CheckoutSessionInvoiceCreationParams{
Enabled: new(true),
},
LineItems: subsItems,
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
"product_name": chProduct.Name,
"credit_amount": fmt.Sprintf("%d", chProduct.Config.CreditAmount),
CheckoutIDMetadataKey: checkoutID,
InitiatorIDMetadataKey: currentPrincipal.ID,
"managed_by": "frontier",
},
CustomerUpdate: &stripe.CheckoutSessionCustomerUpdateParams{
Address: new(addressCollectionParam),
},
AllowPromotionCodes: new(true),
CancelURL: new(ch.CancelUrl),
SuccessURL: new(ch.SuccessUrl),
ExpiresAt: new(time.Now().Add(SessionValidity).Unix()),
PaymentMethodTypes: paymentMethodTypes,
PaymentMethodOptions: &stripe.CheckoutSessionPaymentMethodOptionsParams{
CustomerBalance: &stripe.CheckoutSessionPaymentMethodOptionsCustomerBalanceParams{
FundingType: stripe.String(string(stripe.CheckoutSessionPaymentMethodOptionsCustomerBalanceFundingTypeBankTransfer)),
BankTransfer: &stripe.CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferParams{
Type: stripe.String(string(stripe.CheckoutSessionPaymentMethodOptionsCustomerBalanceBankTransferTypeUSBankTransfer)),
},
},
},
})
if err != nil {
return Checkout{}, fmt.Errorf("failed to buy product at billing provider: %w", billingerrors.TranslateStripeError(err))
}
return s.repository.Create(ctx, Checkout{
ID: checkoutID,
ProviderID: stripeCheckout.ID,
CustomerID: billingCustomer.ID,
ProductID: chProduct.ID,
CancelUrl: ch.CancelUrl,
SuccessUrl: ch.SuccessUrl,
CheckoutUrl: stripeCheckout.URL,
State: string(stripeCheckout.Status),
PaymentStatus: string(stripeCheckout.PaymentStatus),
Metadata: map[string]any{
"product_name": chProduct.Name,
InitiatorIDMetadataKey: currentPrincipal.ID,
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
})
}
return Checkout{}, fmt.Errorf("invalid checkout request")
}
// templatizeUrls replaces the checkout id placeholder in the urls with the actual checkout id
func (s *Service) templatizeUrls(ch Checkout, checkoutID string) Checkout {
ch.SuccessUrl = strings.ReplaceAll(ch.SuccessUrl, "{{.CheckoutID}}", checkoutID)
ch.CancelUrl = strings.ReplaceAll(ch.CancelUrl, "{{.CheckoutID}}", checkoutID)
return ch
}
func (s *Service) GetByID(ctx context.Context, id string) (Checkout, error) {
return s.repository.GetByID(ctx, id)
}
// SyncWithProvider syncs the subscription state with the billing provider
func (s *Service) SyncWithProvider(ctx context.Context, customerID string) error {
s.mu.Lock()
defer s.mu.Unlock()
checks, err := s.repository.List(ctx, Filter{
CustomerID: customerID,
})
if err != nil {
return err
}
var errs []error
// find all checkout sessions of the customer that require a sync
// and update their state in system
for idx, ch := range checks {
if ctx.Err() != nil {
// stop processing if context is done
break
}
if ch.State == StateExpired.String() || (ch.State == StateComplete.String() && ch.PaymentStatus != "unpaid") {
continue
}
if ch.ExpireAt.Before(time.Now()) {
ch.State = StateExpired.String()
if _, err := s.repository.UpdateByID(ctx, ch); err != nil {
return err
}
continue
}
checkoutSession, err := s.stripeClient.CheckoutSessions.Get(ch.ProviderID, &stripe.CheckoutSessionParams{
Params: stripe.Params{
Context: ctx,
},
Expand: []*string{
new("line_items.data.price.product"),
},
})
if err != nil {
errs = append(errs, fmt.Errorf("failed to get checkout session from billing provider: %w", billingerrors.TranslateStripeError(err)))
continue
}
if ch.PaymentStatus != string(checkoutSession.PaymentStatus) {
ch.PaymentStatus = string(checkoutSession.PaymentStatus)
}
if ch.State != string(checkoutSession.Status) {
ch.State = string(checkoutSession.Status)
}
if checkoutSession.Subscription != nil {
ch.Metadata[ProviderIDSubscriptionMetadataKey] = checkoutSession.Subscription.ID
}
ch.Metadata[AmountTotalMetadataKey] = checkoutSession.AmountTotal
ch.Metadata[CurrencyMetadataKey] = checkoutSession.Currency
if checkoutSession.LineItems != nil {
for _, lintitem := range checkoutSession.LineItems.Data {
if lintitem.Price != nil && lintitem.Price.Product != nil &&
lintitem.Price.Product.ID == ch.ProductID {
ch.Metadata[ProductQuantityMetadataKey] = lintitem.Quantity
}
}
}
if checks[idx], err = s.repository.UpdateByID(ctx, ch); err != nil {
return fmt.Errorf("failed to update checkout session: %w", err)
}
}
// if payment is completed, create subscription for them in system
for _, ch := range checks {
if processed, ok := ch.Metadata[ProcessedMetadataKey].(bool); ok && processed {
continue
}
if ch.State == StateComplete.String() &&
(ch.PaymentStatus == "paid" || ch.PaymentStatus == "no_payment_required") {
// checkout could be for a plan or a product
if ch.PlanID != "" {
// if the checkout was created for subscription
if _, err := s.ensureSubscription(ctx, ch); err != nil {
errs = append(errs, fmt.Errorf("ensureSubscription: %w", err))
continue
}
} else if ch.ProductID != "" {
// if the checkout was created for product
if err := s.ensureCreditsForProduct(ctx, ch); err != nil {
errs = append(errs, fmt.Errorf("ensureCreditsForProduct: %w", err))
continue
}
}
ch.Metadata[ProcessedMetadataKey] = true
if _, err := s.repository.UpdateByID(ctx, ch); err != nil {
errs = append(errs, fmt.Errorf("failed to update checkout session: %w", err))
}
}
}
return errors.Join(errs...)
}
func (s *Service) ensureCreditsForProduct(ctx context.Context, ch Checkout) error {
chProduct, err := s.productService.GetByID(ctx, ch.ProductID)
if err != nil {
return err
}
if chProduct.Behavior != product.CreditBehavior {
return fmt.Errorf("invalid product, not a credit product")
}
creditAmount := chProduct.Config.CreditAmount
if quantity, ok := ch.Metadata[ProductQuantityMetadataKey]; ok {
creditAmount = cast.ToInt64(quantity) * chProduct.Config.CreditAmount
}
description := fmt.Sprintf("addition of %d credits for %s", creditAmount, chProduct.Title)
if price, pok := ch.Metadata[AmountTotalMetadataKey]; pok {
if currency, cok := ch.Metadata[CurrencyMetadataKey].(string); cok {
description = fmt.Sprintf("addition of %d credits for %s at %d[%s]", creditAmount, chProduct.Title, price, currency)
}
}
initiatorID := ""
if id, ok := ch.Metadata[InitiatorIDMetadataKey].(string); ok {
initiatorID = id
}
md := metadata.Build(ch.Metadata)
md[CheckoutIDMetadataKey] = ch.ID
if err := s.creditService.Add(ctx, credit.Credit{
ID: ch.ID,
CustomerID: ch.CustomerID,
Amount: creditAmount,
Metadata: md,
Description: description,
Source: credit.SourceSystemBuyEvent,
UserID: initiatorID,
}); err != nil && !errors.Is(err, credit.ErrAlreadyApplied) {
return err
}
return nil
}
func (s *Service) checkIfAlreadySubscribed(ctx context.Context, ch Checkout) (string, error) {
// check if subscription exists
subs, err := s.subscriptionService.List(ctx, subscription.Filter{
CustomerID: ch.CustomerID,
PlanID: ch.PlanID,
})
if err != nil {
return "", err
}
for _, sub := range subs {
// don't care about canceled or ended subscriptions
// trialing subscriptions will be canceled later
if sub.State == subscription.StateCanceled.String() ||
sub.State == subscription.StateEnded.String() ||
sub.State == subscription.StateTrialing.String() {
continue
}
// subscription already exists
return sub.ID, nil
}
return "", nil
}
func (s *Service) cancelTrialingSubscription(ctx context.Context, customerID string, planID string) error {
// check if subscription exists
subs, err := s.subscriptionService.List(ctx, subscription.Filter{
CustomerID: customerID,
PlanID: planID,
})
if err != nil {
return err
}
for _, sub := range subs {
// cancel immediately if trialing
if sub.State == subscription.StateTrialing.String() && !sub.TrialEndsAt.IsZero() {
if _, err := s.subscriptionService.Cancel(ctx, sub.ID, true); err != nil {
return fmt.Errorf("failed to cancel trialing subscription: %w", err)
}
}
}
return nil
}
func (s *Service) ensureSubscription(ctx context.Context, ch Checkout) (string, error) {
if ch.Metadata[ProviderIDSubscriptionMetadataKey] == nil {
return "", fmt.Errorf("invalid checkout session, provider_subscription_id is missing")
}
subProviderID := ch.Metadata[ProviderIDSubscriptionMetadataKey].(string)
// check if already created in frontier
_, err := s.subscriptionService.GetByProviderID(ctx, subProviderID)
if err != nil && !errors.Is(err, subscription.ErrNotFound) {
return "", err
}
if err == nil {
// already created
return "", nil
}
// cancel existing trials if any
if err := s.cancelTrialingSubscription(ctx, ch.CustomerID, ch.PlanID); err != nil {
return "", err
}
stripeSubscription, err := s.stripeClient.Subscriptions.Get(subProviderID,
&stripe.SubscriptionParams{
Params: stripe.Params{
Context: ctx,
},
})
if err != nil {
return "", fmt.Errorf("failed to get subscription from billing provider: %w", billingerrors.TranslateStripeError(err))
}
// create subscription
md := metadata.Build(ch.Metadata)
md[CheckoutIDMetadataKey] = ch.ID
md[subscription.ProviderTestResource] = !stripeSubscription.Livemode
sub, err := s.subscriptionService.Create(ctx, subscription.Subscription{
ID: uuid.New().String(),
ProviderID: subProviderID,
CustomerID: ch.CustomerID,
PlanID: ch.PlanID,
State: string(stripeSubscription.Status),
Metadata: md,
TrialEndsAt: utils.AsTimeFromEpoch(stripeSubscription.TrialEnd),
})
if err != nil {
return "", err
}
// if set to cancel after trial, schedule a phase to cancel the subscription
if ch.CancelAfterTrial && stripeSubscription.TrialEnd > 0 {
_, err := s.subscriptionService.Cancel(ctx, sub.ID, false)
if err != nil {
return "", fmt.Errorf("failed to schedule cancel of subscription after trial: %w", err)
}
}
return sub.ID, nil
}
func (s *Service) List(ctx context.Context, filter Filter) ([]Checkout, error) {
return s.repository.List(ctx, filter)
}
// DeleteByCustomer removes all checkout records of a billing account. Checkout
// sessions on the billing provider are not touched as they expire on their own.
func (s *Service) DeleteByCustomer(ctx context.Context, customerID string) error {
return s.repository.DeleteByCustomerID(ctx, customerID)
}
func (s *Service) CreateSessionForPaymentMethod(ctx context.Context, ch Checkout) (Checkout, error) {
billingCustomer, err := s.customerService.RegisterToProviderIfRequired(ctx, ch.CustomerID)
if err != nil {
return Checkout{}, err
}
checkoutID := uuid.New().String()
ch = s.templatizeUrls(ch, checkoutID)
// create payment method setup checkout link
stripeCheckout, err := s.stripeClient.CheckoutSessions.New(&stripe.CheckoutSessionParams{
Params: stripe.Params{
Context: ctx,
},
Customer: new(billingCustomer.ProviderID),
Currency: new(billingCustomer.Currency),
Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),
CancelURL: new(ch.CancelUrl),
SuccessURL: new(ch.SuccessUrl),
ExpiresAt: new(time.Now().Add(SessionValidity).Unix()),
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
"checkout_id": checkoutID,
"managed_by": "frontier",
},
})
if err != nil {
return Checkout{}, fmt.Errorf("failed to create checkout at billing provider: %w", billingerrors.TranslateStripeError(err))
}
return s.repository.Create(ctx, Checkout{
ID: checkoutID,
ProviderID: stripeCheckout.ID,
CustomerID: billingCustomer.ID,
CancelUrl: ch.CancelUrl,
SuccessUrl: ch.SuccessUrl,
CheckoutUrl: stripeCheckout.URL,
State: string(stripeCheckout.Status),
ExpireAt: utils.AsTimeFromEpoch(stripeCheckout.ExpiresAt),
Metadata: map[string]any{
"mode": "setup",
"org_id": billingCustomer.OrgID,
"customer_name": billingCustomer.Name,
},
})
}
func (s *Service) CreateSessionForCustomerPortal(ctx context.Context, ch Checkout) (Checkout, error) {
billingCustomer, err := s.customerService.RegisterToProviderIfRequired(ctx, ch.CustomerID)
if err != nil {
return Checkout{}, err
}
checkoutID := uuid.New().String()
sessionParams := &stripe.BillingPortalSessionParams{
Params: stripe.Params{
Context: ctx,
},
Customer: new(billingCustomer.ProviderID),
}
if ch.CancelUrl != "" {
sessionParams.ReturnURL = new(ch.CancelUrl)
}
session, err := s.stripeClient.BillingPortalSessions.New(sessionParams)
if err != nil {
return Checkout{}, fmt.Errorf("failed to create session for customer portal: %w", billingerrors.TranslateStripeError(err))
}
return Checkout{
ID: checkoutID,
ProviderID: session.ID,
CustomerID: billingCustomer.ID,
CancelUrl: ch.CancelUrl,
SuccessUrl: ch.SuccessUrl,
CheckoutUrl: session.URL,
Metadata: map[string]any{
"mode": "customer_portal",
},
}, nil
}
// Apply applies the actual request directly without creating a checkout session
// for example when a request is created for a plan, it will directly subscribe without
// actually paying for it
func (s *Service) Apply(ctx context.Context, ch Checkout) (*subscription.Subscription, *product.Product, error) {
ch.ID = uuid.New().String()
// get billing
billingCustomer, err := s.customerService.GetByID(ctx, ch.CustomerID)
if err != nil {
return nil, nil, err
}
currentPrincipal, err := s.authnService.GetPrincipal(ctx)
if err != nil {
return nil, nil, err
}
autoTaxParams := &stripe.SubscriptionAutomaticTaxParams{
Enabled: new(s.stripeAutoTax),
}
// checkout could be for a plan or a product
if ch.PlanID != "" && !billingCustomer.IsOffline() {
plan, err := s.planService.GetByID(ctx, ch.PlanID)
if err != nil {
return nil, nil, err
}
// ensure we use uuid
ch.PlanID = plan.ID
// if already subscribed to the plan, return
if subID, err := s.checkIfAlreadySubscribed(ctx, ch); err != nil {
return nil, nil, err
} else if subID != "" {
return nil, nil, fmt.Errorf("already subscribed to the plan")
}
if err := s.cancelTrialingSubscription(ctx, ch.CustomerID, ch.PlanID); err != nil {
return nil, nil, err
}
// create subscription items
var subsItems []*stripe.SubscriptionItemsParams
userCount, err := s.orgService.MemberCount(ctx, billingCustomer.OrgID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get member count: %w", err)
}
var totalExpectedPrice int64
hasBillableProduct := false
for _, planProduct := range plan.Products {
// if it's credit, skip, they are handled separately
if planProduct.Behavior == product.CreditBehavior {
continue
}
hasBillableProduct = true
// if per seat, check if there is a limit of seats, if it breaches limit, fail
if planProduct.IsSeatLimitBreached(userCount) {
return nil, nil, fmt.Errorf("member count exceeds allowed limit of the plan: %w", product.ErrPerSeatLimitReached)
}
for _, productPrice := range planProduct.Prices {
// skip inactive prices; they cannot be used for a new subscription
if !productPrice.IsActive() {
continue
}
// only work with plan interval prices
if productPrice.Interval != plan.Interval {
continue
}
var quantity int64 = 1
if productPrice.IsLicensed() && planProduct.HasPerSeatBehavior() {
quantity = userCount
}
itemParams := &stripe.SubscriptionItemsParams{
Price: new(productPrice.ProviderID),
Quantity: new(quantity),
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
"product_id": planProduct.ID,
},
}
subsItems = append(subsItems, itemParams)
totalExpectedPrice += productPrice.Amount * quantity
}
}
if hasBillableProduct && len(subsItems) == 0 {
return nil, nil, fmt.Errorf("plan %s has no active prices for interval %s", plan.Name, plan.Interval)
}
var trialDays *int64 = nil
if plan.TrialDays > 0 && !ch.SkipTrial {
trialDays = new(plan.TrialDays)
}
if totalExpectedPrice == 0 {
// if total price is 0, disable auto tax. This ensures that when the subscription is created without
// user billing details while onboarding, creating 0 amount invoice doesn't fail
// This will be toggled back on when the user changes it's plan to a paid one
autoTaxParams.Enabled = new(false)
}
var couponID *string
if ch.ProviderCouponID != "" {
couponID = new(ch.ProviderCouponID)
}
// create subscription directly
stripeSubscription, err := s.stripeClient.Subscriptions.New(&stripe.SubscriptionParams{
Params: stripe.Params{
Context: ctx,
},
AutomaticTax: autoTaxParams,
Customer: new(billingCustomer.ProviderID),
Currency: new(billingCustomer.Currency),
Items: subsItems,
Metadata: map[string]string{
"org_id": billingCustomer.OrgID,
"managed_by": "frontier",
},
TrialPeriodDays: trialDays,
TrialSettings: &stripe.SubscriptionTrialSettingsParams{
EndBehavior: &stripe.SubscriptionTrialSettingsEndBehaviorParams{
MissingPaymentMethod: stripe.String(string(stripe.SubscriptionScheduleEndBehaviorCancel)),
},
},
Coupon: couponID,
})
if err != nil {
return nil, nil, fmt.Errorf("failed to create subscription at billing provider: %w", billingerrors.TranslateStripeError(err))
}
// register subscription in frontier
subs, err := s.subscriptionService.Create(ctx, subscription.Subscription{
ID: uuid.New().String(),
ProviderID: stripeSubscription.ID,
CustomerID: billingCustomer.ID,