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