stripe_shared/
subscription.rs

1/// Subscriptions allow you to charge a customer on a recurring basis.
2///
3/// Related guide: [Creating subscriptions](https://docs.stripe.com/billing/subscriptions/creating)
4///
5/// For more details see <<https://stripe.com/docs/api/subscriptions/object>>.
6#[derive(Clone, Debug)]
7#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
8pub struct Subscription {
9    /// ID of the Connect Application that created the subscription.
10    pub application: Option<stripe_types::Expandable<stripe_shared::Application>>,
11    /// A non-negative decimal between 0 and 100, with at most two decimal places.
12    /// This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account.
13    pub application_fee_percent: Option<f64>,
14    pub automatic_tax: stripe_shared::SubscriptionAutomaticTax,
15    /// The reference point that aligns future [billing cycle](https://docs.stripe.com/subscriptions/billing-cycle) dates.
16    /// It sets the day of week for `week` intervals, the day of month for `month` and `year` intervals, and the month of year for `year` intervals.
17    /// The timestamp is in UTC format.
18    pub billing_cycle_anchor: stripe_types::Timestamp,
19    /// The fixed values used to calculate the `billing_cycle_anchor`.
20    pub billing_cycle_anchor_config:
21        Option<stripe_shared::SubscriptionsResourceBillingCycleAnchorConfig>,
22    pub billing_mode: stripe_shared::SubscriptionsResourceBillingMode,
23    /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period.
24    pub billing_thresholds: Option<stripe_shared::SubscriptionBillingThresholds>,
25    /// A date in the future at which the subscription will automatically get canceled
26    pub cancel_at: Option<stripe_types::Timestamp>,
27    /// Whether this subscription will (if `status=active`) or did (if `status=canceled`) cancel at the end of the current billing period.
28    pub cancel_at_period_end: bool,
29    /// If the subscription has been canceled, the date of that cancellation.
30    /// If the subscription was canceled with `cancel_at_period_end`, `canceled_at` will reflect the time of the most recent update request, not the end of the subscription period when the subscription is automatically moved to a canceled state.
31    pub canceled_at: Option<stripe_types::Timestamp>,
32    /// Details about why this subscription was cancelled
33    pub cancellation_details: Option<stripe_shared::CancellationDetails>,
34    /// Either `charge_automatically`, or `send_invoice`.
35    /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer.
36    /// When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as `active`.
37    pub collection_method: stripe_shared::SubscriptionCollectionMethod,
38    /// Time at which the object was created. Measured in seconds since the Unix epoch.
39    pub created: stripe_types::Timestamp,
40    /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
41    /// Must be a [supported currency](https://stripe.com/docs/currencies).
42    pub currency: stripe_types::Currency,
43    /// ID of the customer who owns the subscription.
44    pub customer: stripe_types::Expandable<stripe_shared::Customer>,
45    /// ID of the account representing the customer who owns the subscription.
46    pub customer_account: Option<String>,
47    /// Number of days a customer has to pay invoices generated by this subscription.
48    /// This value will be `null` for subscriptions where `collection_method=charge_automatically`.
49    pub days_until_due: Option<u32>,
50    /// ID of the default payment method for the subscription.
51    /// It must belong to the customer associated with the subscription.
52    /// This takes precedence over `default_source`.
53    /// If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://docs.stripe.com/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://docs.stripe.com/api/customers/object#customer_object-default_source).
54    pub default_payment_method: Option<stripe_types::Expandable<stripe_shared::PaymentMethod>>,
55    /// ID of the default payment source for the subscription.
56    /// It must belong to the customer associated with the subscription and be in a chargeable state.
57    /// If `default_payment_method` is also set, `default_payment_method` will take precedence.
58    /// If neither are set, invoices will use the customer's [invoice_settings.default_payment_method](https://docs.stripe.com/api/customers/object#customer_object-invoice_settings-default_payment_method) or [default_source](https://docs.stripe.com/api/customers/object#customer_object-default_source).
59    pub default_source: Option<stripe_types::Expandable<stripe_shared::PaymentSource>>,
60    /// The tax rates that will apply to any subscription item that does not have `tax_rates` set.
61    /// Invoices created will have their `default_tax_rates` populated from the subscription.
62    pub default_tax_rates: Option<Vec<stripe_shared::TaxRate>>,
63    /// The subscription's description, meant to be displayable to the customer.
64    /// Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs.
65    pub description: Option<String>,
66    /// The discounts applied to the subscription.
67    /// Subscription item discounts are applied before subscription discounts.
68    /// Use `expand[]=discounts` to expand each discount.
69    pub discounts: Vec<stripe_types::Expandable<stripe_shared::Discount>>,
70    /// If the subscription has ended, the date the subscription ended.
71    pub ended_at: Option<stripe_types::Timestamp>,
72    /// Unique identifier for the object.
73    pub id: stripe_shared::SubscriptionId,
74    pub invoice_settings: stripe_shared::SubscriptionsResourceSubscriptionInvoiceSettings,
75    /// List of subscription items, each with an attached price.
76    pub items: stripe_types::List<stripe_shared::SubscriptionItem>,
77    /// The most recent invoice this subscription has generated.
78    pub latest_invoice: Option<stripe_types::Expandable<stripe_shared::Invoice>>,
79    /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
80    pub livemode: bool,
81    /// Set of [key-value pairs](https://docs.stripe.com/api/metadata) that you can attach to an object.
82    /// This can be useful for storing additional information about the object in a structured format.
83    pub metadata: std::collections::HashMap<String, String>,
84    /// Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at `pending_invoice_item_interval`.
85    pub next_pending_invoice_item_invoice: Option<stripe_types::Timestamp>,
86    /// The account (if any) the charge was made on behalf of for charges associated with this subscription.
87    /// See the [Connect documentation](https://docs.stripe.com/connect/subscriptions#on-behalf-of) for details.
88    pub on_behalf_of: Option<stripe_types::Expandable<stripe_shared::Account>>,
89    /// If specified, payment collection for this subscription will be paused.
90    /// Note that the subscription status will be unchanged and will not be updated to `paused`.
91    /// Learn more about [pausing collection](https://docs.stripe.com/billing/subscriptions/pause-payment).
92    pub pause_collection: Option<stripe_shared::SubscriptionsResourcePauseCollection>,
93    /// Payment settings passed on to invoices created by the subscription.
94    pub payment_settings: Option<stripe_shared::SubscriptionsResourcePaymentSettings>,
95    /// Specifies an interval for how often to bill for any pending invoice items.
96    /// It is analogous to calling [Create an invoice](https://docs.stripe.com/api#create_invoice) for the given subscription at the specified interval.
97    pub pending_invoice_item_interval:
98        Option<stripe_shared::SubscriptionPendingInvoiceItemInterval>,
99    /// You can use this [SetupIntent](https://docs.stripe.com/api/setup_intents) to collect user authentication when creating a subscription without immediate payment or updating a subscription's payment method, allowing you to optimize for off-session payments.
100    /// Learn more in the [SCA Migration Guide](https://docs.stripe.com/billing/migration/strong-customer-authentication#scenario-2).
101    pub pending_setup_intent: Option<stripe_types::Expandable<stripe_shared::SetupIntent>>,
102    /// If specified, [pending updates](https://docs.stripe.com/billing/subscriptions/pending-updates) that will be applied to the subscription once the `latest_invoice` has been paid.
103    pub pending_update: Option<stripe_shared::SubscriptionsResourcePendingUpdate>,
104    /// The schedule attached to the subscription
105    pub schedule: Option<stripe_types::Expandable<stripe_shared::SubscriptionSchedule>>,
106    /// Date when the subscription was first created.
107    /// The date might differ from the `created` date due to backdating.
108    pub start_date: stripe_types::Timestamp,
109    /// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, `unpaid`, or `paused`.
110    ///
111    ///
112    /// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails.
113    /// A subscription in this status can only have metadata and default_source updated.
114    /// Once the first invoice is paid, the subscription moves into an `active` status.
115    /// If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`.
116    /// This is a terminal status, the open invoice will be voided and no further invoices will be generated.
117    ///
118    ///
119    /// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over.
120    ///
121    ///
122    /// A subscription can only enter a `paused` status [when a trial ends without a payment method](https://docs.stripe.com/billing/subscriptions/trials#create-free-trials-without-payment).
123    /// A `paused` subscription doesn't generate invoices and can be resumed after your customer adds their payment method.
124    /// The `paused` status is different from [pausing collection](https://docs.stripe.com/billing/subscriptions/pause-payment), which still generates invoices and leaves the subscription's status unchanged.
125    ///
126    ///
127    /// If subscription `collection_method=charge_automatically`, it becomes `past_due` when payment is required but cannot be paid (due to failed payment or awaiting additional user actions).
128    /// Once Stripe has exhausted all payment retry attempts, the subscription will become `canceled` or `unpaid` (depending on your subscriptions settings).
129    ///
130    ///
131    /// If subscription `collection_method=send_invoice` it becomes `past_due` when its invoice is not paid by the due date, and `canceled` or `unpaid` if it is still not paid by an additional deadline after that.
132    /// Note that when a subscription has a status of `unpaid`, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed).
133    /// After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices.
134    pub status: SubscriptionStatus,
135    /// ID of the test clock this subscription belongs to.
136    pub test_clock: Option<stripe_types::Expandable<stripe_shared::TestHelpersTestClock>>,
137    /// The account (if any) the subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices.
138    pub transfer_data: Option<stripe_shared::SubscriptionTransferData>,
139    /// If the subscription has a trial, the end of that trial.
140    pub trial_end: Option<stripe_types::Timestamp>,
141    /// Settings related to subscription trials.
142    pub trial_settings: Option<stripe_shared::SubscriptionsTrialsResourceTrialSettings>,
143    /// If the subscription has a trial, the beginning of that trial.
144    pub trial_start: Option<stripe_types::Timestamp>,
145}
146#[doc(hidden)]
147pub struct SubscriptionBuilder {
148    application: Option<Option<stripe_types::Expandable<stripe_shared::Application>>>,
149    application_fee_percent: Option<Option<f64>>,
150    automatic_tax: Option<stripe_shared::SubscriptionAutomaticTax>,
151    billing_cycle_anchor: Option<stripe_types::Timestamp>,
152    billing_cycle_anchor_config:
153        Option<Option<stripe_shared::SubscriptionsResourceBillingCycleAnchorConfig>>,
154    billing_mode: Option<stripe_shared::SubscriptionsResourceBillingMode>,
155    billing_thresholds: Option<Option<stripe_shared::SubscriptionBillingThresholds>>,
156    cancel_at: Option<Option<stripe_types::Timestamp>>,
157    cancel_at_period_end: Option<bool>,
158    canceled_at: Option<Option<stripe_types::Timestamp>>,
159    cancellation_details: Option<Option<stripe_shared::CancellationDetails>>,
160    collection_method: Option<stripe_shared::SubscriptionCollectionMethod>,
161    created: Option<stripe_types::Timestamp>,
162    currency: Option<stripe_types::Currency>,
163    customer: Option<stripe_types::Expandable<stripe_shared::Customer>>,
164    customer_account: Option<Option<String>>,
165    days_until_due: Option<Option<u32>>,
166    default_payment_method: Option<Option<stripe_types::Expandable<stripe_shared::PaymentMethod>>>,
167    default_source: Option<Option<stripe_types::Expandable<stripe_shared::PaymentSource>>>,
168    default_tax_rates: Option<Option<Vec<stripe_shared::TaxRate>>>,
169    description: Option<Option<String>>,
170    discounts: Option<Vec<stripe_types::Expandable<stripe_shared::Discount>>>,
171    ended_at: Option<Option<stripe_types::Timestamp>>,
172    id: Option<stripe_shared::SubscriptionId>,
173    invoice_settings: Option<stripe_shared::SubscriptionsResourceSubscriptionInvoiceSettings>,
174    items: Option<stripe_types::List<stripe_shared::SubscriptionItem>>,
175    latest_invoice: Option<Option<stripe_types::Expandable<stripe_shared::Invoice>>>,
176    livemode: Option<bool>,
177    metadata: Option<std::collections::HashMap<String, String>>,
178    next_pending_invoice_item_invoice: Option<Option<stripe_types::Timestamp>>,
179    on_behalf_of: Option<Option<stripe_types::Expandable<stripe_shared::Account>>>,
180    pause_collection: Option<Option<stripe_shared::SubscriptionsResourcePauseCollection>>,
181    payment_settings: Option<Option<stripe_shared::SubscriptionsResourcePaymentSettings>>,
182    pending_invoice_item_interval:
183        Option<Option<stripe_shared::SubscriptionPendingInvoiceItemInterval>>,
184    pending_setup_intent: Option<Option<stripe_types::Expandable<stripe_shared::SetupIntent>>>,
185    pending_update: Option<Option<stripe_shared::SubscriptionsResourcePendingUpdate>>,
186    schedule: Option<Option<stripe_types::Expandable<stripe_shared::SubscriptionSchedule>>>,
187    start_date: Option<stripe_types::Timestamp>,
188    status: Option<SubscriptionStatus>,
189    test_clock: Option<Option<stripe_types::Expandable<stripe_shared::TestHelpersTestClock>>>,
190    transfer_data: Option<Option<stripe_shared::SubscriptionTransferData>>,
191    trial_end: Option<Option<stripe_types::Timestamp>>,
192    trial_settings: Option<Option<stripe_shared::SubscriptionsTrialsResourceTrialSettings>>,
193    trial_start: Option<Option<stripe_types::Timestamp>>,
194}
195
196#[allow(
197    unused_variables,
198    irrefutable_let_patterns,
199    clippy::let_unit_value,
200    clippy::match_single_binding,
201    clippy::single_match
202)]
203const _: () = {
204    use miniserde::de::{Map, Visitor};
205    use miniserde::json::Value;
206    use miniserde::{Deserialize, Result, make_place};
207    use stripe_types::miniserde_helpers::FromValueOpt;
208    use stripe_types::{MapBuilder, ObjectDeser};
209
210    make_place!(Place);
211
212    impl Deserialize for Subscription {
213        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
214            Place::new(out)
215        }
216    }
217
218    struct Builder<'a> {
219        out: &'a mut Option<Subscription>,
220        builder: SubscriptionBuilder,
221    }
222
223    impl Visitor for Place<Subscription> {
224        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
225            Ok(Box::new(Builder {
226                out: &mut self.out,
227                builder: SubscriptionBuilder::deser_default(),
228            }))
229        }
230    }
231
232    impl MapBuilder for SubscriptionBuilder {
233        type Out = Subscription;
234        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
235            Ok(match k {
236                "application" => Deserialize::begin(&mut self.application),
237                "application_fee_percent" => Deserialize::begin(&mut self.application_fee_percent),
238                "automatic_tax" => Deserialize::begin(&mut self.automatic_tax),
239                "billing_cycle_anchor" => Deserialize::begin(&mut self.billing_cycle_anchor),
240                "billing_cycle_anchor_config" => {
241                    Deserialize::begin(&mut self.billing_cycle_anchor_config)
242                }
243                "billing_mode" => Deserialize::begin(&mut self.billing_mode),
244                "billing_thresholds" => Deserialize::begin(&mut self.billing_thresholds),
245                "cancel_at" => Deserialize::begin(&mut self.cancel_at),
246                "cancel_at_period_end" => Deserialize::begin(&mut self.cancel_at_period_end),
247                "canceled_at" => Deserialize::begin(&mut self.canceled_at),
248                "cancellation_details" => Deserialize::begin(&mut self.cancellation_details),
249                "collection_method" => Deserialize::begin(&mut self.collection_method),
250                "created" => Deserialize::begin(&mut self.created),
251                "currency" => Deserialize::begin(&mut self.currency),
252                "customer" => Deserialize::begin(&mut self.customer),
253                "customer_account" => Deserialize::begin(&mut self.customer_account),
254                "days_until_due" => Deserialize::begin(&mut self.days_until_due),
255                "default_payment_method" => Deserialize::begin(&mut self.default_payment_method),
256                "default_source" => Deserialize::begin(&mut self.default_source),
257                "default_tax_rates" => Deserialize::begin(&mut self.default_tax_rates),
258                "description" => Deserialize::begin(&mut self.description),
259                "discounts" => Deserialize::begin(&mut self.discounts),
260                "ended_at" => Deserialize::begin(&mut self.ended_at),
261                "id" => Deserialize::begin(&mut self.id),
262                "invoice_settings" => Deserialize::begin(&mut self.invoice_settings),
263                "items" => Deserialize::begin(&mut self.items),
264                "latest_invoice" => Deserialize::begin(&mut self.latest_invoice),
265                "livemode" => Deserialize::begin(&mut self.livemode),
266                "metadata" => Deserialize::begin(&mut self.metadata),
267                "next_pending_invoice_item_invoice" => {
268                    Deserialize::begin(&mut self.next_pending_invoice_item_invoice)
269                }
270                "on_behalf_of" => Deserialize::begin(&mut self.on_behalf_of),
271                "pause_collection" => Deserialize::begin(&mut self.pause_collection),
272                "payment_settings" => Deserialize::begin(&mut self.payment_settings),
273                "pending_invoice_item_interval" => {
274                    Deserialize::begin(&mut self.pending_invoice_item_interval)
275                }
276                "pending_setup_intent" => Deserialize::begin(&mut self.pending_setup_intent),
277                "pending_update" => Deserialize::begin(&mut self.pending_update),
278                "schedule" => Deserialize::begin(&mut self.schedule),
279                "start_date" => Deserialize::begin(&mut self.start_date),
280                "status" => Deserialize::begin(&mut self.status),
281                "test_clock" => Deserialize::begin(&mut self.test_clock),
282                "transfer_data" => Deserialize::begin(&mut self.transfer_data),
283                "trial_end" => Deserialize::begin(&mut self.trial_end),
284                "trial_settings" => Deserialize::begin(&mut self.trial_settings),
285                "trial_start" => Deserialize::begin(&mut self.trial_start),
286                _ => <dyn Visitor>::ignore(),
287            })
288        }
289
290        fn deser_default() -> Self {
291            Self {
292                application: Deserialize::default(),
293                application_fee_percent: Deserialize::default(),
294                automatic_tax: Deserialize::default(),
295                billing_cycle_anchor: Deserialize::default(),
296                billing_cycle_anchor_config: Deserialize::default(),
297                billing_mode: Deserialize::default(),
298                billing_thresholds: Deserialize::default(),
299                cancel_at: Deserialize::default(),
300                cancel_at_period_end: Deserialize::default(),
301                canceled_at: Deserialize::default(),
302                cancellation_details: Deserialize::default(),
303                collection_method: Deserialize::default(),
304                created: Deserialize::default(),
305                currency: Deserialize::default(),
306                customer: Deserialize::default(),
307                customer_account: Deserialize::default(),
308                days_until_due: Deserialize::default(),
309                default_payment_method: Deserialize::default(),
310                default_source: Deserialize::default(),
311                default_tax_rates: Deserialize::default(),
312                description: Deserialize::default(),
313                discounts: Deserialize::default(),
314                ended_at: Deserialize::default(),
315                id: Deserialize::default(),
316                invoice_settings: Deserialize::default(),
317                items: Deserialize::default(),
318                latest_invoice: Deserialize::default(),
319                livemode: Deserialize::default(),
320                metadata: Deserialize::default(),
321                next_pending_invoice_item_invoice: Deserialize::default(),
322                on_behalf_of: Deserialize::default(),
323                pause_collection: Deserialize::default(),
324                payment_settings: Deserialize::default(),
325                pending_invoice_item_interval: Deserialize::default(),
326                pending_setup_intent: Deserialize::default(),
327                pending_update: Deserialize::default(),
328                schedule: Deserialize::default(),
329                start_date: Deserialize::default(),
330                status: Deserialize::default(),
331                test_clock: Deserialize::default(),
332                transfer_data: Deserialize::default(),
333                trial_end: Deserialize::default(),
334                trial_settings: Deserialize::default(),
335                trial_start: Deserialize::default(),
336            }
337        }
338
339        fn take_out(&mut self) -> Option<Self::Out> {
340            let (
341                Some(application),
342                Some(application_fee_percent),
343                Some(automatic_tax),
344                Some(billing_cycle_anchor),
345                Some(billing_cycle_anchor_config),
346                Some(billing_mode),
347                Some(billing_thresholds),
348                Some(cancel_at),
349                Some(cancel_at_period_end),
350                Some(canceled_at),
351                Some(cancellation_details),
352                Some(collection_method),
353                Some(created),
354                Some(currency),
355                Some(customer),
356                Some(customer_account),
357                Some(days_until_due),
358                Some(default_payment_method),
359                Some(default_source),
360                Some(default_tax_rates),
361                Some(description),
362                Some(discounts),
363                Some(ended_at),
364                Some(id),
365                Some(invoice_settings),
366                Some(items),
367                Some(latest_invoice),
368                Some(livemode),
369                Some(metadata),
370                Some(next_pending_invoice_item_invoice),
371                Some(on_behalf_of),
372                Some(pause_collection),
373                Some(payment_settings),
374                Some(pending_invoice_item_interval),
375                Some(pending_setup_intent),
376                Some(pending_update),
377                Some(schedule),
378                Some(start_date),
379                Some(status),
380                Some(test_clock),
381                Some(transfer_data),
382                Some(trial_end),
383                Some(trial_settings),
384                Some(trial_start),
385            ) = (
386                self.application.take(),
387                self.application_fee_percent,
388                self.automatic_tax.take(),
389                self.billing_cycle_anchor,
390                self.billing_cycle_anchor_config,
391                self.billing_mode.take(),
392                self.billing_thresholds,
393                self.cancel_at,
394                self.cancel_at_period_end,
395                self.canceled_at,
396                self.cancellation_details.take(),
397                self.collection_method.take(),
398                self.created,
399                self.currency.take(),
400                self.customer.take(),
401                self.customer_account.take(),
402                self.days_until_due,
403                self.default_payment_method.take(),
404                self.default_source.take(),
405                self.default_tax_rates.take(),
406                self.description.take(),
407                self.discounts.take(),
408                self.ended_at,
409                self.id.take(),
410                self.invoice_settings.take(),
411                self.items.take(),
412                self.latest_invoice.take(),
413                self.livemode,
414                self.metadata.take(),
415                self.next_pending_invoice_item_invoice,
416                self.on_behalf_of.take(),
417                self.pause_collection.take(),
418                self.payment_settings.take(),
419                self.pending_invoice_item_interval.take(),
420                self.pending_setup_intent.take(),
421                self.pending_update.take(),
422                self.schedule.take(),
423                self.start_date,
424                self.status.take(),
425                self.test_clock.take(),
426                self.transfer_data.take(),
427                self.trial_end,
428                self.trial_settings.take(),
429                self.trial_start,
430            )
431            else {
432                return None;
433            };
434            Some(Self::Out {
435                application,
436                application_fee_percent,
437                automatic_tax,
438                billing_cycle_anchor,
439                billing_cycle_anchor_config,
440                billing_mode,
441                billing_thresholds,
442                cancel_at,
443                cancel_at_period_end,
444                canceled_at,
445                cancellation_details,
446                collection_method,
447                created,
448                currency,
449                customer,
450                customer_account,
451                days_until_due,
452                default_payment_method,
453                default_source,
454                default_tax_rates,
455                description,
456                discounts,
457                ended_at,
458                id,
459                invoice_settings,
460                items,
461                latest_invoice,
462                livemode,
463                metadata,
464                next_pending_invoice_item_invoice,
465                on_behalf_of,
466                pause_collection,
467                payment_settings,
468                pending_invoice_item_interval,
469                pending_setup_intent,
470                pending_update,
471                schedule,
472                start_date,
473                status,
474                test_clock,
475                transfer_data,
476                trial_end,
477                trial_settings,
478                trial_start,
479            })
480        }
481    }
482
483    impl Map for Builder<'_> {
484        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
485            self.builder.key(k)
486        }
487
488        fn finish(&mut self) -> Result<()> {
489            *self.out = self.builder.take_out();
490            Ok(())
491        }
492    }
493
494    impl ObjectDeser for Subscription {
495        type Builder = SubscriptionBuilder;
496    }
497
498    impl FromValueOpt for Subscription {
499        fn from_value(v: Value) -> Option<Self> {
500            let Value::Object(obj) = v else {
501                return None;
502            };
503            let mut b = SubscriptionBuilder::deser_default();
504            for (k, v) in obj {
505                match k.as_str() {
506                    "application" => b.application = FromValueOpt::from_value(v),
507                    "application_fee_percent" => {
508                        b.application_fee_percent = FromValueOpt::from_value(v)
509                    }
510                    "automatic_tax" => b.automatic_tax = FromValueOpt::from_value(v),
511                    "billing_cycle_anchor" => b.billing_cycle_anchor = FromValueOpt::from_value(v),
512                    "billing_cycle_anchor_config" => {
513                        b.billing_cycle_anchor_config = FromValueOpt::from_value(v)
514                    }
515                    "billing_mode" => b.billing_mode = FromValueOpt::from_value(v),
516                    "billing_thresholds" => b.billing_thresholds = FromValueOpt::from_value(v),
517                    "cancel_at" => b.cancel_at = FromValueOpt::from_value(v),
518                    "cancel_at_period_end" => b.cancel_at_period_end = FromValueOpt::from_value(v),
519                    "canceled_at" => b.canceled_at = FromValueOpt::from_value(v),
520                    "cancellation_details" => b.cancellation_details = FromValueOpt::from_value(v),
521                    "collection_method" => b.collection_method = FromValueOpt::from_value(v),
522                    "created" => b.created = FromValueOpt::from_value(v),
523                    "currency" => b.currency = FromValueOpt::from_value(v),
524                    "customer" => b.customer = FromValueOpt::from_value(v),
525                    "customer_account" => b.customer_account = FromValueOpt::from_value(v),
526                    "days_until_due" => b.days_until_due = FromValueOpt::from_value(v),
527                    "default_payment_method" => {
528                        b.default_payment_method = FromValueOpt::from_value(v)
529                    }
530                    "default_source" => b.default_source = FromValueOpt::from_value(v),
531                    "default_tax_rates" => b.default_tax_rates = FromValueOpt::from_value(v),
532                    "description" => b.description = FromValueOpt::from_value(v),
533                    "discounts" => b.discounts = FromValueOpt::from_value(v),
534                    "ended_at" => b.ended_at = FromValueOpt::from_value(v),
535                    "id" => b.id = FromValueOpt::from_value(v),
536                    "invoice_settings" => b.invoice_settings = FromValueOpt::from_value(v),
537                    "items" => b.items = FromValueOpt::from_value(v),
538                    "latest_invoice" => b.latest_invoice = FromValueOpt::from_value(v),
539                    "livemode" => b.livemode = FromValueOpt::from_value(v),
540                    "metadata" => b.metadata = FromValueOpt::from_value(v),
541                    "next_pending_invoice_item_invoice" => {
542                        b.next_pending_invoice_item_invoice = FromValueOpt::from_value(v)
543                    }
544                    "on_behalf_of" => b.on_behalf_of = FromValueOpt::from_value(v),
545                    "pause_collection" => b.pause_collection = FromValueOpt::from_value(v),
546                    "payment_settings" => b.payment_settings = FromValueOpt::from_value(v),
547                    "pending_invoice_item_interval" => {
548                        b.pending_invoice_item_interval = FromValueOpt::from_value(v)
549                    }
550                    "pending_setup_intent" => b.pending_setup_intent = FromValueOpt::from_value(v),
551                    "pending_update" => b.pending_update = FromValueOpt::from_value(v),
552                    "schedule" => b.schedule = FromValueOpt::from_value(v),
553                    "start_date" => b.start_date = FromValueOpt::from_value(v),
554                    "status" => b.status = FromValueOpt::from_value(v),
555                    "test_clock" => b.test_clock = FromValueOpt::from_value(v),
556                    "transfer_data" => b.transfer_data = FromValueOpt::from_value(v),
557                    "trial_end" => b.trial_end = FromValueOpt::from_value(v),
558                    "trial_settings" => b.trial_settings = FromValueOpt::from_value(v),
559                    "trial_start" => b.trial_start = FromValueOpt::from_value(v),
560                    _ => {}
561                }
562            }
563            b.take_out()
564        }
565    }
566};
567#[cfg(feature = "serialize")]
568impl serde::Serialize for Subscription {
569    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
570        use serde::ser::SerializeStruct;
571        let mut s = s.serialize_struct("Subscription", 45)?;
572        s.serialize_field("application", &self.application)?;
573        s.serialize_field("application_fee_percent", &self.application_fee_percent)?;
574        s.serialize_field("automatic_tax", &self.automatic_tax)?;
575        s.serialize_field("billing_cycle_anchor", &self.billing_cycle_anchor)?;
576        s.serialize_field("billing_cycle_anchor_config", &self.billing_cycle_anchor_config)?;
577        s.serialize_field("billing_mode", &self.billing_mode)?;
578        s.serialize_field("billing_thresholds", &self.billing_thresholds)?;
579        s.serialize_field("cancel_at", &self.cancel_at)?;
580        s.serialize_field("cancel_at_period_end", &self.cancel_at_period_end)?;
581        s.serialize_field("canceled_at", &self.canceled_at)?;
582        s.serialize_field("cancellation_details", &self.cancellation_details)?;
583        s.serialize_field("collection_method", &self.collection_method)?;
584        s.serialize_field("created", &self.created)?;
585        s.serialize_field("currency", &self.currency)?;
586        s.serialize_field("customer", &self.customer)?;
587        s.serialize_field("customer_account", &self.customer_account)?;
588        s.serialize_field("days_until_due", &self.days_until_due)?;
589        s.serialize_field("default_payment_method", &self.default_payment_method)?;
590        s.serialize_field("default_source", &self.default_source)?;
591        s.serialize_field("default_tax_rates", &self.default_tax_rates)?;
592        s.serialize_field("description", &self.description)?;
593        s.serialize_field("discounts", &self.discounts)?;
594        s.serialize_field("ended_at", &self.ended_at)?;
595        s.serialize_field("id", &self.id)?;
596        s.serialize_field("invoice_settings", &self.invoice_settings)?;
597        s.serialize_field("items", &self.items)?;
598        s.serialize_field("latest_invoice", &self.latest_invoice)?;
599        s.serialize_field("livemode", &self.livemode)?;
600        s.serialize_field("metadata", &self.metadata)?;
601        s.serialize_field(
602            "next_pending_invoice_item_invoice",
603            &self.next_pending_invoice_item_invoice,
604        )?;
605        s.serialize_field("on_behalf_of", &self.on_behalf_of)?;
606        s.serialize_field("pause_collection", &self.pause_collection)?;
607        s.serialize_field("payment_settings", &self.payment_settings)?;
608        s.serialize_field("pending_invoice_item_interval", &self.pending_invoice_item_interval)?;
609        s.serialize_field("pending_setup_intent", &self.pending_setup_intent)?;
610        s.serialize_field("pending_update", &self.pending_update)?;
611        s.serialize_field("schedule", &self.schedule)?;
612        s.serialize_field("start_date", &self.start_date)?;
613        s.serialize_field("status", &self.status)?;
614        s.serialize_field("test_clock", &self.test_clock)?;
615        s.serialize_field("transfer_data", &self.transfer_data)?;
616        s.serialize_field("trial_end", &self.trial_end)?;
617        s.serialize_field("trial_settings", &self.trial_settings)?;
618        s.serialize_field("trial_start", &self.trial_start)?;
619
620        s.serialize_field("object", "subscription")?;
621        s.end()
622    }
623}
624/// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, `unpaid`, or `paused`.
625///
626///
627/// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails.
628/// A subscription in this status can only have metadata and default_source updated.
629/// Once the first invoice is paid, the subscription moves into an `active` status.
630/// If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`.
631/// This is a terminal status, the open invoice will be voided and no further invoices will be generated.
632///
633///
634/// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over.
635///
636///
637/// A subscription can only enter a `paused` status [when a trial ends without a payment method](https://docs.stripe.com/billing/subscriptions/trials#create-free-trials-without-payment).
638/// A `paused` subscription doesn't generate invoices and can be resumed after your customer adds their payment method.
639/// The `paused` status is different from [pausing collection](https://docs.stripe.com/billing/subscriptions/pause-payment), which still generates invoices and leaves the subscription's status unchanged.
640///
641///
642/// If subscription `collection_method=charge_automatically`, it becomes `past_due` when payment is required but cannot be paid (due to failed payment or awaiting additional user actions).
643/// Once Stripe has exhausted all payment retry attempts, the subscription will become `canceled` or `unpaid` (depending on your subscriptions settings).
644///
645///
646/// If subscription `collection_method=send_invoice` it becomes `past_due` when its invoice is not paid by the due date, and `canceled` or `unpaid` if it is still not paid by an additional deadline after that.
647/// Note that when a subscription has a status of `unpaid`, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed).
648/// After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices.
649#[derive(Clone, Eq, PartialEq)]
650#[non_exhaustive]
651pub enum SubscriptionStatus {
652    Active,
653    Canceled,
654    Incomplete,
655    IncompleteExpired,
656    PastDue,
657    Paused,
658    Trialing,
659    Unpaid,
660    /// An unrecognized value from Stripe. Should not be used as a request parameter.
661    Unknown(String),
662}
663impl SubscriptionStatus {
664    pub fn as_str(&self) -> &str {
665        use SubscriptionStatus::*;
666        match self {
667            Active => "active",
668            Canceled => "canceled",
669            Incomplete => "incomplete",
670            IncompleteExpired => "incomplete_expired",
671            PastDue => "past_due",
672            Paused => "paused",
673            Trialing => "trialing",
674            Unpaid => "unpaid",
675            Unknown(v) => v,
676        }
677    }
678}
679
680impl std::str::FromStr for SubscriptionStatus {
681    type Err = std::convert::Infallible;
682    fn from_str(s: &str) -> Result<Self, Self::Err> {
683        use SubscriptionStatus::*;
684        match s {
685            "active" => Ok(Active),
686            "canceled" => Ok(Canceled),
687            "incomplete" => Ok(Incomplete),
688            "incomplete_expired" => Ok(IncompleteExpired),
689            "past_due" => Ok(PastDue),
690            "paused" => Ok(Paused),
691            "trialing" => Ok(Trialing),
692            "unpaid" => Ok(Unpaid),
693            v => {
694                tracing::warn!("Unknown value '{}' for enum '{}'", v, "SubscriptionStatus");
695                Ok(Unknown(v.to_owned()))
696            }
697        }
698    }
699}
700impl std::fmt::Display for SubscriptionStatus {
701    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
702        f.write_str(self.as_str())
703    }
704}
705
706impl std::fmt::Debug for SubscriptionStatus {
707    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
708        f.write_str(self.as_str())
709    }
710}
711#[cfg(feature = "serialize")]
712impl serde::Serialize for SubscriptionStatus {
713    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
714    where
715        S: serde::Serializer,
716    {
717        serializer.serialize_str(self.as_str())
718    }
719}
720impl miniserde::Deserialize for SubscriptionStatus {
721    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
722        crate::Place::new(out)
723    }
724}
725
726impl miniserde::de::Visitor for crate::Place<SubscriptionStatus> {
727    fn string(&mut self, s: &str) -> miniserde::Result<()> {
728        use std::str::FromStr;
729        self.out = Some(SubscriptionStatus::from_str(s).expect("infallible"));
730        Ok(())
731    }
732}
733
734stripe_types::impl_from_val_with_from_str!(SubscriptionStatus);
735#[cfg(feature = "deserialize")]
736impl<'de> serde::Deserialize<'de> for SubscriptionStatus {
737    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
738        use std::str::FromStr;
739        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
740        Ok(Self::from_str(&s).expect("infallible"))
741    }
742}
743impl stripe_types::Object for Subscription {
744    type Id = stripe_shared::SubscriptionId;
745    fn id(&self) -> &Self::Id {
746        &self.id
747    }
748
749    fn into_id(self) -> Self::Id {
750        self.id
751    }
752}
753stripe_types::def_id!(SubscriptionId);
754#[derive(Clone, Eq, PartialEq)]
755#[non_exhaustive]
756pub enum SubscriptionCollectionMethod {
757    ChargeAutomatically,
758    SendInvoice,
759    /// An unrecognized value from Stripe. Should not be used as a request parameter.
760    Unknown(String),
761}
762impl SubscriptionCollectionMethod {
763    pub fn as_str(&self) -> &str {
764        use SubscriptionCollectionMethod::*;
765        match self {
766            ChargeAutomatically => "charge_automatically",
767            SendInvoice => "send_invoice",
768            Unknown(v) => v,
769        }
770    }
771}
772
773impl std::str::FromStr for SubscriptionCollectionMethod {
774    type Err = std::convert::Infallible;
775    fn from_str(s: &str) -> Result<Self, Self::Err> {
776        use SubscriptionCollectionMethod::*;
777        match s {
778            "charge_automatically" => Ok(ChargeAutomatically),
779            "send_invoice" => Ok(SendInvoice),
780            v => {
781                tracing::warn!(
782                    "Unknown value '{}' for enum '{}'",
783                    v,
784                    "SubscriptionCollectionMethod"
785                );
786                Ok(Unknown(v.to_owned()))
787            }
788        }
789    }
790}
791impl std::fmt::Display for SubscriptionCollectionMethod {
792    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
793        f.write_str(self.as_str())
794    }
795}
796
797impl std::fmt::Debug for SubscriptionCollectionMethod {
798    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
799        f.write_str(self.as_str())
800    }
801}
802impl serde::Serialize for SubscriptionCollectionMethod {
803    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
804    where
805        S: serde::Serializer,
806    {
807        serializer.serialize_str(self.as_str())
808    }
809}
810impl miniserde::Deserialize for SubscriptionCollectionMethod {
811    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
812        crate::Place::new(out)
813    }
814}
815
816impl miniserde::de::Visitor for crate::Place<SubscriptionCollectionMethod> {
817    fn string(&mut self, s: &str) -> miniserde::Result<()> {
818        use std::str::FromStr;
819        self.out = Some(SubscriptionCollectionMethod::from_str(s).expect("infallible"));
820        Ok(())
821    }
822}
823
824stripe_types::impl_from_val_with_from_str!(SubscriptionCollectionMethod);
825#[cfg(feature = "deserialize")]
826impl<'de> serde::Deserialize<'de> for SubscriptionCollectionMethod {
827    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
828        use std::str::FromStr;
829        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
830        Ok(Self::from_str(&s).expect("infallible"))
831    }
832}