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::{Deserialize, Result, make_place};
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                _ => <dyn Visitor>::ignore(),
153            })
154        }
155
156        fn deser_default() -> Self {
157            Self {
158                active: Deserialize::default(),
159                amount: Deserialize::default(),
160                amount_decimal: Deserialize::default(),
161                billing_scheme: Deserialize::default(),
162                created: Deserialize::default(),
163                currency: Deserialize::default(),
164                id: Deserialize::default(),
165                interval: Deserialize::default(),
166                interval_count: Deserialize::default(),
167                livemode: Deserialize::default(),
168                metadata: Deserialize::default(),
169                meter: Deserialize::default(),
170                nickname: Deserialize::default(),
171                product: Deserialize::default(),
172                tiers: Deserialize::default(),
173                tiers_mode: Deserialize::default(),
174                transform_usage: Deserialize::default(),
175                trial_period_days: Deserialize::default(),
176                usage_type: Deserialize::default(),
177            }
178        }
179
180        fn take_out(&mut self) -> Option<Self::Out> {
181            let (
182                Some(active),
183                Some(amount),
184                Some(amount_decimal),
185                Some(billing_scheme),
186                Some(created),
187                Some(currency),
188                Some(id),
189                Some(interval),
190                Some(interval_count),
191                Some(livemode),
192                Some(metadata),
193                Some(meter),
194                Some(nickname),
195                Some(product),
196                Some(tiers),
197                Some(tiers_mode),
198                Some(transform_usage),
199                Some(trial_period_days),
200                Some(usage_type),
201            ) = (
202                self.active,
203                self.amount,
204                self.amount_decimal.take(),
205                self.billing_scheme,
206                self.created,
207                self.currency.take(),
208                self.id.take(),
209                self.interval,
210                self.interval_count,
211                self.livemode,
212                self.metadata.take(),
213                self.meter.take(),
214                self.nickname.take(),
215                self.product.take(),
216                self.tiers.take(),
217                self.tiers_mode,
218                self.transform_usage,
219                self.trial_period_days,
220                self.usage_type,
221            )
222            else {
223                return None;
224            };
225            Some(Self::Out {
226                active,
227                amount,
228                amount_decimal,
229                billing_scheme,
230                created,
231                currency,
232                id,
233                interval,
234                interval_count,
235                livemode,
236                metadata,
237                meter,
238                nickname,
239                product,
240                tiers,
241                tiers_mode,
242                transform_usage,
243                trial_period_days,
244                usage_type,
245            })
246        }
247    }
248
249    impl Map for Builder<'_> {
250        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
251            self.builder.key(k)
252        }
253
254        fn finish(&mut self) -> Result<()> {
255            *self.out = self.builder.take_out();
256            Ok(())
257        }
258    }
259
260    impl ObjectDeser for Plan {
261        type Builder = PlanBuilder;
262    }
263
264    impl FromValueOpt for Plan {
265        fn from_value(v: Value) -> Option<Self> {
266            let Value::Object(obj) = v else {
267                return None;
268            };
269            let mut b = PlanBuilder::deser_default();
270            for (k, v) in obj {
271                match k.as_str() {
272                    "active" => b.active = FromValueOpt::from_value(v),
273                    "amount" => b.amount = FromValueOpt::from_value(v),
274                    "amount_decimal" => b.amount_decimal = FromValueOpt::from_value(v),
275                    "billing_scheme" => b.billing_scheme = FromValueOpt::from_value(v),
276                    "created" => b.created = FromValueOpt::from_value(v),
277                    "currency" => b.currency = FromValueOpt::from_value(v),
278                    "id" => b.id = FromValueOpt::from_value(v),
279                    "interval" => b.interval = FromValueOpt::from_value(v),
280                    "interval_count" => b.interval_count = FromValueOpt::from_value(v),
281                    "livemode" => b.livemode = FromValueOpt::from_value(v),
282                    "metadata" => b.metadata = FromValueOpt::from_value(v),
283                    "meter" => b.meter = FromValueOpt::from_value(v),
284                    "nickname" => b.nickname = FromValueOpt::from_value(v),
285                    "product" => b.product = FromValueOpt::from_value(v),
286                    "tiers" => b.tiers = FromValueOpt::from_value(v),
287                    "tiers_mode" => b.tiers_mode = FromValueOpt::from_value(v),
288                    "transform_usage" => b.transform_usage = FromValueOpt::from_value(v),
289                    "trial_period_days" => b.trial_period_days = FromValueOpt::from_value(v),
290                    "usage_type" => b.usage_type = FromValueOpt::from_value(v),
291                    _ => {}
292                }
293            }
294            b.take_out()
295        }
296    }
297};
298#[cfg(feature = "serialize")]
299impl serde::Serialize for Plan {
300    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
301        use serde::ser::SerializeStruct;
302        let mut s = s.serialize_struct("Plan", 20)?;
303        s.serialize_field("active", &self.active)?;
304        s.serialize_field("amount", &self.amount)?;
305        s.serialize_field("amount_decimal", &self.amount_decimal)?;
306        s.serialize_field("billing_scheme", &self.billing_scheme)?;
307        s.serialize_field("created", &self.created)?;
308        s.serialize_field("currency", &self.currency)?;
309        s.serialize_field("id", &self.id)?;
310        s.serialize_field("interval", &self.interval)?;
311        s.serialize_field("interval_count", &self.interval_count)?;
312        s.serialize_field("livemode", &self.livemode)?;
313        s.serialize_field("metadata", &self.metadata)?;
314        s.serialize_field("meter", &self.meter)?;
315        s.serialize_field("nickname", &self.nickname)?;
316        s.serialize_field("product", &self.product)?;
317        s.serialize_field("tiers", &self.tiers)?;
318        s.serialize_field("tiers_mode", &self.tiers_mode)?;
319        s.serialize_field("transform_usage", &self.transform_usage)?;
320        s.serialize_field("trial_period_days", &self.trial_period_days)?;
321        s.serialize_field("usage_type", &self.usage_type)?;
322
323        s.serialize_field("object", "plan")?;
324        s.end()
325    }
326}
327impl stripe_types::Object for Plan {
328    type Id = stripe_shared::PlanId;
329    fn id(&self) -> &Self::Id {
330        &self.id
331    }
332
333    fn into_id(self) -> Self::Id {
334        self.id
335    }
336}
337stripe_types::def_id!(PlanId);
338#[derive(Copy, Clone, Eq, PartialEq)]
339pub enum PlanBillingScheme {
340    PerUnit,
341    Tiered,
342}
343impl PlanBillingScheme {
344    pub fn as_str(self) -> &'static str {
345        use PlanBillingScheme::*;
346        match self {
347            PerUnit => "per_unit",
348            Tiered => "tiered",
349        }
350    }
351}
352
353impl std::str::FromStr for PlanBillingScheme {
354    type Err = stripe_types::StripeParseError;
355    fn from_str(s: &str) -> Result<Self, Self::Err> {
356        use PlanBillingScheme::*;
357        match s {
358            "per_unit" => Ok(PerUnit),
359            "tiered" => Ok(Tiered),
360            _ => Err(stripe_types::StripeParseError),
361        }
362    }
363}
364impl std::fmt::Display for PlanBillingScheme {
365    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
366        f.write_str(self.as_str())
367    }
368}
369
370impl std::fmt::Debug for PlanBillingScheme {
371    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
372        f.write_str(self.as_str())
373    }
374}
375impl serde::Serialize for PlanBillingScheme {
376    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
377    where
378        S: serde::Serializer,
379    {
380        serializer.serialize_str(self.as_str())
381    }
382}
383impl miniserde::Deserialize for PlanBillingScheme {
384    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
385        crate::Place::new(out)
386    }
387}
388
389impl miniserde::de::Visitor for crate::Place<PlanBillingScheme> {
390    fn string(&mut self, s: &str) -> miniserde::Result<()> {
391        use std::str::FromStr;
392        self.out = Some(PlanBillingScheme::from_str(s).map_err(|_| miniserde::Error)?);
393        Ok(())
394    }
395}
396
397stripe_types::impl_from_val_with_from_str!(PlanBillingScheme);
398#[cfg(feature = "deserialize")]
399impl<'de> serde::Deserialize<'de> for PlanBillingScheme {
400    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
401        use std::str::FromStr;
402        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
403        Self::from_str(&s)
404            .map_err(|_| serde::de::Error::custom("Unknown value for PlanBillingScheme"))
405    }
406}
407#[derive(Copy, Clone, Eq, PartialEq)]
408pub enum PlanInterval {
409    Day,
410    Month,
411    Week,
412    Year,
413}
414impl PlanInterval {
415    pub fn as_str(self) -> &'static str {
416        use PlanInterval::*;
417        match self {
418            Day => "day",
419            Month => "month",
420            Week => "week",
421            Year => "year",
422        }
423    }
424}
425
426impl std::str::FromStr for PlanInterval {
427    type Err = stripe_types::StripeParseError;
428    fn from_str(s: &str) -> Result<Self, Self::Err> {
429        use PlanInterval::*;
430        match s {
431            "day" => Ok(Day),
432            "month" => Ok(Month),
433            "week" => Ok(Week),
434            "year" => Ok(Year),
435            _ => Err(stripe_types::StripeParseError),
436        }
437    }
438}
439impl std::fmt::Display for PlanInterval {
440    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
441        f.write_str(self.as_str())
442    }
443}
444
445impl std::fmt::Debug for PlanInterval {
446    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
447        f.write_str(self.as_str())
448    }
449}
450impl serde::Serialize for PlanInterval {
451    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
452    where
453        S: serde::Serializer,
454    {
455        serializer.serialize_str(self.as_str())
456    }
457}
458impl miniserde::Deserialize for PlanInterval {
459    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
460        crate::Place::new(out)
461    }
462}
463
464impl miniserde::de::Visitor for crate::Place<PlanInterval> {
465    fn string(&mut self, s: &str) -> miniserde::Result<()> {
466        use std::str::FromStr;
467        self.out = Some(PlanInterval::from_str(s).map_err(|_| miniserde::Error)?);
468        Ok(())
469    }
470}
471
472stripe_types::impl_from_val_with_from_str!(PlanInterval);
473#[cfg(feature = "deserialize")]
474impl<'de> serde::Deserialize<'de> for PlanInterval {
475    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
476        use std::str::FromStr;
477        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
478        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanInterval"))
479    }
480}
481#[derive(Copy, Clone, Eq, PartialEq)]
482pub enum PlanTiersMode {
483    Graduated,
484    Volume,
485}
486impl PlanTiersMode {
487    pub fn as_str(self) -> &'static str {
488        use PlanTiersMode::*;
489        match self {
490            Graduated => "graduated",
491            Volume => "volume",
492        }
493    }
494}
495
496impl std::str::FromStr for PlanTiersMode {
497    type Err = stripe_types::StripeParseError;
498    fn from_str(s: &str) -> Result<Self, Self::Err> {
499        use PlanTiersMode::*;
500        match s {
501            "graduated" => Ok(Graduated),
502            "volume" => Ok(Volume),
503            _ => Err(stripe_types::StripeParseError),
504        }
505    }
506}
507impl std::fmt::Display for PlanTiersMode {
508    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
509        f.write_str(self.as_str())
510    }
511}
512
513impl std::fmt::Debug for PlanTiersMode {
514    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
515        f.write_str(self.as_str())
516    }
517}
518impl serde::Serialize for PlanTiersMode {
519    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
520    where
521        S: serde::Serializer,
522    {
523        serializer.serialize_str(self.as_str())
524    }
525}
526impl miniserde::Deserialize for PlanTiersMode {
527    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
528        crate::Place::new(out)
529    }
530}
531
532impl miniserde::de::Visitor for crate::Place<PlanTiersMode> {
533    fn string(&mut self, s: &str) -> miniserde::Result<()> {
534        use std::str::FromStr;
535        self.out = Some(PlanTiersMode::from_str(s).map_err(|_| miniserde::Error)?);
536        Ok(())
537    }
538}
539
540stripe_types::impl_from_val_with_from_str!(PlanTiersMode);
541#[cfg(feature = "deserialize")]
542impl<'de> serde::Deserialize<'de> for PlanTiersMode {
543    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
544        use std::str::FromStr;
545        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
546        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanTiersMode"))
547    }
548}
549#[derive(Copy, Clone, Eq, PartialEq)]
550pub enum PlanUsageType {
551    Licensed,
552    Metered,
553}
554impl PlanUsageType {
555    pub fn as_str(self) -> &'static str {
556        use PlanUsageType::*;
557        match self {
558            Licensed => "licensed",
559            Metered => "metered",
560        }
561    }
562}
563
564impl std::str::FromStr for PlanUsageType {
565    type Err = stripe_types::StripeParseError;
566    fn from_str(s: &str) -> Result<Self, Self::Err> {
567        use PlanUsageType::*;
568        match s {
569            "licensed" => Ok(Licensed),
570            "metered" => Ok(Metered),
571            _ => Err(stripe_types::StripeParseError),
572        }
573    }
574}
575impl std::fmt::Display for PlanUsageType {
576    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
577        f.write_str(self.as_str())
578    }
579}
580
581impl std::fmt::Debug for PlanUsageType {
582    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
583        f.write_str(self.as_str())
584    }
585}
586impl serde::Serialize for PlanUsageType {
587    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
588    where
589        S: serde::Serializer,
590    {
591        serializer.serialize_str(self.as_str())
592    }
593}
594impl miniserde::Deserialize for PlanUsageType {
595    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
596        crate::Place::new(out)
597    }
598}
599
600impl miniserde::de::Visitor for crate::Place<PlanUsageType> {
601    fn string(&mut self, s: &str) -> miniserde::Result<()> {
602        use std::str::FromStr;
603        self.out = Some(PlanUsageType::from_str(s).map_err(|_| miniserde::Error)?);
604        Ok(())
605    }
606}
607
608stripe_types::impl_from_val_with_from_str!(PlanUsageType);
609#[cfg(feature = "deserialize")]
610impl<'de> serde::Deserialize<'de> for PlanUsageType {
611    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
612        use std::str::FromStr;
613        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
614        Self::from_str(&s).map_err(|_| serde::de::Error::custom("Unknown value for PlanUsageType"))
615    }
616}