Skip to main content

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