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