Skip to main content

stripe_shared/
token.rs

1/// Tokenization is the process Stripe uses to collect sensitive card or bank
2/// account details, or personally identifiable information (PII), directly from
3/// your customers in a secure manner. A token representing this information is
4/// returned to your server to use. Use our
5/// [recommended payments integrations](https://docs.stripe.com/payments) to perform this process
6/// on the client-side. This guarantees that no sensitive card data touches your server,
7/// and allows your integration to operate in a PCI-compliant way.
8///
9/// If you can't use client-side tokenization, you can also create tokens using
10/// the API with either your publishable or secret API key. If
11/// your integration uses this method, you're responsible for any PCI compliance
12/// that it might require, and you must keep your secret API key safe. Unlike with
13/// client-side tokenization, your customer's information isn't sent directly to
14/// Stripe, so we can't determine how it's handled or stored.
15///
16/// You can't store or use tokens more than once. To store card or bank account
17/// information for later use, create [Customer](https://docs.stripe.com/api#customers)
18/// objects or [External accounts](/api#external_accounts).
19/// [Radar](https://docs.stripe.com/radar), our integrated solution for automatic fraud protection,
20/// performs best with integrations that use client-side tokenization.
21///
22/// For more details see <<https://stripe.com/docs/api/tokens/object>>.
23#[derive(Clone)]
24#[cfg_attr(not(feature = "redact-generated-debug"), derive(Debug))]
25#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
26pub struct Token {
27    pub bank_account: Option<stripe_shared::BankAccount>,
28    pub card: Option<stripe_shared::Card>,
29    /// IP address of the client that generates the token.
30    pub client_ip: Option<String>,
31    /// Time at which the object was created. Measured in seconds since the Unix epoch.
32    pub created: stripe_types::Timestamp,
33    /// Unique identifier for the object.
34    pub id: stripe_shared::TokenId,
35    /// If the object exists in live mode, the value is `true`.
36    /// If the object exists in test mode, the value is `false`.
37    pub livemode: bool,
38    /// Type of the token: `account`, `bank_account`, `card`, or `pii`.
39    #[cfg_attr(feature = "deserialize", serde(rename = "type"))]
40    pub type_: String,
41    /// Determines if you have already used this token (you can only use tokens once).
42    pub used: bool,
43}
44#[cfg(feature = "redact-generated-debug")]
45impl std::fmt::Debug for Token {
46    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47        f.debug_struct("Token").finish_non_exhaustive()
48    }
49}
50#[doc(hidden)]
51pub struct TokenBuilder {
52    bank_account: Option<Option<stripe_shared::BankAccount>>,
53    card: Option<Option<stripe_shared::Card>>,
54    client_ip: Option<Option<String>>,
55    created: Option<stripe_types::Timestamp>,
56    id: Option<stripe_shared::TokenId>,
57    livemode: Option<bool>,
58    type_: Option<String>,
59    used: Option<bool>,
60}
61
62#[allow(
63    unused_variables,
64    irrefutable_let_patterns,
65    clippy::let_unit_value,
66    clippy::match_single_binding,
67    clippy::single_match
68)]
69const _: () = {
70    use miniserde::de::{Map, Visitor};
71    use miniserde::json::Value;
72    use miniserde::{Deserialize, Result, make_place};
73    use stripe_types::miniserde_helpers::FromValueOpt;
74    use stripe_types::{MapBuilder, ObjectDeser};
75
76    make_place!(Place);
77
78    impl Deserialize for Token {
79        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
80            Place::new(out)
81        }
82    }
83
84    struct Builder<'a> {
85        out: &'a mut Option<Token>,
86        builder: TokenBuilder,
87    }
88
89    impl Visitor for Place<Token> {
90        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
91            Ok(Box::new(Builder { out: &mut self.out, builder: TokenBuilder::deser_default() }))
92        }
93    }
94
95    impl MapBuilder for TokenBuilder {
96        type Out = Token;
97        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
98            Ok(match k {
99                "bank_account" => Deserialize::begin(&mut self.bank_account),
100                "card" => Deserialize::begin(&mut self.card),
101                "client_ip" => Deserialize::begin(&mut self.client_ip),
102                "created" => Deserialize::begin(&mut self.created),
103                "id" => Deserialize::begin(&mut self.id),
104                "livemode" => Deserialize::begin(&mut self.livemode),
105                "type" => Deserialize::begin(&mut self.type_),
106                "used" => Deserialize::begin(&mut self.used),
107                _ => <dyn Visitor>::ignore(),
108            })
109        }
110
111        fn deser_default() -> Self {
112            Self {
113                bank_account: Some(None),
114                card: Some(None),
115                client_ip: Some(None),
116                created: None,
117                id: None,
118                livemode: None,
119                type_: None,
120                used: None,
121            }
122        }
123
124        fn take_out(&mut self) -> Option<Self::Out> {
125            let (
126                Some(bank_account),
127                Some(card),
128                Some(client_ip),
129                Some(created),
130                Some(id),
131                Some(livemode),
132                Some(type_),
133                Some(used),
134            ) = (
135                self.bank_account.take(),
136                self.card.take(),
137                self.client_ip.take(),
138                self.created,
139                self.id.take(),
140                self.livemode,
141                self.type_.take(),
142                self.used,
143            )
144            else {
145                return None;
146            };
147            Some(Self::Out { bank_account, card, client_ip, created, id, livemode, type_, used })
148        }
149    }
150
151    impl Map for Builder<'_> {
152        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
153            self.builder.key(k)
154        }
155
156        fn finish(&mut self) -> Result<()> {
157            *self.out = self.builder.take_out();
158            Ok(())
159        }
160    }
161
162    impl ObjectDeser for Token {
163        type Builder = TokenBuilder;
164    }
165
166    impl FromValueOpt for Token {
167        fn from_value(v: Value) -> Option<Self> {
168            let Value::Object(obj) = v else {
169                return None;
170            };
171            let mut b = TokenBuilder::deser_default();
172            for (k, v) in obj {
173                match k.as_str() {
174                    "bank_account" => b.bank_account = FromValueOpt::from_value(v),
175                    "card" => b.card = FromValueOpt::from_value(v),
176                    "client_ip" => b.client_ip = FromValueOpt::from_value(v),
177                    "created" => b.created = FromValueOpt::from_value(v),
178                    "id" => b.id = FromValueOpt::from_value(v),
179                    "livemode" => b.livemode = FromValueOpt::from_value(v),
180                    "type" => b.type_ = FromValueOpt::from_value(v),
181                    "used" => b.used = FromValueOpt::from_value(v),
182                    _ => {}
183                }
184            }
185            b.take_out()
186        }
187    }
188};
189#[cfg(feature = "serialize")]
190impl serde::Serialize for Token {
191    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
192        use serde::ser::SerializeStruct;
193        let mut s = s.serialize_struct("Token", 9)?;
194        s.serialize_field("bank_account", &self.bank_account)?;
195        s.serialize_field("card", &self.card)?;
196        s.serialize_field("client_ip", &self.client_ip)?;
197        s.serialize_field("created", &self.created)?;
198        s.serialize_field("id", &self.id)?;
199        s.serialize_field("livemode", &self.livemode)?;
200        s.serialize_field("type", &self.type_)?;
201        s.serialize_field("used", &self.used)?;
202
203        s.serialize_field("object", "token")?;
204        s.end()
205    }
206}
207impl stripe_types::Object for Token {
208    type Id = stripe_shared::TokenId;
209    fn id(&self) -> &Self::Id {
210        &self.id
211    }
212
213    fn into_id(self) -> Self::Id {
214        self.id
215    }
216}
217stripe_types::def_id!(TokenId);