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::{make_place, Deserialize, Result};
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
283                _ => <dyn Visitor>::ignore(),
284            })
285        }
286
287        fn deser_default() -> Self {
288            Self {
289                application: Deserialize::default(),
290                application_fee_percent: Deserialize::default(),
291                automatic_tax: Deserialize::default(),
292                billing_cycle_anchor: Deserialize::default(),
293                billing_cycle_anchor_config: Deserialize::default(),
294                billing_mode: Deserialize::default(),
295                billing_thresholds: Deserialize::default(),
296                cancel_at: Deserialize::default(),
297                cancel_at_period_end: Deserialize::default(),
298                canceled_at: Deserialize::default(),
299                cancellation_details: Deserialize::default(),
300                collection_method: Deserialize::default(),
301                created: Deserialize::default(),
302                currency: Deserialize::default(),
303                customer: Deserialize::default(),
304                days_until_due: Deserialize::default(),
305                default_payment_method: Deserialize::default(),
306                default_source: Deserialize::default(),
307                default_tax_rates: Deserialize::default(),
308                description: Deserialize::default(),
309                discounts: Deserialize::default(),
310                ended_at: Deserialize::default(),
311                id: Deserialize::default(),
312                invoice_settings: Deserialize::default(),
313                items: Deserialize::default(),
314                latest_invoice: Deserialize::default(),
315                livemode: Deserialize::default(),
316                metadata: Deserialize::default(),
317                next_pending_invoice_item_invoice: Deserialize::default(),
318                on_behalf_of: Deserialize::default(),
319                pause_collection: Deserialize::default(),
320                payment_settings: Deserialize::default(),
321                pending_invoice_item_interval: Deserialize::default(),
322                pending_setup_intent: Deserialize::default(),
323                pending_update: Deserialize::default(),
324                schedule: Deserialize::default(),
325                start_date: Deserialize::default(),
326                status: Deserialize::default(),
327                test_clock: Deserialize::default(),
328                transfer_data: Deserialize::default(),
329                trial_end: Deserialize::default(),
330                trial_settings: Deserialize::default(),
331                trial_start: Deserialize::default(),
332            }
333        }
334
335        fn take_out(&mut self) -> Option<Self::Out> {
336            let (
337                Some(application),
338                Some(application_fee_percent),
339                Some(automatic_tax),
340                Some(billing_cycle_anchor),
341                Some(billing_cycle_anchor_config),
342                Some(billing_mode),
343                Some(billing_thresholds),
344                Some(cancel_at),
345                Some(cancel_at_period_end),
346                Some(canceled_at),
347                Some(cancellation_details),
348                Some(collection_method),
349                Some(created),
350                Some(currency),
351                Some(customer),
352                Some(days_until_due),
353                Some(default_payment_method),
354                Some(default_source),
355                Some(default_tax_rates),
356                Some(description),
357                Some(discounts),
358                Some(ended_at),
359                Some(id),
360                Some(invoice_settings),
361                Some(items),
362                Some(latest_invoice),
363                Some(livemode),
364                Some(metadata),
365                Some(next_pending_invoice_item_invoice),
366                Some(on_behalf_of),
367                Some(pause_collection),
368                Some(payment_settings),
369                Some(pending_invoice_item_interval),
370                Some(pending_setup_intent),
371                Some(pending_update),
372                Some(schedule),
373                Some(start_date),
374                Some(status),
375                Some(test_clock),
376                Some(transfer_data),
377                Some(trial_end),
378                Some(trial_settings),
379                Some(trial_start),
380            ) = (
381                self.application.take(),
382                self.application_fee_percent,
383                self.automatic_tax.take(),
384                self.billing_cycle_anchor,
385                self.billing_cycle_anchor_config,
386                self.billing_mode,
387                self.billing_thresholds,
388                self.cancel_at,
389                self.cancel_at_period_end,
390                self.canceled_at,
391                self.cancellation_details.take(),
392                self.collection_method,
393                self.created,
394                self.currency.take(),
395                self.customer.take(),
396                self.days_until_due,
397                self.default_payment_method.take(),
398                self.default_source.take(),
399                self.default_tax_rates.take(),
400                self.description.take(),
401                self.discounts.take(),
402                self.ended_at,
403                self.id.take(),
404                self.invoice_settings.take(),
405                self.items.take(),
406                self.latest_invoice.take(),
407                self.livemode,
408                self.metadata.take(),
409                self.next_pending_invoice_item_invoice,
410                self.on_behalf_of.take(),
411                self.pause_collection,
412                self.payment_settings.take(),
413                self.pending_invoice_item_interval,
414                self.pending_setup_intent.take(),
415                self.pending_update.take(),
416                self.schedule.take(),
417                self.start_date,
418                self.status,
419                self.test_clock.take(),
420                self.transfer_data.take(),
421                self.trial_end,
422                self.trial_settings,
423                self.trial_start,
424            )
425            else {
426                return None;
427            };
428            Some(Self::Out {
429                application,
430                application_fee_percent,
431                automatic_tax,
432                billing_cycle_anchor,
433                billing_cycle_anchor_config,
434                billing_mode,
435                billing_thresholds,
436                cancel_at,
437                cancel_at_period_end,
438                canceled_at,
439                cancellation_details,
440                collection_method,
441                created,
442                currency,
443                customer,
444                days_until_due,
445                default_payment_method,
446                default_source,
447                default_tax_rates,
448                description,
449                discounts,
450                ended_at,
451                id,
452                invoice_settings,
453                items,
454                latest_invoice,
455                livemode,
456                metadata,
457                next_pending_invoice_item_invoice,
458                on_behalf_of,
459                pause_collection,
460                payment_settings,
461                pending_invoice_item_interval,
462                pending_setup_intent,
463                pending_update,
464                schedule,
465                start_date,
466                status,
467                test_clock,
468                transfer_data,
469                trial_end,
470                trial_settings,
471                trial_start,
472            })
473        }
474    }
475
476    impl Map for Builder<'_> {
477        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
478            self.builder.key(k)
479        }
480
481        fn finish(&mut self) -> Result<()> {
482            *self.out = self.builder.take_out();
483            Ok(())
484        }
485    }
486
487    impl ObjectDeser for Subscription {
488        type Builder = SubscriptionBuilder;
489    }
490
491    impl FromValueOpt for Subscription {
492        fn from_value(v: Value) -> Option<Self> {
493            let Value::Object(obj) = v else {
494                return None;
495            };
496            let mut b = SubscriptionBuilder::deser_default();
497            for (k, v) in obj {
498                match k.as_str() {
499                    "application" => b.application = FromValueOpt::from_value(v),
500                    "application_fee_percent" => {
501                        b.application_fee_percent = FromValueOpt::from_value(v)
502                    }
503                    "automatic_tax" => b.automatic_tax = FromValueOpt::from_value(v),
504                    "billing_cycle_anchor" => b.billing_cycle_anchor = FromValueOpt::from_value(v),
505                    "billing_cycle_anchor_config" => {
506                        b.billing_cycle_anchor_config = FromValueOpt::from_value(v)
507                    }
508                    "billing_mode" => b.billing_mode = FromValueOpt::from_value(v),
509                    "billing_thresholds" => b.billing_thresholds = FromValueOpt::from_value(v),
510                    "cancel_at" => b.cancel_at = FromValueOpt::from_value(v),
511                    "cancel_at_period_end" => b.cancel_at_period_end = FromValueOpt::from_value(v),
512                    "canceled_at" => b.canceled_at = FromValueOpt::from_value(v),
513                    "cancellation_details" => b.cancellation_details = FromValueOpt::from_value(v),
514                    "collection_method" => b.collection_method = FromValueOpt::from_value(v),
515                    "created" => b.created = FromValueOpt::from_value(v),
516                    "currency" => b.currency = FromValueOpt::from_value(v),
517                    "customer" => b.customer = FromValueOpt::from_value(v),
518                    "days_until_due" => b.days_until_due = FromValueOpt::from_value(v),
519                    "default_payment_method" => {
520                        b.default_payment_method = FromValueOpt::from_value(v)
521                    }
522                    "default_source" => b.default_source = FromValueOpt::from_value(v),
523                    "default_tax_rates" => b.default_tax_rates = FromValueOpt::from_value(v),
524                    "description" => b.description = FromValueOpt::from_value(v),
525                    "discounts" => b.discounts = FromValueOpt::from_value(v),
526                    "ended_at" => b.ended_at = FromValueOpt::from_value(v),
527                    "id" => b.id = FromValueOpt::from_value(v),
528                    "invoice_settings" => b.invoice_settings = FromValueOpt::from_value(v),
529                    "items" => b.items = FromValueOpt::from_value(v),
530                    "latest_invoice" => b.latest_invoice = FromValueOpt::from_value(v),
531                    "livemode" => b.livemode = FromValueOpt::from_value(v),
532                    "metadata" => b.metadata = FromValueOpt::from_value(v),
533                    "next_pending_invoice_item_invoice" => {
534                        b.next_pending_invoice_item_invoice = FromValueOpt::from_value(v)
535                    }
536                    "on_behalf_of" => b.on_behalf_of = FromValueOpt::from_value(v),
537                    "pause_collection" => b.pause_collection = FromValueOpt::from_value(v),
538                    "payment_settings" => b.payment_settings = FromValueOpt::from_value(v),
539                    "pending_invoice_item_interval" => {
540                        b.pending_invoice_item_interval = FromValueOpt::from_value(v)
541                    }
542                    "pending_setup_intent" => b.pending_setup_intent = FromValueOpt::from_value(v),
543                    "pending_update" => b.pending_update = FromValueOpt::from_value(v),
544                    "schedule" => b.schedule = FromValueOpt::from_value(v),
545                    "start_date" => b.start_date = FromValueOpt::from_value(v),
546                    "status" => b.status = FromValueOpt::from_value(v),
547                    "test_clock" => b.test_clock = FromValueOpt::from_value(v),
548                    "transfer_data" => b.transfer_data = FromValueOpt::from_value(v),
549                    "trial_end" => b.trial_end = FromValueOpt::from_value(v),
550                    "trial_settings" => b.trial_settings = FromValueOpt::from_value(v),
551                    "trial_start" => b.trial_start = FromValueOpt::from_value(v),
552
553                    _ => {}
554                }
555            }
556            b.take_out()
557        }
558    }
559};
560#[cfg(feature = "serialize")]
561impl serde::Serialize for Subscription {
562    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
563        use serde::ser::SerializeStruct;
564        let mut s = s.serialize_struct("Subscription", 44)?;
565        s.serialize_field("application", &self.application)?;
566        s.serialize_field("application_fee_percent", &self.application_fee_percent)?;
567        s.serialize_field("automatic_tax", &self.automatic_tax)?;
568        s.serialize_field("billing_cycle_anchor", &self.billing_cycle_anchor)?;
569        s.serialize_field("billing_cycle_anchor_config", &self.billing_cycle_anchor_config)?;
570        s.serialize_field("billing_mode", &self.billing_mode)?;
571        s.serialize_field("billing_thresholds", &self.billing_thresholds)?;
572        s.serialize_field("cancel_at", &self.cancel_at)?;
573        s.serialize_field("cancel_at_period_end", &self.cancel_at_period_end)?;
574        s.serialize_field("canceled_at", &self.canceled_at)?;
575        s.serialize_field("cancellation_details", &self.cancellation_details)?;
576        s.serialize_field("collection_method", &self.collection_method)?;
577        s.serialize_field("created", &self.created)?;
578        s.serialize_field("currency", &self.currency)?;
579        s.serialize_field("customer", &self.customer)?;
580        s.serialize_field("days_until_due", &self.days_until_due)?;
581        s.serialize_field("default_payment_method", &self.default_payment_method)?;
582        s.serialize_field("default_source", &self.default_source)?;
583        s.serialize_field("default_tax_rates", &self.default_tax_rates)?;
584        s.serialize_field("description", &self.description)?;
585        s.serialize_field("discounts", &self.discounts)?;
586        s.serialize_field("ended_at", &self.ended_at)?;
587        s.serialize_field("id", &self.id)?;
588        s.serialize_field("invoice_settings", &self.invoice_settings)?;
589        s.serialize_field("items", &self.items)?;
590        s.serialize_field("latest_invoice", &self.latest_invoice)?;
591        s.serialize_field("livemode", &self.livemode)?;
592        s.serialize_field("metadata", &self.metadata)?;
593        s.serialize_field(
594            "next_pending_invoice_item_invoice",
595            &self.next_pending_invoice_item_invoice,
596        )?;
597        s.serialize_field("on_behalf_of", &self.on_behalf_of)?;
598        s.serialize_field("pause_collection", &self.pause_collection)?;
599        s.serialize_field("payment_settings", &self.payment_settings)?;
600        s.serialize_field("pending_invoice_item_interval", &self.pending_invoice_item_interval)?;
601        s.serialize_field("pending_setup_intent", &self.pending_setup_intent)?;
602        s.serialize_field("pending_update", &self.pending_update)?;
603        s.serialize_field("schedule", &self.schedule)?;
604        s.serialize_field("start_date", &self.start_date)?;
605        s.serialize_field("status", &self.status)?;
606        s.serialize_field("test_clock", &self.test_clock)?;
607        s.serialize_field("transfer_data", &self.transfer_data)?;
608        s.serialize_field("trial_end", &self.trial_end)?;
609        s.serialize_field("trial_settings", &self.trial_settings)?;
610        s.serialize_field("trial_start", &self.trial_start)?;
611
612        s.serialize_field("object", "subscription")?;
613        s.end()
614    }
615}
616/// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, `unpaid`, or `paused`.
617///
618///
619/// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails.
620/// A subscription in this status can only have metadata and default_source updated.
621/// Once the first invoice is paid, the subscription moves into an `active` status.
622/// If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`.
623/// This is a terminal status, the open invoice will be voided and no further invoices will be generated.
624///
625///
626/// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over.
627///
628///
629/// 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).
630/// A `paused` subscription doesn't generate invoices and can be resumed after your customer adds their payment method.
631/// 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.
632///
633///
634/// 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).
635/// Once Stripe has exhausted all payment retry attempts, the subscription will become `canceled` or `unpaid` (depending on your subscriptions settings).
636///
637///
638/// 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.
639/// 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).
640/// After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices.
641#[derive(Copy, Clone, Eq, PartialEq)]
642pub enum SubscriptionStatus {
643    Active,
644    Canceled,
645    Incomplete,
646    IncompleteExpired,
647    PastDue,
648    Paused,
649    Trialing,
650    Unpaid,
651}
652impl SubscriptionStatus {
653    pub fn as_str(self) -> &'static str {
654        use SubscriptionStatus::*;
655        match self {
656            Active => "active",
657            Canceled => "canceled",
658            Incomplete => "incomplete",
659            IncompleteExpired => "incomplete_expired",
660            PastDue => "past_due",
661            Paused => "paused",
662            Trialing => "trialing",
663            Unpaid => "unpaid",
664        }
665    }
666}
667
668impl std::str::FromStr for SubscriptionStatus {
669    type Err = stripe_types::StripeParseError;
670    fn from_str(s: &str) -> Result<Self, Self::Err> {
671        use SubscriptionStatus::*;
672        match s {
673            "active" => Ok(Active),
674            "canceled" => Ok(Canceled),
675            "incomplete" => Ok(Incomplete),
676            "incomplete_expired" => Ok(IncompleteExpired),
677            "past_due" => Ok(PastDue),
678            "paused" => Ok(Paused),
679            "trialing" => Ok(Trialing),
680            "unpaid" => Ok(Unpaid),
681            _ => Err(stripe_types::StripeParseError),
682        }
683    }
684}
685impl std::fmt::Display for SubscriptionStatus {
686    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
687        f.write_str(self.as_str())
688    }
689}
690
691impl std::fmt::Debug for SubscriptionStatus {
692    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
693        f.write_str(self.as_str())
694    }
695}
696#[cfg(feature = "serialize")]
697impl serde::Serialize for SubscriptionStatus {
698    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
699    where
700        S: serde::Serializer,
701    {
702        serializer.serialize_str(self.as_str())
703    }
704}
705impl miniserde::Deserialize for SubscriptionStatus {
706    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
707        crate::Place::new(out)
708    }
709}
710
711impl miniserde::de::Visitor for crate::Place<SubscriptionStatus> {
712    fn string(&mut self, s: &str) -> miniserde::Result<()> {
713        use std::str::FromStr;
714        self.out = Some(SubscriptionStatus::from_str(s).map_err(|_| miniserde::Error)?);
715        Ok(())
716    }
717}
718
719stripe_types::impl_from_val_with_from_str!(SubscriptionStatus);
720#[cfg(feature = "deserialize")]
721impl<'de> serde::Deserialize<'de> for SubscriptionStatus {
722    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
723        use std::str::FromStr;
724        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
725        Self::from_str(&s)
726            .map_err(|_| serde::de::Error::custom("Unknown value for SubscriptionStatus"))
727    }
728}
729impl stripe_types::Object for Subscription {
730    type Id = stripe_shared::SubscriptionId;
731    fn id(&self) -> &Self::Id {
732        &self.id
733    }
734
735    fn into_id(self) -> Self::Id {
736        self.id
737    }
738}
739stripe_types::def_id!(SubscriptionId);
740#[derive(Copy, Clone, Eq, PartialEq)]
741pub enum SubscriptionCollectionMethod {
742    ChargeAutomatically,
743    SendInvoice,
744}
745impl SubscriptionCollectionMethod {
746    pub fn as_str(self) -> &'static str {
747        use SubscriptionCollectionMethod::*;
748        match self {
749            ChargeAutomatically => "charge_automatically",
750            SendInvoice => "send_invoice",
751        }
752    }
753}
754
755impl std::str::FromStr for SubscriptionCollectionMethod {
756    type Err = stripe_types::StripeParseError;
757    fn from_str(s: &str) -> Result<Self, Self::Err> {
758        use SubscriptionCollectionMethod::*;
759        match s {
760            "charge_automatically" => Ok(ChargeAutomatically),
761            "send_invoice" => Ok(SendInvoice),
762            _ => Err(stripe_types::StripeParseError),
763        }
764    }
765}
766impl std::fmt::Display for SubscriptionCollectionMethod {
767    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
768        f.write_str(self.as_str())
769    }
770}
771
772impl std::fmt::Debug for SubscriptionCollectionMethod {
773    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
774        f.write_str(self.as_str())
775    }
776}
777impl serde::Serialize for SubscriptionCollectionMethod {
778    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
779    where
780        S: serde::Serializer,
781    {
782        serializer.serialize_str(self.as_str())
783    }
784}
785impl miniserde::Deserialize for SubscriptionCollectionMethod {
786    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
787        crate::Place::new(out)
788    }
789}
790
791impl miniserde::de::Visitor for crate::Place<SubscriptionCollectionMethod> {
792    fn string(&mut self, s: &str) -> miniserde::Result<()> {
793        use std::str::FromStr;
794        self.out = Some(SubscriptionCollectionMethod::from_str(s).map_err(|_| miniserde::Error)?);
795        Ok(())
796    }
797}
798
799stripe_types::impl_from_val_with_from_str!(SubscriptionCollectionMethod);
800#[cfg(feature = "deserialize")]
801impl<'de> serde::Deserialize<'de> for SubscriptionCollectionMethod {
802    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
803        use std::str::FromStr;
804        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
805        Self::from_str(&s)
806            .map_err(|_| serde::de::Error::custom("Unknown value for SubscriptionCollectionMethod"))
807    }
808}