-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsubscription.go
More file actions
2007 lines (1804 loc) · 91.6 KB
/
Copy pathsubscription.go
File metadata and controls
2007 lines (1804 loc) · 91.6 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
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package dodopayments
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
"slices"
"time"
"github.com/dodopayments/dodopayments-go/internal/apijson"
"github.com/dodopayments/dodopayments-go/internal/apiquery"
"github.com/dodopayments/dodopayments-go/internal/param"
"github.com/dodopayments/dodopayments-go/internal/requestconfig"
"github.com/dodopayments/dodopayments-go/option"
"github.com/dodopayments/dodopayments-go/packages/pagination"
"github.com/tidwall/gjson"
)
// SubscriptionService contains methods and other services that help with
// interacting with the Dodo Payments API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewSubscriptionService] method instead.
type SubscriptionService struct {
Options []option.RequestOption
}
// NewSubscriptionService generates a new service that applies the given options to
// each request. These options are applied after the parent client's options (if
// there is one), and before any request-specific options.
func NewSubscriptionService(opts ...option.RequestOption) (r *SubscriptionService) {
r = &SubscriptionService{}
r.Options = opts
return
}
// Deprecated: deprecated
func (r *SubscriptionService) New(ctx context.Context, body SubscriptionNewParams, opts ...option.RequestOption) (res *SubscriptionNewResponse, err error) {
opts = slices.Concat(r.Options, opts)
path := "subscriptions"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
func (r *SubscriptionService) Get(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (res *Subscription, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
func (r *SubscriptionService) Update(ctx context.Context, subscriptionID string, body SubscriptionUpdateParams, opts ...option.RequestOption) (res *Subscription, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return res, err
}
func (r *SubscriptionService) List(ctx context.Context, query SubscriptionListParams, opts ...option.RequestOption) (res *pagination.DefaultPageNumberPagination[SubscriptionListResponse], err error) {
var raw *http.Response
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
path := "subscriptions"
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
func (r *SubscriptionService) ListAutoPaging(ctx context.Context, query SubscriptionListParams, opts ...option.RequestOption) *pagination.DefaultPageNumberPaginationAutoPager[SubscriptionListResponse] {
return pagination.NewDefaultPageNumberPaginationAutoPager(r.List(ctx, query, opts...))
}
func (r *SubscriptionService) CancelChangePlan(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return err
}
path := fmt.Sprintf("subscriptions/%s/change-plan/scheduled", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...)
return err
}
func (r *SubscriptionService) ChangePlan(ctx context.Context, subscriptionID string, body SubscriptionChangePlanParams, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return err
}
path := fmt.Sprintf("subscriptions/%s/change-plan", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, nil, opts...)
return err
}
func (r *SubscriptionService) Charge(ctx context.Context, subscriptionID string, body SubscriptionChargeParams, opts ...option.RequestOption) (res *SubscriptionChargeResponse, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s/charge", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
func (r *SubscriptionService) PreviewChangePlan(ctx context.Context, subscriptionID string, body SubscriptionPreviewChangePlanParams, opts ...option.RequestOption) (res *SubscriptionPreviewChangePlanResponse, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s/change-plan/preview", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
func (r *SubscriptionService) GetCreditUsage(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (res *SubscriptionGetCreditUsageResponse, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s/credit-usage", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Get detailed usage history for a subscription that includes usage-based billing
// (metered components). This endpoint provides insights into customer usage
// patterns and billing calculations over time.
//
// ## What You'll Get:
//
// - **Billing periods**: Each item represents a billing cycle with start and end
// dates
// - **Meter usage**: Detailed breakdown of usage for each meter configured on the
// subscription
// - **Usage calculations**: Total units consumed, free threshold units, and
// chargeable units
// - **Historical tracking**: Complete audit trail of usage-based charges
//
// ## Use Cases:
//
// - **Customer support**: Investigate billing questions and usage discrepancies
// - **Usage analytics**: Analyze customer consumption patterns over time
// - **Billing transparency**: Provide customers with detailed usage breakdowns
// - **Revenue optimization**: Identify usage trends to optimize pricing strategies
//
// ## Filtering Options:
//
// - **Date range filtering**: Get usage history for specific time periods
// - **Meter-specific filtering**: Focus on usage for a particular meter
// - **Pagination**: Navigate through large usage histories efficiently
//
// ## Important Notes:
//
// - Only returns data for subscriptions with usage-based (metered) components
// - Usage history is organized by billing periods (subscription cycles)
// - Free threshold units are calculated and displayed separately from chargeable
// units
// - Historical data is preserved even if meter configurations change
//
// ## Example Query Patterns:
//
// - Get last 3 months:
// `?start_date=2024-01-01T00:00:00Z&end_date=2024-03-31T23:59:59Z`
// - Filter by meter: `?meter_id=mtr_api_requests`
// - Paginate results: `?page_size=20&page_number=1`
// - Recent usage: `?start_date=2024-03-01T00:00:00Z` (from March 1st to now)
func (r *SubscriptionService) GetUsageHistory(ctx context.Context, subscriptionID string, query SubscriptionGetUsageHistoryParams, opts ...option.RequestOption) (res *pagination.DefaultPageNumberPagination[SubscriptionGetUsageHistoryResponse], err error) {
var raw *http.Response
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s/usage-history", subscriptionID)
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
// Get detailed usage history for a subscription that includes usage-based billing
// (metered components). This endpoint provides insights into customer usage
// patterns and billing calculations over time.
//
// ## What You'll Get:
//
// - **Billing periods**: Each item represents a billing cycle with start and end
// dates
// - **Meter usage**: Detailed breakdown of usage for each meter configured on the
// subscription
// - **Usage calculations**: Total units consumed, free threshold units, and
// chargeable units
// - **Historical tracking**: Complete audit trail of usage-based charges
//
// ## Use Cases:
//
// - **Customer support**: Investigate billing questions and usage discrepancies
// - **Usage analytics**: Analyze customer consumption patterns over time
// - **Billing transparency**: Provide customers with detailed usage breakdowns
// - **Revenue optimization**: Identify usage trends to optimize pricing strategies
//
// ## Filtering Options:
//
// - **Date range filtering**: Get usage history for specific time periods
// - **Meter-specific filtering**: Focus on usage for a particular meter
// - **Pagination**: Navigate through large usage histories efficiently
//
// ## Important Notes:
//
// - Only returns data for subscriptions with usage-based (metered) components
// - Usage history is organized by billing periods (subscription cycles)
// - Free threshold units are calculated and displayed separately from chargeable
// units
// - Historical data is preserved even if meter configurations change
//
// ## Example Query Patterns:
//
// - Get last 3 months:
// `?start_date=2024-01-01T00:00:00Z&end_date=2024-03-31T23:59:59Z`
// - Filter by meter: `?meter_id=mtr_api_requests`
// - Paginate results: `?page_size=20&page_number=1`
// - Recent usage: `?start_date=2024-03-01T00:00:00Z` (from March 1st to now)
func (r *SubscriptionService) GetUsageHistoryAutoPaging(ctx context.Context, subscriptionID string, query SubscriptionGetUsageHistoryParams, opts ...option.RequestOption) *pagination.DefaultPageNumberPaginationAutoPager[SubscriptionGetUsageHistoryResponse] {
return pagination.NewDefaultPageNumberPaginationAutoPager(r.GetUsageHistory(ctx, subscriptionID, query, opts...))
}
func (r *SubscriptionService) UpdatePaymentMethod(ctx context.Context, subscriptionID string, body SubscriptionUpdatePaymentMethodParams, opts ...option.RequestOption) (res *SubscriptionUpdatePaymentMethodResponse, err error) {
opts = slices.Concat(r.Options, opts)
if subscriptionID == "" {
err = errors.New("missing required subscription_id parameter")
return nil, err
}
path := fmt.Sprintf("subscriptions/%s/update-payment-method", subscriptionID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Response struct representing subscription details
type AddonCartResponseItem struct {
AddonID string `json:"addon_id" api:"required"`
Quantity int64 `json:"quantity" api:"required"`
JSON addonCartResponseItemJSON `json:"-"`
}
// addonCartResponseItemJSON contains the JSON metadata for the struct
// [AddonCartResponseItem]
type addonCartResponseItemJSON struct {
AddonID apijson.Field
Quantity apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *AddonCartResponseItem) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r addonCartResponseItemJSON) RawJSON() string {
return r.raw
}
type AttachAddonParam struct {
AddonID param.Field[string] `json:"addon_id" api:"required"`
Quantity param.Field[int64] `json:"quantity" api:"required"`
}
func (r AttachAddonParam) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type CancellationFeedback string
const (
CancellationFeedbackTooExpensive CancellationFeedback = "too_expensive"
CancellationFeedbackMissingFeatures CancellationFeedback = "missing_features"
CancellationFeedbackSwitchedService CancellationFeedback = "switched_service"
CancellationFeedbackUnused CancellationFeedback = "unused"
CancellationFeedbackCustomerService CancellationFeedback = "customer_service"
CancellationFeedbackLowQuality CancellationFeedback = "low_quality"
CancellationFeedbackTooComplex CancellationFeedback = "too_complex"
CancellationFeedbackOther CancellationFeedback = "other"
)
func (r CancellationFeedback) IsKnown() bool {
switch r {
case CancellationFeedbackTooExpensive, CancellationFeedbackMissingFeatures, CancellationFeedbackSwitchedService, CancellationFeedbackUnused, CancellationFeedbackCustomerService, CancellationFeedbackLowQuality, CancellationFeedbackTooComplex, CancellationFeedbackOther:
return true
}
return false
}
// Response struct representing credit entitlement cart details for a subscription
type CreditEntitlementCartResponse struct {
CreditEntitlementID string `json:"credit_entitlement_id" api:"required"`
CreditEntitlementName string `json:"credit_entitlement_name" api:"required"`
CreditsAmount string `json:"credits_amount" api:"required"`
// Customer's current overage balance for this entitlement
OverageBalance string `json:"overage_balance" api:"required"`
// Controls how overage is handled at the end of a billing cycle.
//
// | Preset | Charge at billing | Credits reduce overage | Preserve overage at reset |
// | -------------------------- | :---------------: | :--------------------: | :-----------------------: |
// | `forgive_at_reset` | No | No | No |
// | `invoice_at_billing` | Yes | No | No |
// | `carry_deficit` | No | No | Yes |
// | `carry_deficit_auto_repay` | No | Yes | Yes |
OverageBehavior CbbOverageBehavior `json:"overage_behavior" api:"required"`
OverageEnabled bool `json:"overage_enabled" api:"required"`
ProductID string `json:"product_id" api:"required"`
// Customer's current remaining credit balance for this entitlement
RemainingBalance string `json:"remaining_balance" api:"required"`
RolloverEnabled bool `json:"rollover_enabled" api:"required"`
// Unit label for the credit entitlement (e.g., "API Calls", "Tokens")
Unit string `json:"unit" api:"required"`
ExpiresAfterDays int64 `json:"expires_after_days" api:"nullable"`
LowBalanceThresholdPercent int64 `json:"low_balance_threshold_percent" api:"nullable"`
MaxRolloverCount int64 `json:"max_rollover_count" api:"nullable"`
OverageLimit string `json:"overage_limit" api:"nullable"`
RolloverPercentage int64 `json:"rollover_percentage" api:"nullable"`
RolloverTimeframeCount int64 `json:"rollover_timeframe_count" api:"nullable"`
RolloverTimeframeInterval TimeInterval `json:"rollover_timeframe_interval" api:"nullable"`
JSON creditEntitlementCartResponseJSON `json:"-"`
}
// creditEntitlementCartResponseJSON contains the JSON metadata for the struct
// [CreditEntitlementCartResponse]
type creditEntitlementCartResponseJSON struct {
CreditEntitlementID apijson.Field
CreditEntitlementName apijson.Field
CreditsAmount apijson.Field
OverageBalance apijson.Field
OverageBehavior apijson.Field
OverageEnabled apijson.Field
ProductID apijson.Field
RemainingBalance apijson.Field
RolloverEnabled apijson.Field
Unit apijson.Field
ExpiresAfterDays apijson.Field
LowBalanceThresholdPercent apijson.Field
MaxRolloverCount apijson.Field
OverageLimit apijson.Field
RolloverPercentage apijson.Field
RolloverTimeframeCount apijson.Field
RolloverTimeframeInterval apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *CreditEntitlementCartResponse) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r creditEntitlementCartResponseJSON) RawJSON() string {
return r.raw
}
// Response struct representing usage-based meter cart details for a subscription
type MeterCartResponseItem struct {
Currency Currency `json:"currency" api:"required"`
FreeThreshold int64 `json:"free_threshold" api:"required"`
MeasurementUnit string `json:"measurement_unit" api:"required"`
MeterID string `json:"meter_id" api:"required"`
Name string `json:"name" api:"required"`
Description string `json:"description" api:"nullable"`
PricePerUnit string `json:"price_per_unit" api:"nullable"`
JSON meterCartResponseItemJSON `json:"-"`
}
// meterCartResponseItemJSON contains the JSON metadata for the struct
// [MeterCartResponseItem]
type meterCartResponseItemJSON struct {
Currency apijson.Field
FreeThreshold apijson.Field
MeasurementUnit apijson.Field
MeterID apijson.Field
Name apijson.Field
Description apijson.Field
PricePerUnit apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MeterCartResponseItem) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r meterCartResponseItemJSON) RawJSON() string {
return r.raw
}
// Response struct representing meter-credit entitlement mapping cart details for a
// subscription
type MeterCreditEntitlementCartResponse struct {
CreditEntitlementID string `json:"credit_entitlement_id" api:"required"`
MeterID string `json:"meter_id" api:"required"`
MeterName string `json:"meter_name" api:"required"`
MeterUnitsPerCredit string `json:"meter_units_per_credit" api:"required"`
ProductID string `json:"product_id" api:"required"`
JSON meterCreditEntitlementCartResponseJSON `json:"-"`
}
// meterCreditEntitlementCartResponseJSON contains the JSON metadata for the struct
// [MeterCreditEntitlementCartResponse]
type meterCreditEntitlementCartResponseJSON struct {
CreditEntitlementID apijson.Field
MeterID apijson.Field
MeterName apijson.Field
MeterUnitsPerCredit apijson.Field
ProductID apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MeterCreditEntitlementCartResponse) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r meterCreditEntitlementCartResponseJSON) RawJSON() string {
return r.raw
}
type OnDemandSubscriptionParam struct {
// If set as True, does not perform any charge and only authorizes payment method
// details for future use.
MandateOnly param.Field[bool] `json:"mandate_only" api:"required"`
// Whether adaptive currency fees should be included in the product_price (true) or
// added on top (false). This field is ignored if adaptive pricing is not enabled
// for the business.
AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
// Optional currency of the product price. If not specified, defaults to the
// currency of the product.
ProductCurrency param.Field[Currency] `json:"product_currency"`
// Optional product description override for billing and line items. If not
// specified, the stored description of the product will be used.
ProductDescription param.Field[string] `json:"product_description"`
// Product price for the initial charge to customer If not specified the stored
// price of the product will be used Represented in the lowest denomination of the
// currency (e.g., cents for USD). For example, to charge $1.00, pass `100`.
ProductPrice param.Field[int64] `json:"product_price"`
}
func (r OnDemandSubscriptionParam) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type ScheduledPlanChange struct {
// The scheduled plan change ID
ID string `json:"id" api:"required"`
// Addons included in the scheduled change
Addons []ScheduledPlanChangeAddon `json:"addons" api:"required"`
// When this scheduled change was created
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// When the change will be applied
EffectiveAt time.Time `json:"effective_at" api:"required" format:"date-time"`
// The product ID the subscription will change to
ProductID string `json:"product_id" api:"required"`
// Quantity for the new plan
Quantity int64 `json:"quantity" api:"required"`
// Description of the product being changed to
ProductDescription string `json:"product_description" api:"nullable"`
// Name of the product being changed to
ProductName string `json:"product_name" api:"nullable"`
JSON scheduledPlanChangeJSON `json:"-"`
}
// scheduledPlanChangeJSON contains the JSON metadata for the struct
// [ScheduledPlanChange]
type scheduledPlanChangeJSON struct {
ID apijson.Field
Addons apijson.Field
CreatedAt apijson.Field
EffectiveAt apijson.Field
ProductID apijson.Field
Quantity apijson.Field
ProductDescription apijson.Field
ProductName apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ScheduledPlanChange) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r scheduledPlanChangeJSON) RawJSON() string {
return r.raw
}
type ScheduledPlanChangeAddon struct {
// The addon ID
AddonID string `json:"addon_id" api:"required"`
// Name of the addon
Name string `json:"name" api:"required"`
// Quantity of the addon
Quantity int64 `json:"quantity" api:"required"`
JSON scheduledPlanChangeAddonJSON `json:"-"`
}
// scheduledPlanChangeAddonJSON contains the JSON metadata for the struct
// [ScheduledPlanChangeAddon]
type scheduledPlanChangeAddonJSON struct {
AddonID apijson.Field
Name apijson.Field
Quantity apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ScheduledPlanChangeAddon) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r scheduledPlanChangeAddonJSON) RawJSON() string {
return r.raw
}
// Response struct representing subscription details
type Subscription struct {
// Addons associated with this subscription
Addons []AddonCartResponseItem `json:"addons" api:"required"`
// Billing address details for payments
Billing BillingAddress `json:"billing" api:"required"`
// Brand id this subscription belongs to
BrandID string `json:"brand_id" api:"required"`
// Indicates if the subscription will cancel at the next billing date
CancelAtNextBillingDate bool `json:"cancel_at_next_billing_date" api:"required"`
// Timestamp when the subscription was created
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// Credit entitlement cart settings for this subscription
CreditEntitlementCart []CreditEntitlementCartResponse `json:"credit_entitlement_cart" api:"required"`
// Currency used for the subscription payments
Currency Currency `json:"currency" api:"required"`
// Customer details associated with the subscription
Customer CustomerLimitedDetails `json:"customer" api:"required"`
// Additional custom data associated with the subscription
Metadata Metadata `json:"metadata" api:"required"`
// Meter credit entitlement cart settings for this subscription
MeterCreditEntitlementCart []MeterCreditEntitlementCartResponse `json:"meter_credit_entitlement_cart" api:"required"`
// Meters associated with this subscription (for usage-based billing)
Meters []MeterCartResponseItem `json:"meters" api:"required"`
// Timestamp of the next scheduled billing. Indicates the end of current billing
// period
NextBillingDate time.Time `json:"next_billing_date" api:"required" format:"date-time"`
// Wether the subscription is on-demand or not
OnDemand bool `json:"on_demand" api:"required"`
// Number of payment frequency intervals
PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
// Time interval for payment frequency (e.g. month, year)
PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
// Timestamp of the last payment. Indicates the start of current billing period
PreviousBillingDate time.Time `json:"previous_billing_date" api:"required" format:"date-time"`
// Identifier of the product associated with this subscription
ProductID string `json:"product_id" api:"required"`
// Number of units/items included in the subscription
Quantity int64 `json:"quantity" api:"required"`
// Amount charged before tax for each recurring payment in the currency's smallest
// unit (cents for USD, yen for JPY, fils for KWD)
RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
// Current status of the subscription
Status SubscriptionStatus `json:"status" api:"required"`
// Unique identifier for the subscription
SubscriptionID string `json:"subscription_id" api:"required"`
// Number of subscription period intervals
SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
// Time interval for the subscription period (e.g. month, year)
SubscriptionPeriodInterval TimeInterval `json:"subscription_period_interval" api:"required"`
// Indicates if the recurring_pre_tax_amount is tax inclusive
TaxInclusive bool `json:"tax_inclusive" api:"required"`
// Number of days in the trial period (0 if no trial)
TrialPeriodDays int64 `json:"trial_period_days" api:"required"`
// Free-text cancellation comment, if any
CancellationComment string `json:"cancellation_comment" api:"nullable"`
// Customer-supplied churn reason, if any
CancellationFeedback CancellationFeedback `json:"cancellation_feedback" api:"nullable"`
// Cancelled timestamp if the subscription is cancelled
CancelledAt time.Time `json:"cancelled_at" api:"nullable" format:"date-time"`
// Customer's responses to custom fields collected during checkout
CustomFieldResponses []CustomFieldResponse `json:"custom_field_responses" api:"nullable"`
// Business / legal name associated with the tax id (B2B). When set this is used on
// the invoice in place of the customer's personal name.
CustomerBusinessName string `json:"customer_business_name" api:"nullable"`
// DEPRECATED: Use discounts[].cycles_remaining instead.
DiscountCyclesRemaining int64 `json:"discount_cycles_remaining" api:"nullable"`
// DEPRECATED: Use discounts instead. Returns the first discount's ID if present.
DiscountID string `json:"discount_id" api:"nullable"`
// All stacked discounts applied, ordered by position
Discounts []DiscountDetail `json:"discounts" api:"nullable"`
// Timestamp when the subscription will expire
ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
// Saved payment method id used for recurring charges
PaymentMethodID string `json:"payment_method_id" api:"nullable"`
// Scheduled plan change details, if any
ScheduledChange ScheduledPlanChange `json:"scheduled_change" api:"nullable"`
// Tax identifier provided for this subscription (if applicable)
TaxID string `json:"tax_id" api:"nullable"`
JSON subscriptionJSON `json:"-"`
}
// subscriptionJSON contains the JSON metadata for the struct [Subscription]
type subscriptionJSON struct {
Addons apijson.Field
Billing apijson.Field
BrandID apijson.Field
CancelAtNextBillingDate apijson.Field
CreatedAt apijson.Field
CreditEntitlementCart apijson.Field
Currency apijson.Field
Customer apijson.Field
Metadata apijson.Field
MeterCreditEntitlementCart apijson.Field
Meters apijson.Field
NextBillingDate apijson.Field
OnDemand apijson.Field
PaymentFrequencyCount apijson.Field
PaymentFrequencyInterval apijson.Field
PreviousBillingDate apijson.Field
ProductID apijson.Field
Quantity apijson.Field
RecurringPreTaxAmount apijson.Field
Status apijson.Field
SubscriptionID apijson.Field
SubscriptionPeriodCount apijson.Field
SubscriptionPeriodInterval apijson.Field
TaxInclusive apijson.Field
TrialPeriodDays apijson.Field
CancellationComment apijson.Field
CancellationFeedback apijson.Field
CancelledAt apijson.Field
CustomFieldResponses apijson.Field
CustomerBusinessName apijson.Field
DiscountCyclesRemaining apijson.Field
DiscountID apijson.Field
Discounts apijson.Field
ExpiresAt apijson.Field
PaymentMethodID apijson.Field
ScheduledChange apijson.Field
TaxID apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *Subscription) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r subscriptionJSON) RawJSON() string {
return r.raw
}
type SubscriptionStatus string
const (
SubscriptionStatusPending SubscriptionStatus = "pending"
SubscriptionStatusActive SubscriptionStatus = "active"
SubscriptionStatusOnHold SubscriptionStatus = "on_hold"
SubscriptionStatusCancelled SubscriptionStatus = "cancelled"
SubscriptionStatusFailed SubscriptionStatus = "failed"
SubscriptionStatusExpired SubscriptionStatus = "expired"
)
func (r SubscriptionStatus) IsKnown() bool {
switch r {
case SubscriptionStatusPending, SubscriptionStatusActive, SubscriptionStatusOnHold, SubscriptionStatusCancelled, SubscriptionStatusFailed, SubscriptionStatusExpired:
return true
}
return false
}
type TimeInterval string
const (
TimeIntervalDay TimeInterval = "Day"
TimeIntervalWeek TimeInterval = "Week"
TimeIntervalMonth TimeInterval = "Month"
TimeIntervalYear TimeInterval = "Year"
)
func (r TimeInterval) IsKnown() bool {
switch r {
case TimeIntervalDay, TimeIntervalWeek, TimeIntervalMonth, TimeIntervalYear:
return true
}
return false
}
type UpdateSubscriptionPlanReqParam struct {
// Unique identifier of the product to subscribe to
ProductID param.Field[string] `json:"product_id" api:"required"`
// Proration Billing Mode
ProrationBillingMode param.Field[UpdateSubscriptionPlanReqProrationBillingMode] `json:"proration_billing_mode" api:"required"`
// Number of units to subscribe for. Must be at least 1.
Quantity param.Field[int64] `json:"quantity" api:"required"`
// Whether adaptive currency fees should be included in the price (true) or added
// on top (false). If not specified, uses the subscription's stored setting.
AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
// Addons for the new plan. Note : Leaving this empty would remove any existing
// addons
Addons param.Field[[]AttachAddonParam] `json:"addons"`
// DEPRECATED: Use discount_codes instead. Cannot be used together with
// discount_codes.
//
// Deprecated: Use `discount_id` instead.
DiscountCode param.Field[string] `json:"discount_code"`
// Stacked discount codes to apply to the new plan. Max 20. Cannot be used together
// with discount_code. If provided, replaces any existing discount codes. Empty
// array removes all discounts. If not provided (None), existing discounts with
// preserve_on_plan_change=true are preserved.
DiscountCodes param.Field[[]string] `json:"discount_codes"`
// When to apply the plan change.
//
// - `immediately` (default): Apply the plan change right away
// - `next_billing_date`: Schedule the change for the next billing date
EffectiveAt param.Field[UpdateSubscriptionPlanReqEffectiveAt] `json:"effective_at"`
// Metadata for the payment. If not passed, the metadata of the subscription will
// be taken
Metadata param.Field[MetadataParam] `json:"metadata"`
// Controls behavior when the plan change payment fails.
//
// - `prevent_change`: Keep subscription on current plan until payment succeeds
// - `apply_change` (default): Apply plan change immediately regardless of payment
// outcome
//
// If not specified, uses the business-level default setting.
OnPaymentFailure param.Field[UpdateSubscriptionPlanReqOnPaymentFailure] `json:"on_payment_failure"`
}
func (r UpdateSubscriptionPlanReqParam) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
// Proration Billing Mode
type UpdateSubscriptionPlanReqProrationBillingMode string
const (
UpdateSubscriptionPlanReqProrationBillingModeProratedImmediately UpdateSubscriptionPlanReqProrationBillingMode = "prorated_immediately"
UpdateSubscriptionPlanReqProrationBillingModeFullImmediately UpdateSubscriptionPlanReqProrationBillingMode = "full_immediately"
UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately UpdateSubscriptionPlanReqProrationBillingMode = "difference_immediately"
UpdateSubscriptionPlanReqProrationBillingModeDoNotBill UpdateSubscriptionPlanReqProrationBillingMode = "do_not_bill"
)
func (r UpdateSubscriptionPlanReqProrationBillingMode) IsKnown() bool {
switch r {
case UpdateSubscriptionPlanReqProrationBillingModeProratedImmediately, UpdateSubscriptionPlanReqProrationBillingModeFullImmediately, UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately, UpdateSubscriptionPlanReqProrationBillingModeDoNotBill:
return true
}
return false
}
// When to apply the plan change.
//
// - `immediately` (default): Apply the plan change right away
// - `next_billing_date`: Schedule the change for the next billing date
type UpdateSubscriptionPlanReqEffectiveAt string
const (
UpdateSubscriptionPlanReqEffectiveAtImmediately UpdateSubscriptionPlanReqEffectiveAt = "immediately"
UpdateSubscriptionPlanReqEffectiveAtNextBillingDate UpdateSubscriptionPlanReqEffectiveAt = "next_billing_date"
)
func (r UpdateSubscriptionPlanReqEffectiveAt) IsKnown() bool {
switch r {
case UpdateSubscriptionPlanReqEffectiveAtImmediately, UpdateSubscriptionPlanReqEffectiveAtNextBillingDate:
return true
}
return false
}
// Controls behavior when the plan change payment fails.
//
// - `prevent_change`: Keep subscription on current plan until payment succeeds
// - `apply_change` (default): Apply plan change immediately regardless of payment
// outcome
//
// If not specified, uses the business-level default setting.
type UpdateSubscriptionPlanReqOnPaymentFailure string
const (
UpdateSubscriptionPlanReqOnPaymentFailurePreventChange UpdateSubscriptionPlanReqOnPaymentFailure = "prevent_change"
UpdateSubscriptionPlanReqOnPaymentFailureApplyChange UpdateSubscriptionPlanReqOnPaymentFailure = "apply_change"
)
func (r UpdateSubscriptionPlanReqOnPaymentFailure) IsKnown() bool {
switch r {
case UpdateSubscriptionPlanReqOnPaymentFailurePreventChange, UpdateSubscriptionPlanReqOnPaymentFailureApplyChange:
return true
}
return false
}
type SubscriptionNewResponse struct {
// Addons associated with this subscription
Addons []AddonCartResponseItem `json:"addons" api:"required"`
// Customer details associated with this subscription
Customer CustomerLimitedDetails `json:"customer" api:"required"`
// Additional metadata associated with the subscription
Metadata Metadata `json:"metadata" api:"required"`
// First payment id for the subscription
PaymentID string `json:"payment_id" api:"required"`
// Tax will be added to the amount and charged to the customer on each billing
// cycle
RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
// Unique identifier for the subscription
SubscriptionID string `json:"subscription_id" api:"required"`
// Client secret used to load Dodo checkout SDK NOTE : Dodo checkout SDK will be
// coming soon
ClientSecret string `json:"client_secret" api:"nullable"`
// DEPRECATED: Use discount_ids instead. Returns the first discount's ID if
// present.
//
// Deprecated: Use `discounts` instead.
DiscountID string `json:"discount_id" api:"nullable"`
// All stacked discount IDs applied, in order of application
DiscountIDs []string `json:"discount_ids" api:"nullable"`
// Expiry timestamp of the payment link
ExpiresOn time.Time `json:"expires_on" api:"nullable" format:"date-time"`
// One time products associated with the purchase of subscription
OneTimeProductCart []SubscriptionNewResponseOneTimeProductCart `json:"one_time_product_cart" api:"nullable"`
// URL to checkout page
PaymentLink string `json:"payment_link" api:"nullable"`
JSON subscriptionNewResponseJSON `json:"-"`
}
// subscriptionNewResponseJSON contains the JSON metadata for the struct
// [SubscriptionNewResponse]
type subscriptionNewResponseJSON struct {
Addons apijson.Field
Customer apijson.Field
Metadata apijson.Field
PaymentID apijson.Field
RecurringPreTaxAmount apijson.Field
SubscriptionID apijson.Field
ClientSecret apijson.Field
DiscountID apijson.Field
DiscountIDs apijson.Field
ExpiresOn apijson.Field
OneTimeProductCart apijson.Field
PaymentLink apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SubscriptionNewResponse) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r subscriptionNewResponseJSON) RawJSON() string {
return r.raw
}
type SubscriptionNewResponseOneTimeProductCart struct {
ProductID string `json:"product_id" api:"required"`
Quantity int64 `json:"quantity" api:"required"`
JSON subscriptionNewResponseOneTimeProductCartJSON `json:"-"`
}
// subscriptionNewResponseOneTimeProductCartJSON contains the JSON metadata for the
// struct [SubscriptionNewResponseOneTimeProductCart]
type subscriptionNewResponseOneTimeProductCartJSON struct {
ProductID apijson.Field
Quantity apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SubscriptionNewResponseOneTimeProductCart) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r subscriptionNewResponseOneTimeProductCartJSON) RawJSON() string {
return r.raw
}
// Response struct representing subscription details
type SubscriptionListResponse struct {
// Billing address details for payments
Billing BillingAddress `json:"billing" api:"required"`
// Indicates if the subscription will cancel at the next billing date
CancelAtNextBillingDate bool `json:"cancel_at_next_billing_date" api:"required"`
// Timestamp when the subscription was created
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
// Currency used for the subscription payments
Currency Currency `json:"currency" api:"required"`
// Customer details associated with the subscription
Customer CustomerLimitedDetails `json:"customer" api:"required"`
// All stacked discounts applied, in order of application
Discounts []SubscriptionListResponseDiscount `json:"discounts" api:"required"`
// Additional custom data associated with the subscription
Metadata Metadata `json:"metadata" api:"required"`
// Timestamp of the next scheduled billing. Indicates the end of current billing
// period
NextBillingDate time.Time `json:"next_billing_date" api:"required" format:"date-time"`
// Wether the subscription is on-demand or not
OnDemand bool `json:"on_demand" api:"required"`
// Number of payment frequency intervals
PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
// Time interval for payment frequency (e.g. month, year)
PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
// Timestamp of the last payment. Indicates the start of current billing period
PreviousBillingDate time.Time `json:"previous_billing_date" api:"required" format:"date-time"`
// Identifier of the product associated with this subscription
ProductID string `json:"product_id" api:"required"`
// Number of units/items included in the subscription
Quantity int64 `json:"quantity" api:"required"`
// Amount charged before tax for each recurring payment in the currency's smallest
// unit (cents for USD, yen for JPY, fils for KWD)
RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
// Current status of the subscription
Status SubscriptionStatus `json:"status" api:"required"`
// Unique identifier for the subscription
SubscriptionID string `json:"subscription_id" api:"required"`
// Number of subscription period intervals
SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
// Time interval for the subscription period (e.g. month, year)
SubscriptionPeriodInterval TimeInterval `json:"subscription_period_interval" api:"required"`
// Indicates if the recurring_pre_tax_amount is tax inclusive
TaxInclusive bool `json:"tax_inclusive" api:"required"`
// Number of days in the trial period (0 if no trial)
TrialPeriodDays int64 `json:"trial_period_days" api:"required"`
// Cancelled timestamp if the subscription is cancelled
CancelledAt time.Time `json:"cancelled_at" api:"nullable" format:"date-time"`
// Business / legal name associated with the tax id (B2B). When set this is used on
// the invoice in place of the customer's personal name.
CustomerBusinessName string `json:"customer_business_name" api:"nullable"`
// DEPRECATED: Use discounts[].cycles_remaining instead.
DiscountCyclesRemaining int64 `json:"discount_cycles_remaining" api:"nullable"`
// DEPRECATED: Use discounts instead.
DiscountID string `json:"discount_id" api:"nullable"`
// Saved payment method id used for recurring charges
PaymentMethodID string `json:"payment_method_id" api:"nullable"`
// Name of the product associated with this subscription
ProductName string `json:"product_name" api:"nullable"`
// Scheduled plan change details, if any
ScheduledChange ScheduledPlanChange `json:"scheduled_change" api:"nullable"`
// Tax identifier provided for this subscription (if applicable)
TaxID string `json:"tax_id" api:"nullable"`
JSON subscriptionListResponseJSON `json:"-"`
}
// subscriptionListResponseJSON contains the JSON metadata for the struct
// [SubscriptionListResponse]
type subscriptionListResponseJSON struct {
Billing apijson.Field
CancelAtNextBillingDate apijson.Field
CreatedAt apijson.Field
Currency apijson.Field
Customer apijson.Field
Discounts apijson.Field
Metadata apijson.Field
NextBillingDate apijson.Field
OnDemand apijson.Field
PaymentFrequencyCount apijson.Field
PaymentFrequencyInterval apijson.Field
PreviousBillingDate apijson.Field
ProductID apijson.Field
Quantity apijson.Field
RecurringPreTaxAmount apijson.Field
Status apijson.Field
SubscriptionID apijson.Field
SubscriptionPeriodCount apijson.Field
SubscriptionPeriodInterval apijson.Field
TaxInclusive apijson.Field
TrialPeriodDays apijson.Field
CancelledAt apijson.Field
CustomerBusinessName apijson.Field
DiscountCyclesRemaining apijson.Field
DiscountID apijson.Field
PaymentMethodID apijson.Field