stripe_shared/
subscription.rs

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