stripe_shared/
plan.rs

1/// You can now model subscriptions more flexibly using the [Prices API](https://stripe.com/docs/api#prices).
2/// It replaces the Plans API and is backwards compatible to simplify your migration.
3///
4/// Plans define the base price, currency, and billing cycle for recurring purchases of products.
5/// [Products](https://stripe.com/docs/api#products) help you track inventory or provisioning, and plans help you track pricing.
6/// Different physical goods or levels of service should be represented by products, and pricing options should be represented by plans.
7/// This approach lets you change prices without having to change your provisioning scheme.
8///
9/// For example, you might have a single "gold" product that has plans for $10/month, $100/year, €9/month, and €90/year.
10///
11/// Related guides: [Set up a subscription](https://stripe.com/docs/billing/subscriptions/set-up-subscription) and more about [products and prices](https://stripe.com/docs/products-prices/overview).
12///
13/// For more details see <<https://stripe.com/docs/api/plans/object>>.
14#[derive(Clone, Debug)]
15#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
16pub struct Plan {
17    /// Whether the plan can be used for new purchases.
18    pub active: bool,
19    /// The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible.
20    /// Only set if `billing_scheme=per_unit`.
21    pub amount: Option<i64>,
22    /// The unit amount in cents (or local equivalent) to be charged, represented as a decimal string with at most 12 decimal places.
23    /// Only set if `billing_scheme=per_unit`.
24    pub amount_decimal: Option<String>,
25    /// Describes how to compute the price per period.
26    /// Either `per_unit` or `tiered`.
27    /// `per_unit` indicates that the fixed amount (specified in `amount`) will be charged per unit in `quantity` (for plans with `usage_type=licensed`), or per unit of total usage (for plans with `usage_type=metered`).
28    /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes.
29    pub billing_scheme: stripe_shared::PlanBillingScheme,
30    /// Time at which the object was created. Measured in seconds since the Unix epoch.
31    pub created: stripe_types::Timestamp,
32    /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
33    /// Must be a [supported currency](https://stripe.com/docs/currencies).
34    pub currency: stripe_types::Currency,
35    /// Unique identifier for the object.
36    pub id: stripe_shared::PlanId,
37    /// The frequency at which a subscription is billed. One of `day`, `week`, `month` or `year`.
38    pub interval: stripe_shared::PlanInterval,
39    /// The number of intervals (specified in the `interval` attribute) between subscription billings.
40    /// For example, `interval=month` and `interval_count=3` bills every 3 months.
41    pub interval_count: u64,
42    /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
43    pub livemode: bool,
44    /// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object.
45    /// This can be useful for storing additional information about the object in a structured format.
46    pub metadata: Option<std::collections::HashMap<String, String>>,
47    /// The meter tracking the usage of a metered price
48    pub meter: Option<String>,
49    /// A brief description of the plan, hidden from customers.
50    pub nickname: Option<String>,
51    /// The product whose pricing this plan determines.
52    pub product: Option<stripe_types::Expandable<stripe_shared::Product>>,
53    /// Each element represents a pricing tier.
54    /// This parameter requires `billing_scheme` to be set to `tiered`.
55    /// See also the documentation for `billing_scheme`.
56    pub tiers: Option<Vec<stripe_shared::PlanTier>>,
57    /// Defines if the tiering price should be `graduated` or `volume` based.
58    /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price.
59    /// In `graduated` tiering, pricing can change as the quantity grows.
60    pub tiers_mode: Option<stripe_shared::PlanTiersMode>,
61    /// Apply a transformation to the reported usage or set quantity before computing the amount billed.
62    /// Cannot be combined with `tiers`.
63    pub transform_usage: Option<stripe_shared::TransformUsage>,
64    /// Default number of trial days when subscribing a customer to this plan using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan).
65    pub trial_period_days: Option<u32>,
66    /// Configures how the quantity per period should be determined.
67    /// Can be either `metered` or `licensed`.
68    /// `licensed` automatically bills the `quantity` set when adding it to a subscription.
69    /// `metered` aggregates the total usage based on usage records.
70    /// Defaults to `licensed`.
71    pub usage_type: stripe_shared::PlanUsageType,
72}
73#[doc(hidden)]
74pub struct PlanBuilder {
75    active: Option<bool>,
76    amount: Option<Option<i64>>,
77    amount_decimal: Option<Option<String>>,
78    billing_scheme: Option<stripe_shared::PlanBillingScheme>,
79    created: Option<stripe_types::Timestamp>,
80    currency: Option<stripe_types::Currency>,
81    id: Option<stripe_shared::PlanId>,
82    interval: Option<stripe_shared::PlanInterval>,
83    interval_count: Option<u64>,
84    livemode: Option<bool>,
85    metadata: Option<Option<std::collections::HashMap<String, String>>>,
86    meter: Option<Option<String>>,
87    nickname: Option<Option<String>>,
88    product: Option<Option<stripe_types::Expandable<stripe_shared::Product>>>,
89    tiers: Option<Option<Vec<stripe_shared::PlanTier>>>,
90    tiers_mode: Option<Option<stripe_shared::PlanTiersMode>>,
91    transform_usage: Option<Option<stripe_shared::TransformUsage>>,
92    trial_period_days: Option<Option<u32>>,
93    usage_type: Option<stripe_shared::PlanUsageType>,
94}
95
96#[allow(
97    unused_variables,
98    irrefutable_let_patterns,
99    clippy::let_unit_value,
100    clippy::match_single_binding,
101    clippy::single_match
102)]
103const _: () = {
104    use miniserde::de::{Map, Visitor};
105    use miniserde::json::Value;
106    use miniserde::{make_place, Deserialize, Result};
107    use stripe_types::miniserde_helpers::FromValueOpt;
108    use stripe_types::{MapBuilder, ObjectDeser};
109
110    make_place!(Place);
111
112    impl Deserialize for Plan {
113        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
114            Place::new(out)
115        }
116    }
117
118    struct Builder<'a> {
119        out: &'a mut Option<Plan>,
120        builder: PlanBuilder,
121    }
122
123    impl Visitor for Place<Plan> {
124        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
125            Ok(Box::new(Builder { out: &mut self.out, builder: PlanBuilder::deser_default() }))
126        }
127    }
128
129    impl MapBuilder for PlanBuilder {
130        type Out = Plan;
131        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
132            Ok(match k {
133                "active" => Deserialize::begin(&mut self.active),
134                "amount" => Deserialize::begin(&mut self.amount),
135                "amount_decimal" => Deserialize::begin(&mut self.amount_decimal),
136                "billing_scheme" => Deserialize::begin(&mut self.billing_scheme),
137                "created" => Deserialize::begin(&mut self.created),
138                "currency" => Deserialize::begin(&mut self.currency),
139                "id" => Deserialize::begin(&mut self.id),
140                "interval" => Deserialize::begin(&mut self.interval),
141                "interval_count" => Deserialize::begin(&mut self.interval_count),
142                "livemode" => Deserialize::begin(&mut self.livemode),
143                "metadata" => Deserialize::begin(&mut self.metadata),
144                "meter" => Deserialize::begin(&mut self.meter),
145                "nickname" => Deserialize::begin(&mut self.nickname),
146                "product" => Deserialize::begin(&mut self.product),
147                "tiers" => Deserialize::begin(&mut self.tiers),
148                "tiers_mode" => Deserialize::begin(&mut self.tiers_mode),
149                "transform_usage" => Deserialize::begin(&mut self.transform_usage),
150                "trial_period_days" => Deserialize::begin(&mut self.trial_period_days),
151                "usage_type" => Deserialize::begin(&mut self.usage_type),
152
153                _ => <dyn Visitor>::ignore(),
154            })
155        }
156
157        fn deser_default() -> Self {
158            Self {
159                active: Deserialize::default(),
160                amount: Deserialize::default(),
161                amount_decimal: Deserialize::default(),
162                billing_scheme: Deserialize::default(),
163                created: Deserialize::default(),
164                currency: Deserialize::default(),
165                id: Deserialize::default(),
166                interval: Deserialize::default(),
167                interval_count: Deserialize::default(),
168                livemode: Deserialize::default(),
169                metadata: Deserialize::default(),
170                meter: Deserialize::default(),
171                nickname: Deserialize::default(),
172                product: Deserialize::default(),
173                tiers: Deserialize::default(),
174                tiers_mode: Deserialize::default(),
175                transform_usage: Deserialize::default(),
176                trial_period_days: Deserialize::default(),
177                usage_type: Deserialize::default(),
178            }
179        }
180
181        fn take_out(&mut self) -> Option<Self::Out> {
182            let (
183                Some(active),
184                Some(amount),
185                Some(amount_decimal),
186                Some(billing_scheme),
187                Some(created),
188                Some(currency),
189                Some(id),
190                Some(interval),
191                Some(interval_count),
192                Some(livemode),
193                Some(metadata),
194                Some(meter),
195                Some(nickname),
196                Some(product),
197                Some(tiers),
198                Some(tiers_mode),
199                Some(transform_usage),
200                Some(trial_period_days),
201                Some(usage_type),
202            ) = (
203                self.active,
204                self.amount,
205                self.amount_decimal.take(),
206                self.billing_scheme,
207                self.created,
208                self.currency,
209                self.id.take(),
210                self.interval,
211                self.interval_count,
212                self.livemode,
213                self.metadata.take(),
214                self.meter.take(),
215                self.nickname.take(),
216                self.product.take(),
217                self.tiers.take(),
218                self.tiers_mode,
219                self.transform_usage,
220                self.trial_period_days,
221                self.usage_type,
222            )
223            else {
224                return None;
225            };
226            Some(Self::Out {
227                active,
228                amount,
229                amount_decimal,
230                billing_scheme,
231                created,
232                currency,
233                id,
234                interval,
235                interval_count,
236                livemode,
237                metadata,
238                meter,
239                nickname,
240                product,
241                tiers,
242                tiers_mode,
243                transform_usage,
244                trial_period_days,
245                usage_type,
246            })
247        }
248    }
249
250    impl<'a> Map for Builder<'a> {
251        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
252            self.builder.key(k)
253        }
254
255        fn finish(&mut self) -> Result<()> {
256            *self.out = self.builder.take_out();
257            Ok(())
258        }
259    }
260
261    impl ObjectDeser for Plan {
262        type Builder = PlanBuilder;
263    }
264
265    impl FromValueOpt for Plan {
266        fn from_value(v: Value) -> Option<Self> {
267            let Value::Object(obj) = v else {
268                return None;
269            };
270            let mut b = PlanBuilder::deser_default();
271            for (k, v) in obj {
272                match k.as_str() {
273                    "active" => b.active = FromValueOpt::from_value(v),
274                    "amount" => b.amount = FromValueOpt::from_value(v),
275                    "amount_decimal" => b.amount_decimal = FromValueOpt::from_value(v),
276                    "billing_scheme" => b.billing_scheme = FromValueOpt::from_value(v),
277                    "created" => b.created = FromValueOpt::from_value(v),
278                    "currency" => b.currency = FromValueOpt::from_value(v),
279                    "id" => b.id = FromValueOpt::from_value(v),
280                    "interval" => b.interval = FromValueOpt::from_value(v),
281                    "interval_count" => b.interval_count = FromValueOpt::from_value(v),
282                    "livemode" => b.livemode = FromValueOpt::from_value(v),
283                    "metadata" => b.metadata = FromValueOpt::from_value(v),
284                    "meter" => b.meter = FromValueOpt::from_value(v),
285                    "nickname" => b.nickname = FromValueOpt::from_value(v),
286                    "product" => b.product = FromValueOpt::from_value(v),
287                    "tiers" => b.tiers = FromValueOpt::from_value(v),
288                    "tiers_mode" => b.tiers_mode = FromValueOpt::from_value(v),
289                    "transform_usage" => b.transform_usage = FromValueOpt::from_value(v),
290                    "trial_period_days" => b.trial_period_days = FromValueOpt::from_value(v),
291                    "usage_type" => b.usage_type = FromValueOpt::from_value(v),
292
293                    _ => {}
294                }
295            }
296            b.take_out()
297        }
298    }
299};
300#[cfg(feature = "serialize")]
301impl serde::Serialize for Plan {
302    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
303        use serde::ser::SerializeStruct;
304        let mut s = s.serialize_struct("Plan", 20)?;
305        s.serialize_field("active", &self.active)?;
306        s.serialize_field("amount", &self.amount)?;
307        s.serialize_field("amount_decimal", &self.amount_decimal)?;
308        s.serialize_field("billing_scheme", &self.billing_scheme)?;
309        s.serialize_field("created", &self.created)?;
310        s.serialize_field("currency", &self.currency)?;
311        s.serialize_field("id", &self.id)?;
312        s.serialize_field("interval", &self.interval)?;
313        s.serialize_field("interval_count", &self.interval_count)?;
314        s.serialize_field("livemode", &self.livemode)?;
315        s.serialize_field("metadata", &self.metadata)?;
316        s.serialize_field("meter", &self.meter)?;
317        s.serialize_field("nickname", &self.nickname)?;
318        s.serialize_field("product", &self.product)?;
319        s.serialize_field("tiers", &self.tiers)?;
320        s.serialize_field("tiers_mode", &self.tiers_mode)?;
321        s.serialize_field("transform_usage", &self.transform_usage)?;
322        s.serialize_field("trial_period_days", &self.trial_period_days)?;
323        s.serialize_field("usage_type", &self.usage_type)?;
324
325        s.serialize_field("object", "plan")?;
326        s.end()
327    }
328}
329impl stripe_types::Object for Plan {
330    type Id = stripe_shared::PlanId;
331    fn id(&self) -> &Self::Id {
332        &self.id
333    }
334
335    fn into_id(self) -> Self::Id {
336        self.id
337    }
338}
339stripe_types::def_id!(PlanId);
340#[derive(Copy, Clone, Eq, PartialEq)]
341pub enum PlanBillingScheme {
342    PerUnit,
343    Tiered,
344}
345impl PlanBillingScheme {
346    pub fn as_str(self) -> &'static str {
347        use PlanBillingScheme::*;
348        match self {
349            PerUnit => "per_unit",
350            Tiered => "tiered",
351        }
352    }
353}
354
355impl std::str::FromStr for PlanBillingScheme {
356    type Err = stripe_types::StripeParseError;
357    fn from_str(s: &str) -> Result<Self, Self::Err> {
358        use PlanBillingScheme::*;
359        match s {
360            "per_unit" => Ok(PerUnit),
361            "tiered" => Ok(Tiered),
362            _ => Err(stripe_types::StripeParseError),
363        }
364    }
365}
366impl std::fmt::Display for PlanBillingScheme {
367    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
368        f.write_str(self.as_str())
369    }
370}
371
372impl std::fmt::Debug for PlanBillingScheme {
373    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
374        f.write_str(self.as_str())
375    }
376}
377impl serde::Serialize for PlanBillingScheme {
378    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
379    where
380        S: serde::Serializer,
381    {
382        serializer.serialize_str(self.as_str())
383    }
384}
385impl miniserde::Deserialize for PlanBillingScheme {
386    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
387        crate::Place::new(out)
388    }
389}
390
391impl miniserde::de::Visitor for crate::Place<PlanBillingScheme> {
392    fn string(&mut self, s: &str) -> miniserde::Result<()> {
393        use std::str::FromStr;
394        self.out = Some(PlanBillingScheme::from_str(s).map_err(|_| miniserde::Error)?);
395        Ok(())
396    }
397}
398
399stripe_types::impl_from_val_with_from_str!(PlanBillingScheme);
400#[cfg(feature = "deserialize")]
401impl<'de> serde::Deserialize<'de> for PlanBillingScheme {
402    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
403        use std::str::FromStr;
404        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
405        Self::from_str(&s)
406            .map_err(|_| serde::de::Error::custom("Unknown value for PlanBillingScheme"))
407    }
408}
409#[derive(Copy, Clone, Eq, PartialEq)]
410pub enum PlanInterval {
411    Day,
412    Month,
413    Week,
414    Year,
415}
416impl PlanInterval {
417    pub fn as_str(self) -> &'static str {
418        use PlanInterval::*;
419        match self {
420            Day => "day",
421            Month => "month",
422            Week => "week",
423            Year => "year",
424        }
425    }
426}
427
428impl std::str::FromStr for PlanInterval {
429    type Err = stripe_types::StripeParseError;
430    fn from_str(s: &str) -> Result<Self, Self::Err> {
431        use PlanInterval::*;
432        match s {
433            "day" => Ok(Day),
434            "month" => Ok(Month),
435            "week" => Ok(Week),
436            "year" => Ok(Year),
437            _ => Err(stripe_types::StripeParseError),
438        }
439    }
440}
441impl std::fmt::Display for PlanInterval {
442    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
443        f.write_str(self.as_str())
444    }
445}
446
447impl std::fmt::Debug for PlanInterval {
448    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
449        f.write_str(self.as_str())
450    }
451}
452impl serde::Serialize for PlanInterval {
453    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
454    where
455        S: serde::Serializer,
456    {
457        serializer.serialize_str(self.as_str())
458    }
459}
460impl miniserde::Deserialize for PlanInterval {
461    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
462        crate::Place::new(out)
463    }
464}
465
466impl miniserde::de::Visitor for crate::Place<PlanInterval> {
467    fn string(&mut self, s: &str) -> miniserde::Result<()> {
468        use std::str::FromStr;
469        self.out = Some(PlanInterval::from_str(s).map_err(|_| miniserde::Error)?);
470        Ok(())
471    }
472}
473
474stripe_types::impl_from_val_with_from_str!(PlanInterval);
475#[cfg(feature = "deserialize")]
476impl<'de> serde::Deserialize<'de> for PlanInterval {
477    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
478        use std::str::FromStr;
479        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
480        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanInterval"))
481    }
482}
483#[derive(Copy, Clone, Eq, PartialEq)]
484pub enum PlanTiersMode {
485    Graduated,
486    Volume,
487}
488impl PlanTiersMode {
489    pub fn as_str(self) -> &'static str {
490        use PlanTiersMode::*;
491        match self {
492            Graduated => "graduated",
493            Volume => "volume",
494        }
495    }
496}
497
498impl std::str::FromStr for PlanTiersMode {
499    type Err = stripe_types::StripeParseError;
500    fn from_str(s: &str) -> Result<Self, Self::Err> {
501        use PlanTiersMode::*;
502        match s {
503            "graduated" => Ok(Graduated),
504            "volume" => Ok(Volume),
505            _ => Err(stripe_types::StripeParseError),
506        }
507    }
508}
509impl std::fmt::Display for PlanTiersMode {
510    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
511        f.write_str(self.as_str())
512    }
513}
514
515impl std::fmt::Debug for PlanTiersMode {
516    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
517        f.write_str(self.as_str())
518    }
519}
520impl serde::Serialize for PlanTiersMode {
521    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
522    where
523        S: serde::Serializer,
524    {
525        serializer.serialize_str(self.as_str())
526    }
527}
528impl miniserde::Deserialize for PlanTiersMode {
529    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
530        crate::Place::new(out)
531    }
532}
533
534impl miniserde::de::Visitor for crate::Place<PlanTiersMode> {
535    fn string(&mut self, s: &str) -> miniserde::Result<()> {
536        use std::str::FromStr;
537        self.out = Some(PlanTiersMode::from_str(s).map_err(|_| miniserde::Error)?);
538        Ok(())
539    }
540}
541
542stripe_types::impl_from_val_with_from_str!(PlanTiersMode);
543#[cfg(feature = "deserialize")]
544impl<'de> serde::Deserialize<'de> for PlanTiersMode {
545    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
546        use std::str::FromStr;
547        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
548        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanTiersMode"))
549    }
550}
551#[derive(Copy, Clone, Eq, PartialEq)]
552pub enum PlanUsageType {
553    Licensed,
554    Metered,
555}
556impl PlanUsageType {
557    pub fn as_str(self) -> &'static str {
558        use PlanUsageType::*;
559        match self {
560            Licensed => "licensed",
561            Metered => "metered",
562        }
563    }
564}
565
566impl std::str::FromStr for PlanUsageType {
567    type Err = stripe_types::StripeParseError;
568    fn from_str(s: &str) -> Result<Self, Self::Err> {
569        use PlanUsageType::*;
570        match s {
571            "licensed" => Ok(Licensed),
572            "metered" => Ok(Metered),
573            _ => Err(stripe_types::StripeParseError),
574        }
575    }
576}
577impl std::fmt::Display for PlanUsageType {
578    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
579        f.write_str(self.as_str())
580    }
581}
582
583impl std::fmt::Debug for PlanUsageType {
584    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
585        f.write_str(self.as_str())
586    }
587}
588impl serde::Serialize for PlanUsageType {
589    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
590    where
591        S: serde::Serializer,
592    {
593        serializer.serialize_str(self.as_str())
594    }
595}
596impl miniserde::Deserialize for PlanUsageType {
597    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
598        crate::Place::new(out)
599    }
600}
601
602impl miniserde::de::Visitor for crate::Place<PlanUsageType> {
603    fn string(&mut self, s: &str) -> miniserde::Result<()> {
604        use std::str::FromStr;
605        self.out = Some(PlanUsageType::from_str(s).map_err(|_| miniserde::Error)?);
606        Ok(())
607    }
608}
609
610stripe_types::impl_from_val_with_from_str!(PlanUsageType);
611#[cfg(feature = "deserialize")]
612impl<'de> serde::Deserialize<'de> for PlanUsageType {
613    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
614        use std::str::FromStr;
615        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
616        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanUsageType"))
617    }
618}