From 80a361f32e2867be6f209cd9b2b8a23997f8762c Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Tue, 18 Jun 2024 17:03:07 +0530 Subject: [PATCH 01/24] Add expires_at --- ft-sdk/src/auth/provider.rs | 28 +++++++++++++++++---- ft-sdk/src/auth/schema.rs | 1 + ft-sdk/src/auth/session.rs | 50 +++++++++++++++++++++++++++++++------ 3 files changed, 67 insertions(+), 12 deletions(-) diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index 948f41a..f885510 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -295,18 +295,36 @@ pub fn create_user( /// `identity`: Eg for GitHub, it could be the username. This is stored in the cookie so can be /// retrieved without a db call to show a user identifiable information. pub fn login( + conn: &mut ft_sdk::Connection, + user_id: &ft_sdk::UserId, + session_id: Option, +) -> Result { + login_with_custom_session_expiration(conn, user_id, session_id, None) +} + +pub fn login_with_custom_session_expiration( conn: &mut ft_sdk::Connection, ft_sdk::UserId(user_id): &ft_sdk::UserId, session_id: Option, + session_expiration_duration: Option, ) -> Result { match session_id { - Some(session_id) if session_id.0 == "hello" => { - Ok(ft_sdk::auth::session::create_with_user(conn, *user_id)?) - } + Some(session_id) if session_id.0 == "hello" => Ok(ft_sdk::auth::session::create_with_user( + conn, + *user_id, + session_expiration_duration, + )?), Some(session_id) => Ok(ft_sdk::auth::session::set_user_id( - conn, session_id, *user_id, + conn, + session_id, + *user_id, + session_expiration_duration, + )?), + None => Ok(ft_sdk::auth::session::create_with_user( + conn, + *user_id, + session_expiration_duration, )?), - None => Ok(ft_sdk::auth::session::create_with_user(conn, *user_id)?), } } diff --git a/ft-sdk/src/auth/schema.rs b/ft-sdk/src/auth/schema.rs index c632e49..d06c7f0 100644 --- a/ft-sdk/src/auth/schema.rs +++ b/ft-sdk/src/auth/schema.rs @@ -20,6 +20,7 @@ diesel::table! { data -> Text, updated_at -> Timestamptz, created_at -> Timestamptz, + expires_at -> Nullable, } } diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 120f2f8..4c69e9d 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -17,17 +17,49 @@ pub fn set_user_id( conn: &mut ft_sdk::Connection, SessionID(session_id): SessionID, user_id: i64, + session_expiration_duration: Option, ) -> Result { use diesel::prelude::*; use ft_sdk::auth::fastn_session; - match diesel::update(fastn_session::table.filter(fastn_session::id.eq(session_id.as_str()))) - .set(fastn_session::uid.eq(Some(user_id))) - .execute(conn)? - { - 0 => Ok(create_with_user(conn, user_id)?), - 1 => Ok(SessionID(session_id)), - _ => Err(SetUserIDError::MultipleSessionsFound), + // Query to check if the session exists and get its expiration time + let existing_session_expires_at = fastn_session::table + .select(fastn_session::expires_at.nullable()) + .filter(fastn_session::id.eq(session_id.as_str())) + .first::>>(conn) // Assuming session columns are (id, uid, expires_at) + .optional()?; + + let now = ft_sdk::env::now(); + match existing_session_expires_at { + Some(Some(expires_at)) if expires_at < now => { + // Session is expired, delete it and create a new one + diesel::delete(fastn_session::table.filter(fastn_session::id.eq(session_id.as_str()))) + .execute(conn)?; + Ok(create_with_user( + conn, + user_id, + session_expiration_duration, + )?) + } + Some(_) => { + // Session is not expired, update the user ID + diesel::update(fastn_session::table.filter(fastn_session::id.eq(session_id.as_str()))) + .set(( + fastn_session::uid.eq(Some(user_id)), + fastn_session::updated_at.eq(now), + )) + .execute(conn)?; + + Ok(SessionID(session_id)) + } + None => { + // Session does not exist, create a new one + Ok(create_with_user( + conn, + user_id, + session_expiration_duration, + )?) + } } } @@ -35,11 +67,14 @@ pub fn set_user_id( pub fn create_with_user( conn: &mut ft_sdk::Connection, user_id: i64, + session_expiration_duration: Option, ) -> Result { use diesel::prelude::*; use ft_sdk::auth::fastn_session; let session_id = generate_new_session_id(); + let session_expires_at = + session_expiration_duration.map(|duration| ft_sdk::env::now().add(duration)); diesel::insert_into(fastn_session::table) .values(( @@ -47,6 +82,7 @@ pub fn create_with_user( fastn_session::uid.eq(Some(user_id)), fastn_session::created_at.eq(ft_sdk::env::now()), fastn_session::updated_at.eq(ft_sdk::env::now()), + fastn_session::expires_at.eq(session_expires_at), fastn_session::data.eq("{}"), )) .execute(conn)?; From 6960337875a723f0dab18d7e750f2392c1ae96bc Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Tue, 18 Jun 2024 17:13:28 +0530 Subject: [PATCH 02/24] Added code documentation for login --- ft-sdk/src/auth/provider.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index f885510..dfe17eb 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -290,10 +290,18 @@ pub fn create_user( Ok(ft_sdk::auth::UserId(user_id)) } -/// persist the user in session and redirect to `next` +/// Logs in a user and manages session creation or update. /// -/// `identity`: Eg for GitHub, it could be the username. This is stored in the cookie so can be -/// retrieved without a db call to show a user identifiable information. +/// # Arguments +/// +/// * `conn` - Mutable reference to a `ft_sdk::Connection` to interact with the database. +/// * `user_id` - Reference to a `ft_sdk::UserId` representing the user's ID. +/// * `session_id` - Optional `ft_sdk::auth::SessionID` representing an existing session ID. +/// +/// # Returns +/// +/// A `Result` containing a `ft_sdk::auth::SessionID` if the login operation is successful, +/// or a `LoginError` if there's an issue with the login process. pub fn login( conn: &mut ft_sdk::Connection, user_id: &ft_sdk::UserId, @@ -302,6 +310,20 @@ pub fn login( login_with_custom_session_expiration(conn, user_id, session_id, None) } + +/// Logs in a user with customizable session expiration and manages session creation or update. +/// +/// # Arguments +/// +/// * `conn` - Mutable reference to a `ft_sdk::Connection` to interact with the database. +/// * `user_id` - Reference to a `ft_sdk::UserId` representing the user's ID. +/// * `session_id` - Optional `ft_sdk::auth::SessionID` representing an existing session ID. +/// * `session_expiration_duration` - Optional `chrono::Duration` for custom session expiration. +/// +/// # Returns +/// +/// A `Result` containing a `ft_sdk::auth::SessionID` if the login operation is successful, +/// or a `LoginError` if there's an issue with the login process. pub fn login_with_custom_session_expiration( conn: &mut ft_sdk::Connection, ft_sdk::UserId(user_id): &ft_sdk::UserId, From 6d1f1af92f450589cb3dda3ba866e5290de9687f Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Tue, 18 Jun 2024 17:14:35 +0530 Subject: [PATCH 03/24] Minor fix --- ft-sdk/src/auth/provider.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index dfe17eb..d4b74c2 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -356,7 +356,6 @@ pub enum LoginError { DatabaseError(#[from] diesel::result::Error), #[error("set user id for session {0}")] SetUserIDError(#[from] ft_sdk::auth::session::SetUserIDError), - #[error("json error: {0}")] JsonError(#[from] serde_json::Error), } From 5b266d4daa40ca47743ea9d6f8f186a184a94449 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Tue, 18 Jun 2024 23:56:20 +0530 Subject: [PATCH 04/24] Added set_session_cookie and expire_session_cookie --- Cargo.lock | 63 ++++++++++++++++++++++++++ Cargo.toml | 1 + ft-sdk/Cargo.toml | 1 + ft-sdk/src/auth/provider.rs | 90 +++++++++++++++++++++++++++++++++++++ ft-sdk/src/auth/session.rs | 2 + 5 files changed, 157 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 01b0795..bf7de12 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,12 +90,31 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "time", + "version_check", +] + [[package]] name = "core-foundation-sys" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] + [[package]] name = "diesel" version = "2.1.6" @@ -179,6 +198,7 @@ dependencies = [ "anyhow", "bytes", "chrono", + "cookie", "diesel", "ft-derive", "ft-sys", @@ -358,6 +378,12 @@ dependencies = [ "include_dir", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-traits" version = "0.2.19" @@ -385,6 +411,12 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "pretty_assertions" version = "1.4.0" @@ -530,6 +562,37 @@ dependencies = [ "syn 2.0.66", ] +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "unicode-ident" version = "1.0.12" diff --git a/Cargo.toml b/Cargo.toml index c0c3eee..ccd13d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "1" chrono = { version = "0.4", default-features = false, features = ["serde"] } +cookie = "0.18" diesel = { version = ">=2, <2.2", features = ["serde_json"] } serde_urlencoded = "0.7" include_dir = "0.7" diff --git a/ft-sdk/Cargo.toml b/ft-sdk/Cargo.toml index c0c1aa7..27eaf6e 100644 --- a/ft-sdk/Cargo.toml +++ b/ft-sdk/Cargo.toml @@ -33,6 +33,7 @@ diesel = { workspace = true, optional = true } include_dir.workspace = true rand_core.workspace = true uuid.workspace = true +cookie.workspace = true [dev-dependencies] pretty_assertions = "1" diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index d4b74c2..f0a2d7c 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -22,6 +22,9 @@ //! username etc. The UI will have been provided by the auth provider, or some other generic auth //! setting package. +use crate::auth::fastn_session; +use crate::auth::session::SetUserIDError; + /// In the current session, we have zero or more scopes dropped by different auth /// providers that have been used so far. Each auth provider sdk also provides some /// APIs that require certain scopes to be present. Before calling those APIs, the @@ -360,6 +363,93 @@ pub enum LoginError { JsonError(#[from] serde_json::Error), } + +/// Sets a session cookie with an expiration time based on the session's expiration time +/// in the database. If the session has an expiration time in the future, the cookie's +/// max age is set to the remaining duration until that time. Otherwise, a default max age +/// of 400 days is set. +/// +/// # Arguments +/// +/// * `conn` - A mutable reference to the database connection. +/// * `session_id` - A string slice representing the session ID. +/// * `host` - The host for which the cookie is valid. +/// +/// # Errors +/// +/// This function will return an error if: +/// * The session ID is not found in the database. +/// * The session ID is found but has expired. +/// * There is an issue querying the database. +/// * There is an error creating the `http::HeaderValue`. +pub fn set_session_cookie( + conn: &mut ft_sdk::Connection, + session_id: &str, + host: ft_sdk::Host +) -> Result { + use diesel::prelude::*; + use ft_sdk::auth::fastn_session; + + let now = ft_sdk::env::now(); + + // Query to check if the session exists and get its expiration time. + let max_age = match fastn_session::table + .select(fastn_session::expires_at.nullable()) + .filter(fastn_session::id.eq(session_id)) + .first::>>(conn) + { + // If the session has an expiration time and it is in the future. + Ok(Some(session_expires_at)) if session_expires_at > now => { + let duration = session_expires_at - now; + cookie::time::Duration::new(duration.num_seconds(), duration.subsec_nanos()) + }, + // If the session does not have an expiration time. + Ok(None) => cookie::time::Duration::seconds(34560000), + // If the session has an expiration time and it is in the past. + Ok(_) => return Err(SetUserIDError::SessionExpired), + // If the session is not found. + Err(diesel::NotFound) => return Err(SetUserIDError::SessionNotFound), + // If there is an error querying the database. + Err(e) => return Err(e.into()) + }; + + // Build the cookie with the determined max age + let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, session_id)) + .domain(host.without_port()) + .path("/") + .max_age(max_age) + .same_site(cookie::SameSite::Strict) + .build(); + + // Convert the cookie to an HTTP header value and return it + Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) +} + +/// Expires the session cookie immediately by setting its expiration time to the current time. +pub fn expire_session_cookie( + host: ft_sdk::Host, +) -> Result { + let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, "")) + .domain(host.without_port()) + .path("/") + .expires(convert_now_to_offsetdatetime()) + .build(); + + Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) +} + +/// Converts the current time to `cookie::time::OffsetDateTime`. +fn convert_now_to_offsetdatetime() -> cookie::time::OffsetDateTime { + let now = ft_sdk::env::now(); + let timestamp = now.timestamp(); + let nanoseconds = now.timestamp_subsec_nanos(); + cookie::time::OffsetDateTime::from_unix_timestamp_nanos( + (timestamp * 1_000_000_000 + nanoseconds as i64) as i128, + ) + .unwrap() +} + + // Normalise and save user details // // If the provider provides UserData::VerifiedEmail, then we also add the data against "email" diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 4c69e9d..e96d046 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -6,6 +6,8 @@ pub struct SessionID(pub String); pub enum SetUserIDError { #[error("session not found")] SessionNotFound, + #[error("session expired")] + SessionExpired, #[error("multiple sessions found")] MultipleSessionsFound, #[error("failed to query db: {0:?}")] From 5468d791e0a56a6a3d01ad0523f6bed635c6ce3d Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 00:33:06 +0530 Subject: [PATCH 05/24] Added SessionID::from_user_id --- ft-sdk/src/auth/provider.rs | 88 ---------------------- ft-sdk/src/auth/session.rs | 143 +++++++++++++++++++++++++++++++++++- 2 files changed, 142 insertions(+), 89 deletions(-) diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index f0a2d7c..b142de4 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -313,7 +313,6 @@ pub fn login( login_with_custom_session_expiration(conn, user_id, session_id, None) } - /// Logs in a user with customizable session expiration and manages session creation or update. /// /// # Arguments @@ -363,93 +362,6 @@ pub enum LoginError { JsonError(#[from] serde_json::Error), } - -/// Sets a session cookie with an expiration time based on the session's expiration time -/// in the database. If the session has an expiration time in the future, the cookie's -/// max age is set to the remaining duration until that time. Otherwise, a default max age -/// of 400 days is set. -/// -/// # Arguments -/// -/// * `conn` - A mutable reference to the database connection. -/// * `session_id` - A string slice representing the session ID. -/// * `host` - The host for which the cookie is valid. -/// -/// # Errors -/// -/// This function will return an error if: -/// * The session ID is not found in the database. -/// * The session ID is found but has expired. -/// * There is an issue querying the database. -/// * There is an error creating the `http::HeaderValue`. -pub fn set_session_cookie( - conn: &mut ft_sdk::Connection, - session_id: &str, - host: ft_sdk::Host -) -> Result { - use diesel::prelude::*; - use ft_sdk::auth::fastn_session; - - let now = ft_sdk::env::now(); - - // Query to check if the session exists and get its expiration time. - let max_age = match fastn_session::table - .select(fastn_session::expires_at.nullable()) - .filter(fastn_session::id.eq(session_id)) - .first::>>(conn) - { - // If the session has an expiration time and it is in the future. - Ok(Some(session_expires_at)) if session_expires_at > now => { - let duration = session_expires_at - now; - cookie::time::Duration::new(duration.num_seconds(), duration.subsec_nanos()) - }, - // If the session does not have an expiration time. - Ok(None) => cookie::time::Duration::seconds(34560000), - // If the session has an expiration time and it is in the past. - Ok(_) => return Err(SetUserIDError::SessionExpired), - // If the session is not found. - Err(diesel::NotFound) => return Err(SetUserIDError::SessionNotFound), - // If there is an error querying the database. - Err(e) => return Err(e.into()) - }; - - // Build the cookie with the determined max age - let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, session_id)) - .domain(host.without_port()) - .path("/") - .max_age(max_age) - .same_site(cookie::SameSite::Strict) - .build(); - - // Convert the cookie to an HTTP header value and return it - Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) -} - -/// Expires the session cookie immediately by setting its expiration time to the current time. -pub fn expire_session_cookie( - host: ft_sdk::Host, -) -> Result { - let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, "")) - .domain(host.without_port()) - .path("/") - .expires(convert_now_to_offsetdatetime()) - .build(); - - Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) -} - -/// Converts the current time to `cookie::time::OffsetDateTime`. -fn convert_now_to_offsetdatetime() -> cookie::time::OffsetDateTime { - let now = ft_sdk::env::now(); - let timestamp = now.timestamp(); - let nanoseconds = now.timestamp_subsec_nanos(); - cookie::time::OffsetDateTime::from_unix_timestamp_nanos( - (timestamp * 1_000_000_000 + nanoseconds as i64) as i128, - ) - .unwrap() -} - - // Normalise and save user details // // If the provider provides UserData::VerifiedEmail, then we also add the data against "email" diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index e96d046..0fb6214 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -28,7 +28,7 @@ pub fn set_user_id( let existing_session_expires_at = fastn_session::table .select(fastn_session::expires_at.nullable()) .filter(fastn_session::id.eq(session_id.as_str())) - .first::>>(conn) // Assuming session columns are (id, uid, expires_at) + .first::>>(conn) .optional()?; let now = ft_sdk::env::now(); @@ -92,6 +92,147 @@ pub fn create_with_user( Ok(ft_sdk::auth::SessionID(session_id)) } +/// Sets a session cookie with an expiration time based on the session's expiration time +/// in the database. If the session has an expiration time in the future, the cookie's +/// max age is set to the remaining duration until that time. Otherwise, a default max age +/// of 400 days is set. +/// +/// # Arguments +/// +/// * `conn` - A mutable reference to the database connection. +/// * `session_id` - A string slice representing the session ID. +/// * `host` - The host for which the cookie is valid. +/// +/// # Errors +/// +/// This function will return an error if: +/// * The session ID is not found in the database. +/// * The session ID is found but has expired. +/// * There is an issue querying the database. +/// * There is an error creating the `http::HeaderValue`. +#[cfg(feature = "auth-provider")] +pub fn set_session_cookie( + conn: &mut ft_sdk::Connection, + session_id: &str, + host: ft_sdk::Host, +) -> Result { + use diesel::prelude::*; + use ft_sdk::auth::fastn_session; + + let now = ft_sdk::env::now(); + + // Query to check if the session exists and get its expiration time. + let max_age = match fastn_session::table + .select(fastn_session::expires_at.nullable()) + .filter(fastn_session::id.eq(session_id)) + .first::>>(conn) + { + // If the session has an expiration time and it is in the future. + Ok(Some(session_expires_at)) if session_expires_at > now => { + let duration = session_expires_at - now; + cookie::time::Duration::new(duration.num_seconds(), duration.subsec_nanos()) + } + // If the session does not have an expiration time. + Ok(None) => cookie::time::Duration::seconds(34560000), + // If the session has an expiration time and it is in the past. + Ok(_) => return Err(SetUserIDError::SessionExpired.into()), + // If the session is not found. + Err(diesel::NotFound) => return Err(SetUserIDError::SessionNotFound.into()), + // If there is an error querying the database. + Err(e) => return Err(e.into()), + }; + + // Build the cookie with the determined max age + let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, session_id)) + .domain(host.without_port()) + .path("/") + .max_age(max_age) + .same_site(cookie::SameSite::Strict) + .build(); + + // Convert the cookie to an HTTP header value and return it + Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) +} + +/// Expires the session cookie immediately by setting its expiration time to the current time. +#[cfg(feature = "auth-provider")] +pub fn expire_session_cookie(host: ft_sdk::Host) -> Result { + let cookie = cookie::Cookie::build((ft_sdk::auth::SESSION_KEY, "")) + .domain(host.without_port()) + .path("/") + .expires(convert_now_to_offsetdatetime()) + .build(); + + Ok(http::HeaderValue::from_str(cookie.to_string().as_str())?) +} + +#[derive(Debug, thiserror::Error)] +pub enum SessionIDError { + #[error("session not found")] + SessionNotFound, + #[error("session expired")] + SessionExpired, + #[error("failed to query db: {0:?}")] + DatabaseError(#[from] diesel::result::Error), +} + +impl SessionID { + /// Retrieves a session ID based on a given user ID. + /// + /// This method queries the database to find a session associated with the + /// given user ID. + /// + /// # Arguments + /// + /// * `conn` - A mutable reference to the database connection. + /// * `user_id` - The user ID for which the session ID needs to be retrieved. + /// + /// # Returns + /// + /// * `Ok(SessionID)` - If a valid session ID is found. + /// * `Err(SessionIDError)` - If an error occurs, such as session expiration or session not found. + pub fn from_user_id( + conn: &mut ft_sdk::Connection, + user_id: ft_sdk::auth::UserId, + ) -> Result { + use diesel::prelude::*; + use ft_sdk::auth::fastn_session; + + // Get the current time. + let now = ft_sdk::env::now(); + + // Query to find the session ID and its expiration time for the given user ID. + match fastn_session::table + .select((fastn_session::id, fastn_session::expires_at)) + .filter(fastn_session::uid.eq(user_id.0)) + .first::<(String, Option>)>(conn) + { + // If a session is found and it is expired, return a `SessionExpired` error. + Ok((_, Some(expires_at))) if expires_at < now => { + return Err(SessionIDError::SessionExpired) + } + // If a valid session is found, return the session ID. + Ok((id, _)) => Ok(SessionID(id)), + // If no session is found for the user ID, return a `SessionNotFound` error. + Err(diesel::NotFound) => return Err(SessionIDError::SessionNotFound), + // If any other error occurs during the query, return it. + Err(e) => return Err(e.into()), + } + } +} + +/// Converts the current time to `cookie::time::OffsetDateTime`. +#[cfg(feature = "auth-provider")] +fn convert_now_to_offsetdatetime() -> cookie::time::OffsetDateTime { + let now = ft_sdk::env::now(); + let timestamp = now.timestamp(); + let nanoseconds = now.timestamp_subsec_nanos(); + cookie::time::OffsetDateTime::from_unix_timestamp_nanos( + (timestamp * 1_000_000_000 + nanoseconds as i64) as i128, + ) + .unwrap() +} + #[cfg(feature = "auth-provider")] fn generate_new_session_id() -> String { use rand_core::RngCore; From bc002d737f811228d8b3a06e18da27aedc42c51e Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 00:36:23 +0530 Subject: [PATCH 06/24] Minor fix --- ft-sdk/src/auth/session.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 0fb6214..e499986 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -193,7 +193,7 @@ impl SessionID { /// * `Err(SessionIDError)` - If an error occurs, such as session expiration or session not found. pub fn from_user_id( conn: &mut ft_sdk::Connection, - user_id: ft_sdk::auth::UserId, + user_id: &ft_sdk::auth::UserId, ) -> Result { use diesel::prelude::*; use ft_sdk::auth::fastn_session; From fbecd9348e15ab87f7f83058f4fc95856646f85b Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 00:45:12 +0530 Subject: [PATCH 07/24] Minor fix --- ft-sdk/src/auth/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 9709f06..e2d7704 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -6,7 +6,7 @@ mod utils; pub use ft_sys_shared::SESSION_KEY; pub use schema::{fastn_session, fastn_user}; -pub use session::SessionID; +pub use session::{SessionID, set_session_cookie, expire_session_cookie}; pub use utils::{user_data_by_query, Counter}; #[derive(Clone, Debug)] From d9687fa61f22b0555e094c5449a8dcd10713c946 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 00:47:07 +0530 Subject: [PATCH 08/24] Minor fix --- ft-sdk/src/auth/session.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index e499986..8b86bed 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -113,7 +113,7 @@ pub fn create_with_user( #[cfg(feature = "auth-provider")] pub fn set_session_cookie( conn: &mut ft_sdk::Connection, - session_id: &str, + ft_sdk::auth::SessionID(session_id): ft_sdk::auth::SessionID, host: ft_sdk::Host, ) -> Result { use diesel::prelude::*; From 4e10bd4f941a8d2533c85bf6895f3e6cd6469b2e Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 01:30:00 +0530 Subject: [PATCH 09/24] Fix expired_session logic in login --- ft-sdk/src/auth/mod.rs | 4 ++- ft-sdk/src/auth/provider.rs | 15 ++++------ ft-sdk/src/auth/session.rs | 55 +++++++++++++++++++++++++------------ 3 files changed, 45 insertions(+), 29 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index e2d7704..4dec62a 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -6,7 +6,9 @@ mod utils; pub use ft_sys_shared::SESSION_KEY; pub use schema::{fastn_session, fastn_user}; -pub use session::{SessionID, set_session_cookie, expire_session_cookie}; +pub use session::{SessionID, SessionIDError}; +#[cfg(feature = "auth-provider")] +pub use session::{set_session_cookie, expire_session_cookie}; pub use utils::{user_data_by_query, Counter}; #[derive(Clone, Debug)] diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index b142de4..8ec013c 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -328,27 +328,22 @@ pub fn login( /// or a `LoginError` if there's an issue with the login process. pub fn login_with_custom_session_expiration( conn: &mut ft_sdk::Connection, - ft_sdk::UserId(user_id): &ft_sdk::UserId, + user_id: &ft_sdk::UserId, session_id: Option, session_expiration_duration: Option, ) -> Result { match session_id { Some(session_id) if session_id.0 == "hello" => Ok(ft_sdk::auth::session::create_with_user( conn, - *user_id, + user_id, session_expiration_duration, )?), - Some(session_id) => Ok(ft_sdk::auth::session::set_user_id( + _ => Ok(ft_sdk::auth::session::set_user_id( conn, session_id, - *user_id, + user_id, session_expiration_duration, - )?), - None => Ok(ft_sdk::auth::session::create_with_user( - conn, - *user_id, - session_expiration_duration, - )?), + )?) } } diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 8b86bed..9b396b7 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -17,23 +17,42 @@ pub enum SetUserIDError { #[cfg(feature = "auth-provider")] pub fn set_user_id( conn: &mut ft_sdk::Connection, - SessionID(session_id): SessionID, - user_id: i64, + session_id: Option, + user_id: &ft_sdk::UserId, session_expiration_duration: Option, ) -> Result { use diesel::prelude::*; use ft_sdk::auth::fastn_session; + let now = ft_sdk::env::now(); + // Query to check if the session exists and get its expiration time - let existing_session_expires_at = fastn_session::table - .select(fastn_session::expires_at.nullable()) - .filter(fastn_session::id.eq(session_id.as_str())) - .first::>>(conn) - .optional()?; + let session = match session_id { + Some(session_id) => { + let existing_session_expires_at = fastn_session::table + .select(fastn_session::expires_at.nullable()) + .filter(fastn_session::id.eq(session_id.as_str())) + .first::>>(conn) + .optional()?; - let now = ft_sdk::env::now(); - match existing_session_expires_at { - Some(Some(expires_at)) if expires_at < now => { + match existing_session_expires_at { + Some(Some(expires_at)) if expires_at < now => Some((session_id, true)), + Some(_) => Some((session_id, false)), + None => None + } + }, + None => { + match ft_sdk::auth::SessionID::from_user_id(conn, user_id) { + Ok(session_id) => Some((session_id, false)), + Err(ft_sdk::auth::SessionIDError::SessionExpired(session_id)) => Some((session_id, true)), + Err(ft_sdk::auth::SessionIDError::SessionNotFound) => None, + Err(e) => return Err(e.into()) + } + } + }; + + match session { + Some((session_id, true)) => { // Session is expired, delete it and create a new one diesel::delete(fastn_session::table.filter(fastn_session::id.eq(session_id.as_str()))) .execute(conn)?; @@ -43,11 +62,11 @@ pub fn set_user_id( session_expiration_duration, )?) } - Some(_) => { + Some((session_id, false)) => { // Session is not expired, update the user ID diesel::update(fastn_session::table.filter(fastn_session::id.eq(session_id.as_str()))) .set(( - fastn_session::uid.eq(Some(user_id)), + fastn_session::uid.eq(Some(user_id.0)), fastn_session::updated_at.eq(now), )) .execute(conn)?; @@ -68,7 +87,7 @@ pub fn set_user_id( #[cfg(feature = "auth-provider")] pub fn create_with_user( conn: &mut ft_sdk::Connection, - user_id: i64, + ft_sdk::UserId(user_id): &ft_sdk::UserId, session_expiration_duration: Option, ) -> Result { use diesel::prelude::*; @@ -81,7 +100,7 @@ pub fn create_with_user( diesel::insert_into(fastn_session::table) .values(( fastn_session::id.eq(&session_id), - fastn_session::uid.eq(Some(user_id)), + fastn_session::uid.eq(Some(*user_id)), fastn_session::created_at.eq(ft_sdk::env::now()), fastn_session::updated_at.eq(ft_sdk::env::now()), fastn_session::expires_at.eq(session_expires_at), @@ -171,7 +190,7 @@ pub enum SessionIDError { #[error("session not found")] SessionNotFound, #[error("session expired")] - SessionExpired, + SessionExpired(String), #[error("failed to query db: {0:?}")] DatabaseError(#[from] diesel::result::Error), } @@ -203,13 +222,13 @@ impl SessionID { // Query to find the session ID and its expiration time for the given user ID. match fastn_session::table - .select((fastn_session::id, fastn_session::expires_at)) + .select((fastn_session::id, fastn_session::expires_at.nullable())) .filter(fastn_session::uid.eq(user_id.0)) .first::<(String, Option>)>(conn) { // If a session is found and it is expired, return a `SessionExpired` error. - Ok((_, Some(expires_at))) if expires_at < now => { - return Err(SessionIDError::SessionExpired) + Ok((id, Some(expires_at))) if expires_at < now => { + return Err(SessionIDError::SessionExpired(id)) } // If a valid session is found, return the session ID. Ok((id, _)) => Ok(SessionID(id)), From dd1abe348b7473978a65691fabd2d0819ab77dfd Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 10:46:34 +0530 Subject: [PATCH 10/24] Added validate session --- ft-sdk/src/auth/mod.rs | 46 +++++++++++++++++++++++++++++--------- ft-sdk/src/auth/session.rs | 44 +++++++++++++++++++++++++++--------- 2 files changed, 70 insertions(+), 20 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 4dec62a..32c956d 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -75,29 +75,33 @@ pub fn session_providers() -> Vec { todo!() } +/// Fetches user data based on a given session cookie. +/// +/// This function fetches user data based on a given session cookie if the +/// session cookie is found and is valid. If the session cookie not found, +/// it returns `None`. #[cfg(feature = "field-extractors")] pub fn ud( cookie: ft_sdk::Cookie, conn: &mut ft_sdk::Connection, ) -> Result, UserDataError> { - if let Some(v) = ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { - let mut v = v.splitn(4, ' '); - return Ok(Some(ft_sys::UserData { - id: v.next().unwrap().parse().unwrap(), - identity: v.next().unwrap_or_default().to_string(), - name: v.next().map(|v| v.to_string()).unwrap_or_default(), - email: v.next().map(|v| v.to_string()).unwrap_or_default(), - verified_email: true, - })); + // Check if debug user data is available, return it if found. + if let Some(ud) = get_debug_ud() { + return Ok(Some(ud)); } ft_sdk::println!("sid: {cookie}"); + // Extract the session ID from the cookie. let sid = match cookie.0 { Some(v) => v, None => return Ok(None), }; + // Validate the session using the extracted session ID. + ft_sdk::auth::SessionID(sid).validate_session(conn)?; + + // Query the database to get the user data associated with the session ID. let (UserId(id), identity, data) = match utils::user_data_by_query( conn, r#" @@ -116,6 +120,7 @@ pub fn ud( Err(e) => return Err(e), }; + // Extract the primary email from the user data, prefer verified emails. let email = data .verified_emails .first() @@ -124,19 +129,40 @@ pub fn ud( Ok(Some(ft_sys::UserData { id, - identity: identity.expect("user fetched from session cookie must have identity"), + identity: identity.ok_or_else(|| UserDataError::IdentityNotFound)?, name: data.name.unwrap_or_default(), email, verified_email: !data.verified_emails.is_empty(), })) } + +fn get_debug_ud() -> Option { + match ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { + Some(debug_logged_in) => { + let mut debug_logged_in = debug_logged_in.splitn(4, ' '); + Some(ft_sys::UserData { + id: debug_logged_in.next().unwrap().parse().unwrap(), + identity: debug_logged_in.next().unwrap_or_default().to_string(), + name: debug_logged_in.next().map(|v| v.to_string()).unwrap_or_default(), + email: debug_logged_in.next().map(|v| v.to_string()).unwrap_or_default(), + verified_email: true, + }) + }, + None => None + } +} + #[derive(Debug, thiserror::Error)] pub enum UserDataError { #[error("no data found for the provider")] NoDataFound, #[error("multiple rows found")] MultipleRowsFound, + #[error("session error: {0:?}")] + SessionError(#[from] ft_sdk::auth::SessionIDError), + #[error("user fetched from session cookie must have identity")] + IdentityNotFound, #[error("db error: {0:?}")] DatabaseError(#[from] diesel::result::Error), #[error("failed to deserialize data from db: {0:?}")] diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 9b396b7..8b44302 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -200,16 +200,6 @@ impl SessionID { /// /// This method queries the database to find a session associated with the /// given user ID. - /// - /// # Arguments - /// - /// * `conn` - A mutable reference to the database connection. - /// * `user_id` - The user ID for which the session ID needs to be retrieved. - /// - /// # Returns - /// - /// * `Ok(SessionID)` - If a valid session ID is found. - /// * `Err(SessionIDError)` - If an error occurs, such as session expiration or session not found. pub fn from_user_id( conn: &mut ft_sdk::Connection, user_id: &ft_sdk::auth::UserId, @@ -238,6 +228,40 @@ impl SessionID { Err(e) => return Err(e.into()), } } + + /// Validates if the session is active and not expired. + /// + /// This function checks the validity of the session associated with the session ID. + /// If the session is found and is not expired, it returns `Ok(())`. + /// If the session is expired or not found, it returns an appropriate error. + pub fn validate_session( + &self, + conn: &mut ft_sdk::Connection, + ) -> Result<(), SessionIDError> { + use diesel::prelude::*; + use ft_sdk::auth::fastn_session; + + // Get the current time. + let now = ft_sdk::env::now(); + + // Query to find the session ID and its expiration time for the given user ID. + match fastn_session::table + .select((fastn_session::id, fastn_session::expires_at.nullable())) + .filter(fastn_session::id.eq(&self.0)) + .first::<(String, Option>)>(conn) + { + // If a session is found and it is expired, return a `SessionExpired` error. + Ok((id, Some(expires_at))) if expires_at < now => { + return Err(SessionIDError::SessionExpired(id)) + } + // If a valid session is found, return. + Ok((_, _)) => Ok(()), + // If no session is found for the user ID, return a `SessionNotFound` error. + Err(diesel::NotFound) => return Err(SessionIDError::SessionNotFound), + // If any other error occurs during the query, return it. + Err(e) => return Err(e.into()), + } + } } /// Converts the current time to `cookie::time::OffsetDateTime`. From 2e515e50cc832430d6c9c2d0269e7b4eb545c454 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 10:50:55 +0530 Subject: [PATCH 11/24] Minor fix --- ft-sdk/src/auth/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 32c956d..6b77ebd 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -99,7 +99,7 @@ pub fn ud( }; // Validate the session using the extracted session ID. - ft_sdk::auth::SessionID(sid).validate_session(conn)?; + ft_sdk::auth::SessionID(sid.clone()).validate_session(conn)?; // Query the database to get the user data associated with the session ID. let (UserId(id), identity, data) = match utils::user_data_by_query( From 9521c853464b9aee65b50e85f8128b53b3ca91da Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 12:27:41 +0530 Subject: [PATCH 12/24] Added ud_from_session_key --- ft-sdk/src/auth/mod.rs | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 6b77ebd..49e4efc 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -85,21 +85,36 @@ pub fn ud( cookie: ft_sdk::Cookie, conn: &mut ft_sdk::Connection, ) -> Result, UserDataError> { - // Check if debug user data is available, return it if found. - if let Some(ud) = get_debug_ud() { - return Ok(Some(ud)); - } - - ft_sdk::println!("sid: {cookie}"); + ft_sdk::println!("session cookie: {cookie}"); // Extract the session ID from the cookie. - let sid = match cookie.0 { + let session_id = match cookie.0 { Some(v) => v, None => return Ok(None), }; + ud_from_session_key(&ft_sdk::auth::SessionID(session_id), conn) +} + + +/// Fetches user data based on a given session id. +/// +/// This function fetches user data based on a given session id if the +/// session is valid. If the session cookie not found, it returns `None`. +#[cfg(feature = "field-extractors")] +pub fn ud_from_session_key( + session_id: &ft_sdk::auth::SessionID, + conn: &mut ft_sdk::Connection, +) -> Result, UserDataError> { + // Check if debug user data is available, return it if found. + if let Some(ud) = get_debug_ud() { + return Ok(Some(ud)); + } + + ft_sdk::println!("sid: {}", session_id.0); + // Validate the session using the extracted session ID. - ft_sdk::auth::SessionID(sid.clone()).validate_session(conn)?; + session_id.validate_session(conn)?; // Query the database to get the user data associated with the session ID. let (UserId(id), identity, data) = match utils::user_data_by_query( @@ -113,7 +128,7 @@ pub fn ud( fastn_session.id = $1 AND fastn_user.id = fastn_session.uid "#, - sid.as_str(), + session_id.0.as_str(), ) { Ok(v) => v, Err(UserDataError::NoDataFound) => return Ok(None), @@ -137,6 +152,7 @@ pub fn ud( } +/// Check if debug user data is available, return it if found. fn get_debug_ud() -> Option { match ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { Some(debug_logged_in) => { From 9e84717fa3a8af3be4a1e72b0b29f5e7b357a457 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 12:33:41 +0530 Subject: [PATCH 13/24] Fix code documentation --- ft-sdk/src/auth/mod.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 49e4efc..5a2c980 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -78,8 +78,8 @@ pub fn session_providers() -> Vec { /// Fetches user data based on a given session cookie. /// /// This function fetches user data based on a given session cookie if the -/// session cookie is found and is valid. If the session cookie not found, -/// it returns `None`. +/// session cookie is found and is valid and user data is found. +/// If the session cookie not found, it returns `None`. #[cfg(feature = "field-extractors")] pub fn ud( cookie: ft_sdk::Cookie, @@ -100,7 +100,8 @@ pub fn ud( /// Fetches user data based on a given session id. /// /// This function fetches user data based on a given session id if the -/// session is valid. If the session cookie not found, it returns `None`. +/// session is valid and user data is found. +/// If the session cookie not found, it returns `None`. #[cfg(feature = "field-extractors")] pub fn ud_from_session_key( session_id: &ft_sdk::auth::SessionID, From 0fd8f3f369c812d950813a5667983419cf823654 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 13:14:52 +0530 Subject: [PATCH 14/24] Fix: set_user_id --- ft-sdk/src/auth/session.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 8b44302..f9beba6 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -31,19 +31,19 @@ pub fn set_user_id( Some(session_id) => { let existing_session_expires_at = fastn_session::table .select(fastn_session::expires_at.nullable()) - .filter(fastn_session::id.eq(session_id.as_str())) + .filter(fastn_session::id.eq(session_id.0.as_str())) .first::>>(conn) .optional()?; match existing_session_expires_at { - Some(Some(expires_at)) if expires_at < now => Some((session_id, true)), - Some(_) => Some((session_id, false)), + Some(Some(expires_at)) if expires_at < now => Some((session_id.0.clone(), true)), + Some(_) => Some((session_id.0.clone(), false)), None => None } }, None => { match ft_sdk::auth::SessionID::from_user_id(conn, user_id) { - Ok(session_id) => Some((session_id, false)), + Ok(session_id) => Some((session_id.0.clone(), false)), Err(ft_sdk::auth::SessionIDError::SessionExpired(session_id)) => Some((session_id, true)), Err(ft_sdk::auth::SessionIDError::SessionNotFound) => None, Err(e) => return Err(e.into()) @@ -92,6 +92,7 @@ pub fn create_with_user( ) -> Result { use diesel::prelude::*; use ft_sdk::auth::fastn_session; + use std::ops::Add; let session_id = generate_new_session_id(); let session_expires_at = From 63674dabe2549476b2bbe9f97007aaf1f1a70e41 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 13:25:06 +0530 Subject: [PATCH 15/24] Fixing errors --- ft-sdk/src/auth/session.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index f9beba6..3f32437 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -4,12 +4,8 @@ pub struct SessionID(pub String); #[cfg(feature = "auth-provider")] #[derive(Debug, thiserror::Error)] pub enum SetUserIDError { - #[error("session not found")] - SessionNotFound, - #[error("session expired")] - SessionExpired, - #[error("multiple sessions found")] - MultipleSessionsFound, + #[error("session id error: {0:?}")] + SessionIDError(#[from] ft_sdk::auth::SessionIDError), #[error("failed to query db: {0:?}")] DatabaseError(#[from] diesel::result::Error), } @@ -155,9 +151,9 @@ pub fn set_session_cookie( // If the session does not have an expiration time. Ok(None) => cookie::time::Duration::seconds(34560000), // If the session has an expiration time and it is in the past. - Ok(_) => return Err(SetUserIDError::SessionExpired.into()), + Ok(_) => return Err(SessionIDError::SessionExpired(session_id.clone()).into()), // If the session is not found. - Err(diesel::NotFound) => return Err(SetUserIDError::SessionNotFound.into()), + Err(diesel::NotFound) => return Err(SessionIDError::SessionNotFound.into()), // If there is an error querying the database. Err(e) => return Err(e.into()), }; From 514616db68786f78285b319c68f071968da3b94b Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 13:26:18 +0530 Subject: [PATCH 16/24] Minor fix --- ft-sdk/src/auth/session.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index 3f32437..c0160fc 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -140,7 +140,7 @@ pub fn set_session_cookie( // Query to check if the session exists and get its expiration time. let max_age = match fastn_session::table .select(fastn_session::expires_at.nullable()) - .filter(fastn_session::id.eq(session_id)) + .filter(fastn_session::id.eq(&session_id)) .first::>>(conn) { // If the session has an expiration time and it is in the future. From 8d8e6cfbda486be49150ab2db973dcb472158e1f Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 14:57:58 +0530 Subject: [PATCH 17/24] Added mobile <-> email hack --- Cargo.lock | 9 +++++++++ Cargo.toml | 3 ++- ft-sdk/src/auth/mod.rs | 14 ++++++++++++-- stripe/Cargo.toml | 14 ++++++++++++++ stripe/src/lib.rs | 14 ++++++++++++++ 5 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 stripe/Cargo.toml create mode 100644 stripe/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index bf7de12..e3ec633 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -520,6 +520,15 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +[[package]] +name = "stripe" +version = "0.1.0" +dependencies = [ + "ft-sdk", + "http", + "thiserror", +] + [[package]] name = "syn" version = "1.0.109" diff --git a/Cargo.toml b/Cargo.toml index ccd13d7..b92e7d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ members = [ "ft-derive", "ft-sdk", "ft-sys", - "ft-sys-shared", + "ft-sys-shared", "stripe", ] exclude = ["examples", "f"] resolver = "2" @@ -44,6 +44,7 @@ uuid = { version = "1.8", default-features = false, features = ["v8"] } ft-sys-shared = { path = "ft-sys-shared", version = "0.1.2" } ft-derive = { path = "ft-derive", version = "0.1.1" } ft-sys = { path = "ft-sys", version = "0.1.3" } +ft-sdk = { path = "ft-sdk", version = "0.1.12" } [workspace.dependencies.rusqlite] diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index 5a2c980..df72914 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -93,7 +93,7 @@ pub fn ud( None => return Ok(None), }; - ud_from_session_key(&ft_sdk::auth::SessionID(session_id), conn) + ud_from_session_key(conn, &ft_sdk::auth::SessionID(session_id)) } @@ -104,8 +104,8 @@ pub fn ud( /// If the session cookie not found, it returns `None`. #[cfg(feature = "field-extractors")] pub fn ud_from_session_key( - session_id: &ft_sdk::auth::SessionID, conn: &mut ft_sdk::Connection, + session_id: &ft_sdk::auth::SessionID, ) -> Result, UserDataError> { // Check if debug user data is available, return it if found. if let Some(ud) = get_debug_ud() { @@ -170,6 +170,16 @@ fn get_debug_ud() -> Option { } } + +// This is hack to keep mobile number as email. +pub fn mobile_to_email(mobile_number: &str) -> String { + format!("{mobile_number}@mobile.fifthtry.com") +} +// This is hack to keep mobile number as email. +pub fn mobile_from_email(email: &str) -> Option { + email.strip_suffix("@mobile.fifthtry.com").map(|s| s.to_string()) +} + #[derive(Debug, thiserror::Error)] pub enum UserDataError { #[error("no data found for the provider")] diff --git a/stripe/Cargo.toml b/stripe/Cargo.toml new file mode 100644 index 0000000..7e26862 --- /dev/null +++ b/stripe/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "stripe" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +description.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true + +[dependencies] +thiserror.workspace = true +http.workspace = true +ft-sdk.workspace = true \ No newline at end of file diff --git a/stripe/src/lib.rs b/stripe/src/lib.rs new file mode 100644 index 0000000..f0663bf --- /dev/null +++ b/stripe/src/lib.rs @@ -0,0 +1,14 @@ +pub struct CustomerID(pub String); + +pub fn create_customer(conn: &mut ft_sdk::Connection, session_id: &ft_sdk::auth::SessionID) -> Result { + let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)?.ok_or_else(|| CreateCustomerError::UserNotFound)?; + todo!() +} + +#[derive(thiserror::Error, Debug)] +pub enum CreateCustomerError { + #[error("user data error: {0:?}")] + UserData(#[from] ft_sdk::auth::UserDataError), + #[error("user not found")] + UserNotFound +} From d9eb55f674a4fdc35c3ac39ad7750914ae1b0ed5 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 15:42:27 +0530 Subject: [PATCH 18/24] Added stripe::create_customer --- Cargo.lock | 5 +++ ft-sdk/src/auth/mod.rs | 25 +++++++++------ ft-sdk/src/auth/provider.rs | 2 +- ft-sdk/src/auth/session.rs | 23 ++++++-------- stripe/Cargo.toml | 7 ++++- stripe/src/lib.rs | 61 ++++++++++++++++++++++++++++++++++--- 6 files changed, 94 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e3ec633..6aaaaa6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,8 +524,13 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" name = "stripe" version = "0.1.0" dependencies = [ + "bytes", "ft-sdk", + "ft-sys", "http", + "serde", + "serde_json", + "serde_urlencoded", "thiserror", ] diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index df72914..f2de86e 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -6,9 +6,9 @@ mod utils; pub use ft_sys_shared::SESSION_KEY; pub use schema::{fastn_session, fastn_user}; -pub use session::{SessionID, SessionIDError}; #[cfg(feature = "auth-provider")] -pub use session::{set_session_cookie, expire_session_cookie}; +pub use session::{expire_session_cookie, set_session_cookie}; +pub use session::{SessionID, SessionIDError}; pub use utils::{user_data_by_query, Counter}; #[derive(Clone, Debug)] @@ -96,7 +96,6 @@ pub fn ud( ud_from_session_key(conn, &ft_sdk::auth::SessionID(session_id)) } - /// Fetches user data based on a given session id. /// /// This function fetches user data based on a given session id if the @@ -152,7 +151,6 @@ pub fn ud_from_session_key( })) } - /// Check if debug user data is available, return it if found. fn get_debug_ud() -> Option { match ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { @@ -161,23 +159,30 @@ fn get_debug_ud() -> Option { Some(ft_sys::UserData { id: debug_logged_in.next().unwrap().parse().unwrap(), identity: debug_logged_in.next().unwrap_or_default().to_string(), - name: debug_logged_in.next().map(|v| v.to_string()).unwrap_or_default(), - email: debug_logged_in.next().map(|v| v.to_string()).unwrap_or_default(), + name: debug_logged_in + .next() + .map(|v| v.to_string()) + .unwrap_or_default(), + email: debug_logged_in + .next() + .map(|v| v.to_string()) + .unwrap_or_default(), verified_email: true, }) - }, - None => None + } + None => None, } } - // This is hack to keep mobile number as email. pub fn mobile_to_email(mobile_number: &str) -> String { format!("{mobile_number}@mobile.fifthtry.com") } // This is hack to keep mobile number as email. pub fn mobile_from_email(email: &str) -> Option { - email.strip_suffix("@mobile.fifthtry.com").map(|s| s.to_string()) + email + .strip_suffix("@mobile.fifthtry.com") + .map(|s| s.to_string()) } #[derive(Debug, thiserror::Error)] diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index 8ec013c..78cde80 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -343,7 +343,7 @@ pub fn login_with_custom_session_expiration( session_id, user_id, session_expiration_duration, - )?) + )?), } } diff --git a/ft-sdk/src/auth/session.rs b/ft-sdk/src/auth/session.rs index c0160fc..3c2d017 100644 --- a/ft-sdk/src/auth/session.rs +++ b/ft-sdk/src/auth/session.rs @@ -34,17 +34,17 @@ pub fn set_user_id( match existing_session_expires_at { Some(Some(expires_at)) if expires_at < now => Some((session_id.0.clone(), true)), Some(_) => Some((session_id.0.clone(), false)), - None => None - } - }, - None => { - match ft_sdk::auth::SessionID::from_user_id(conn, user_id) { - Ok(session_id) => Some((session_id.0.clone(), false)), - Err(ft_sdk::auth::SessionIDError::SessionExpired(session_id)) => Some((session_id, true)), - Err(ft_sdk::auth::SessionIDError::SessionNotFound) => None, - Err(e) => return Err(e.into()) + None => None, } } + None => match ft_sdk::auth::SessionID::from_user_id(conn, user_id) { + Ok(session_id) => Some((session_id.0.clone(), false)), + Err(ft_sdk::auth::SessionIDError::SessionExpired(session_id)) => { + Some((session_id, true)) + } + Err(ft_sdk::auth::SessionIDError::SessionNotFound) => None, + Err(e) => return Err(e.into()), + }, }; match session { @@ -231,10 +231,7 @@ impl SessionID { /// This function checks the validity of the session associated with the session ID. /// If the session is found and is not expired, it returns `Ok(())`. /// If the session is expired or not found, it returns an appropriate error. - pub fn validate_session( - &self, - conn: &mut ft_sdk::Connection, - ) -> Result<(), SessionIDError> { + pub fn validate_session(&self, conn: &mut ft_sdk::Connection) -> Result<(), SessionIDError> { use diesel::prelude::*; use ft_sdk::auth::fastn_session; diff --git a/stripe/Cargo.toml b/stripe/Cargo.toml index 7e26862..2833c04 100644 --- a/stripe/Cargo.toml +++ b/stripe/Cargo.toml @@ -11,4 +11,9 @@ homepage.workspace = true [dependencies] thiserror.workspace = true http.workspace = true -ft-sdk.workspace = true \ No newline at end of file +ft-sdk.workspace = true +bytes.workspace = true +serde.workspace = true +serde_json.workspace = true +serde_urlencoded.workspace = true +ft-sys.workspace = true diff --git a/stripe/src/lib.rs b/stripe/src/lib.rs index f0663bf..ff6e5be 100644 --- a/stripe/src/lib.rs +++ b/stripe/src/lib.rs @@ -1,8 +1,57 @@ pub struct CustomerID(pub String); -pub fn create_customer(conn: &mut ft_sdk::Connection, session_id: &ft_sdk::auth::SessionID) -> Result { - let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)?.ok_or_else(|| CreateCustomerError::UserNotFound)?; - todo!() +pub fn create_customer( + conn: &mut ft_sdk::Connection, + session_id: &ft_sdk::auth::SessionID, + token: &str, +) -> Result { + let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)? + .ok_or_else(|| CreateCustomerError::UserNotFound)?; + + let body = match ft_sdk::auth::mobile_from_email(user_data.email.as_str()) { + Some(phone) => serde_json::json!({"phone": phone}), + None => serde_json::json!({"email": user_data.email}), + }; + + call_create_customer_api(token, &body) +} + +fn call_create_customer_api( + token: &str, + body: &serde_json::Value, +) -> Result { + let authorization_header = format!("Bearer {}", token); + + // Serialize the struct to URL-encoded format + let body = serde_urlencoded::to_string(body).unwrap(); + + let client = http::Request::builder(); + let request = client + .method("POST") + .uri("https://api.stripe.com/v1/customers") + .header("Authorization", authorization_header) + .header("Content-Type", "application/x-www-form-urlencoded") + .body(bytes::Bytes::from(body))?; + + let response = ft_sdk::http::send(request).unwrap(); //todo: remove unwrap() + + #[derive(Debug, serde::Deserialize)] + struct Response { + id: String, + } + + let response_body = String::from_utf8_lossy(response.body()).to_string(); + + if response.status().is_success() { + let api_response: Response = serde_json::from_str(response_body.as_str()).unwrap(); + + ft_sdk::println!("Create customer API Response: {:?}", api_response); + + Ok(CustomerID(api_response.id)) + } else { + ft_sdk::println!("Request failed with status: {}", response.status()); + Err(CreateCustomerError::CannotCreateCustomer(response_body)) + } } #[derive(thiserror::Error, Debug)] @@ -10,5 +59,9 @@ pub enum CreateCustomerError { #[error("user data error: {0:?}")] UserData(#[from] ft_sdk::auth::UserDataError), #[error("user not found")] - UserNotFound + UserNotFound, + #[error("http error: {0:?}")] + HttpError(#[from] http::Error), + #[error("Cannot create customer: {0}")] + CannotCreateCustomer(String), } From 29bb8a4bf75ff0cbd9937713175d265cc0796125 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 16:13:42 +0530 Subject: [PATCH 19/24] minor changes --- ft-sdk/src/auth/mod.rs | 6 ++++++ ft-sdk/src/auth/provider.rs | 2 -- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index f2de86e..c247d80 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -86,6 +86,10 @@ pub fn ud( conn: &mut ft_sdk::Connection, ) -> Result, UserDataError> { ft_sdk::println!("session cookie: {cookie}"); + // Check if debug user data is available, return it if found. + if let Some(ud) = get_debug_ud() { + return Ok(Some(ud)); + } // Extract the session ID from the cookie. let session_id = match cookie.0 { @@ -151,6 +155,8 @@ pub fn ud_from_session_key( })) } + + /// Check if debug user data is available, return it if found. fn get_debug_ud() -> Option { match ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index 78cde80..e55fafb 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -22,8 +22,6 @@ //! username etc. The UI will have been provided by the auth provider, or some other generic auth //! setting package. -use crate::auth::fastn_session; -use crate::auth::session::SetUserIDError; /// In the current session, we have zero or more scopes dropped by different auth /// providers that have been used so far. Each auth provider sdk also provides some From b2c323353cb980473171d5328fb1cac0566835ce Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 16:25:43 +0530 Subject: [PATCH 20/24] Review changes --- Cargo.toml | 3 ++- ft-sdk/src/auth/mod.rs | 2 -- ft-sdk/src/auth/provider.rs | 1 - {stripe => ft-stripe}/Cargo.toml | 2 +- {stripe => ft-stripe}/src/lib.rs | 4 ++-- 5 files changed, 5 insertions(+), 7 deletions(-) rename {stripe => ft-stripe}/Cargo.toml (95%) rename {stripe => ft-stripe}/src/lib.rs (96%) diff --git a/Cargo.toml b/Cargo.toml index b92e7d6..06b0dcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,8 @@ members = [ "ft-derive", "ft-sdk", "ft-sys", - "ft-sys-shared", "stripe", + "ft-sys-shared", + "ft-stripe", ] exclude = ["examples", "f"] resolver = "2" diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index c247d80..cdefff1 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -155,8 +155,6 @@ pub fn ud_from_session_key( })) } - - /// Check if debug user data is available, return it if found. fn get_debug_ud() -> Option { match ft_sys::env::var("DEBUG_LOGGED_IN".to_string()) { diff --git a/ft-sdk/src/auth/provider.rs b/ft-sdk/src/auth/provider.rs index e55fafb..d7312a9 100644 --- a/ft-sdk/src/auth/provider.rs +++ b/ft-sdk/src/auth/provider.rs @@ -22,7 +22,6 @@ //! username etc. The UI will have been provided by the auth provider, or some other generic auth //! setting package. - /// In the current session, we have zero or more scopes dropped by different auth /// providers that have been used so far. Each auth provider sdk also provides some /// APIs that require certain scopes to be present. Before calling those APIs, the diff --git a/stripe/Cargo.toml b/ft-stripe/Cargo.toml similarity index 95% rename from stripe/Cargo.toml rename to ft-stripe/Cargo.toml index 2833c04..b9cf0e8 100644 --- a/stripe/Cargo.toml +++ b/ft-stripe/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "stripe" +name = "ft-stripe" version = "0.1.0" authors.workspace = true edition.workspace = true diff --git a/stripe/src/lib.rs b/ft-stripe/src/lib.rs similarity index 96% rename from stripe/src/lib.rs rename to ft-stripe/src/lib.rs index ff6e5be..d5b1ccd 100644 --- a/stripe/src/lib.rs +++ b/ft-stripe/src/lib.rs @@ -3,7 +3,7 @@ pub struct CustomerID(pub String); pub fn create_customer( conn: &mut ft_sdk::Connection, session_id: &ft_sdk::auth::SessionID, - token: &str, + secret_token: &str, ) -> Result { let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)? .ok_or_else(|| CreateCustomerError::UserNotFound)?; @@ -13,7 +13,7 @@ pub fn create_customer( None => serde_json::json!({"email": user_data.email}), }; - call_create_customer_api(token, &body) + call_create_customer_api(secret_token, &body) } fn call_create_customer_api( From 144fb21dd2e9ec1c8e4043621ce521b9f6555800 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Wed, 19 Jun 2024 16:57:16 +0530 Subject: [PATCH 21/24] Remove hack to keep mobile --- ft-sdk/src/auth/mod.rs | 11 ----------- ft-stripe/src/lib.rs | 9 ++++++++- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/ft-sdk/src/auth/mod.rs b/ft-sdk/src/auth/mod.rs index cdefff1..ce6028e 100644 --- a/ft-sdk/src/auth/mod.rs +++ b/ft-sdk/src/auth/mod.rs @@ -178,17 +178,6 @@ fn get_debug_ud() -> Option { } } -// This is hack to keep mobile number as email. -pub fn mobile_to_email(mobile_number: &str) -> String { - format!("{mobile_number}@mobile.fifthtry.com") -} -// This is hack to keep mobile number as email. -pub fn mobile_from_email(email: &str) -> Option { - email - .strip_suffix("@mobile.fifthtry.com") - .map(|s| s.to_string()) -} - #[derive(Debug, thiserror::Error)] pub enum UserDataError { #[error("no data found for the provider")] diff --git a/ft-stripe/src/lib.rs b/ft-stripe/src/lib.rs index d5b1ccd..0383537 100644 --- a/ft-stripe/src/lib.rs +++ b/ft-stripe/src/lib.rs @@ -8,7 +8,7 @@ pub fn create_customer( let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)? .ok_or_else(|| CreateCustomerError::UserNotFound)?; - let body = match ft_sdk::auth::mobile_from_email(user_data.email.as_str()) { + let body = match mobile_from_email(user_data.email.as_str()) { Some(phone) => serde_json::json!({"phone": phone}), None => serde_json::json!({"email": user_data.email}), }; @@ -65,3 +65,10 @@ pub enum CreateCustomerError { #[error("Cannot create customer: {0}")] CannotCreateCustomer(String), } + +// This is hack to keep mobile number as email. We need to soon remove this. +fn mobile_from_email(email: &str) -> Option { + email + .strip_suffix("@mobile.fifthtry.com") + .map(|s| s.to_string()) +} \ No newline at end of file From a4164c677a9be98a2866611f689f0fff298b1c5b Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Thu, 20 Jun 2024 10:33:42 +0530 Subject: [PATCH 22/24] Added ft-stripe sdk --- Cargo.lock | 28 +- ft-stripe/Cargo.toml | 1 + ft-stripe/src/client.rs | 167 ++ ft-stripe/src/ids.rs | 626 +++++++ ft-stripe/src/lib.rs | 43 +- ft-stripe/src/params.rs | 253 +++ ft-stripe/src/payment_source.rs | 108 ++ ft-stripe/src/resources.rs | 304 ++++ ft-stripe/src/resources/account.rs | 1420 ++++++++++++++++ ft-stripe/src/resources/alipay_account.rs | 75 + ft-stripe/src/resources/application.rs | 28 + ft-stripe/src/resources/application_fee.rs | 145 ++ ft-stripe/src/resources/balance.rs | 76 + .../src/resources/balance_transaction.rs | 320 ++++ .../src/resources/balance_transaction_ext.rs | 111 ++ ft-stripe/src/resources/bank_account.rs | 96 ++ ft-stripe/src/resources/bank_account_ext.rs | 36 + ft-stripe/src/resources/card.rs | 217 +++ ft-stripe/src/resources/charge.rs | 626 +++++++ ft-stripe/src/resources/charge_ext.rs | 55 + ft-stripe/src/resources/checkout_session.rs | 1042 ++++++++++++ .../resources/connect_collection_transfer.rs | 33 + ft-stripe/src/resources/coupon.rs | 318 ++++ ft-stripe/src/resources/currency.rs | 463 +++++ ft-stripe/src/resources/customer.rs | 678 ++++++++ ft-stripe/src/resources/customer_ext.rs | 83 + ft-stripe/src/resources/discount.rs | 46 + ft-stripe/src/resources/dispute.rs | 338 ++++ ft-stripe/src/resources/event.rs | 403 +++++ ft-stripe/src/resources/fee_refund.rs | 52 + ft-stripe/src/resources/file.rs | 174 ++ ft-stripe/src/resources/file_link.rs | 204 +++ ft-stripe/src/resources/invoice.rs | 902 ++++++++++ ft-stripe/src/resources/invoice_ext.rs | 72 + ft-stripe/src/resources/invoiceitem.rs | 452 +++++ .../src/resources/issuing_authorization.rs | 207 +++ .../resources/issuing_authorization_ext.rs | 69 + ft-stripe/src/resources/issuing_card.rs | 312 ++++ ft-stripe/src/resources/issuing_card_ext.rs | 125 ++ ft-stripe/src/resources/issuing_cardholder.rs | 307 ++++ ft-stripe/src/resources/issuing_dispute.rs | 27 + .../src/resources/issuing_dispute_ext.rs | 63 + .../src/resources/issuing_merchant_data.rs | 325 ++++ .../src/resources/issuing_transaction.rs | 210 +++ .../src/resources/issuing_transaction_ext.rs | 38 + ft-stripe/src/resources/item.rs | 62 + ft-stripe/src/resources/line_item.rs | 138 ++ ft-stripe/src/resources/line_item_ext.rs | 45 + ft-stripe/src/resources/mandate.rs | 233 +++ ft-stripe/src/resources/order.rs | 522 ++++++ ft-stripe/src/resources/order_ext.rs | 34 + ft-stripe/src/resources/order_item.rs | 50 + ft-stripe/src/resources/order_return.rs | 120 ++ ft-stripe/src/resources/payment_intent.rs | 601 +++++++ ft-stripe/src/resources/payment_method.rs | 948 +++++++++++ ft-stripe/src/resources/payment_method_ext.rs | 32 + ft-stripe/src/resources/payment_source.rs | 114 ++ ft-stripe/src/resources/payout.rs | 382 +++++ ft-stripe/src/resources/payout_ext.rs | 29 + ft-stripe/src/resources/person.rs | 397 +++++ ft-stripe/src/resources/placeholders.rs | 598 +++++++ ft-stripe/src/resources/plan.rs | 674 ++++++++ ft-stripe/src/resources/platform_tax_fee.rs | 28 + ft-stripe/src/resources/price.rs | 920 ++++++++++ ft-stripe/src/resources/product.rs | 500 ++++++ ft-stripe/src/resources/recipient.rs | 325 ++++ ft-stripe/src/resources/refund.rs | 286 ++++ .../src/resources/reserve_transaction.rs | 32 + ft-stripe/src/resources/review.rs | 240 +++ ft-stripe/src/resources/review_ext.rs | 38 + .../src/resources/scheduled_query_run.rs | 61 + ft-stripe/src/resources/setup_intent.rs | 654 +++++++ ft-stripe/src/resources/sku.rs | 374 ++++ ft-stripe/src/resources/source.rs | 1511 +++++++++++++++++ ft-stripe/src/resources/source_ext.rs | 129 ++ ft-stripe/src/resources/subscription.rs | 1201 +++++++++++++ ft-stripe/src/resources/subscription_ext.rs | 43 + ft-stripe/src/resources/subscription_item.rs | 480 ++++++ .../src/resources/subscription_item_ext.rs | 161 ++ .../src/resources/subscription_schedule.rs | 820 +++++++++ .../src/resources/tax_deducted_at_source.rs | 31 + ft-stripe/src/resources/tax_id.rs | 185 ++ ft-stripe/src/resources/tax_rate.rs | 247 +++ ft-stripe/src/resources/token.rs | 229 +++ ft-stripe/src/resources/token_ext.rs | 34 + ft-stripe/src/resources/topup.rs | 271 +++ ft-stripe/src/resources/transfer.rs | 303 ++++ ft-stripe/src/resources/transfer_reversal.rs | 60 + ft-stripe/src/resources/types.rs | 725 ++++++++ ft-stripe/src/resources/webhook_endpoint.rs | 744 ++++++++ .../src/resources/webhook_endpoint_ext.rs | 30 + ft-stripe/src/types.rs | 36 + 92 files changed, 27333 insertions(+), 22 deletions(-) create mode 100644 ft-stripe/src/client.rs create mode 100644 ft-stripe/src/ids.rs create mode 100644 ft-stripe/src/params.rs create mode 100644 ft-stripe/src/payment_source.rs create mode 100644 ft-stripe/src/resources.rs create mode 100644 ft-stripe/src/resources/account.rs create mode 100644 ft-stripe/src/resources/alipay_account.rs create mode 100644 ft-stripe/src/resources/application.rs create mode 100644 ft-stripe/src/resources/application_fee.rs create mode 100644 ft-stripe/src/resources/balance.rs create mode 100644 ft-stripe/src/resources/balance_transaction.rs create mode 100644 ft-stripe/src/resources/balance_transaction_ext.rs create mode 100644 ft-stripe/src/resources/bank_account.rs create mode 100644 ft-stripe/src/resources/bank_account_ext.rs create mode 100644 ft-stripe/src/resources/card.rs create mode 100644 ft-stripe/src/resources/charge.rs create mode 100644 ft-stripe/src/resources/charge_ext.rs create mode 100644 ft-stripe/src/resources/checkout_session.rs create mode 100644 ft-stripe/src/resources/connect_collection_transfer.rs create mode 100644 ft-stripe/src/resources/coupon.rs create mode 100644 ft-stripe/src/resources/currency.rs create mode 100644 ft-stripe/src/resources/customer.rs create mode 100644 ft-stripe/src/resources/customer_ext.rs create mode 100644 ft-stripe/src/resources/discount.rs create mode 100644 ft-stripe/src/resources/dispute.rs create mode 100644 ft-stripe/src/resources/event.rs create mode 100644 ft-stripe/src/resources/fee_refund.rs create mode 100644 ft-stripe/src/resources/file.rs create mode 100644 ft-stripe/src/resources/file_link.rs create mode 100644 ft-stripe/src/resources/invoice.rs create mode 100644 ft-stripe/src/resources/invoice_ext.rs create mode 100644 ft-stripe/src/resources/invoiceitem.rs create mode 100644 ft-stripe/src/resources/issuing_authorization.rs create mode 100644 ft-stripe/src/resources/issuing_authorization_ext.rs create mode 100644 ft-stripe/src/resources/issuing_card.rs create mode 100644 ft-stripe/src/resources/issuing_card_ext.rs create mode 100644 ft-stripe/src/resources/issuing_cardholder.rs create mode 100644 ft-stripe/src/resources/issuing_dispute.rs create mode 100644 ft-stripe/src/resources/issuing_dispute_ext.rs create mode 100644 ft-stripe/src/resources/issuing_merchant_data.rs create mode 100644 ft-stripe/src/resources/issuing_transaction.rs create mode 100644 ft-stripe/src/resources/issuing_transaction_ext.rs create mode 100644 ft-stripe/src/resources/item.rs create mode 100644 ft-stripe/src/resources/line_item.rs create mode 100644 ft-stripe/src/resources/line_item_ext.rs create mode 100644 ft-stripe/src/resources/mandate.rs create mode 100644 ft-stripe/src/resources/order.rs create mode 100644 ft-stripe/src/resources/order_ext.rs create mode 100644 ft-stripe/src/resources/order_item.rs create mode 100644 ft-stripe/src/resources/order_return.rs create mode 100644 ft-stripe/src/resources/payment_intent.rs create mode 100644 ft-stripe/src/resources/payment_method.rs create mode 100644 ft-stripe/src/resources/payment_method_ext.rs create mode 100644 ft-stripe/src/resources/payment_source.rs create mode 100644 ft-stripe/src/resources/payout.rs create mode 100644 ft-stripe/src/resources/payout_ext.rs create mode 100644 ft-stripe/src/resources/person.rs create mode 100644 ft-stripe/src/resources/placeholders.rs create mode 100644 ft-stripe/src/resources/plan.rs create mode 100644 ft-stripe/src/resources/platform_tax_fee.rs create mode 100644 ft-stripe/src/resources/price.rs create mode 100644 ft-stripe/src/resources/product.rs create mode 100644 ft-stripe/src/resources/recipient.rs create mode 100644 ft-stripe/src/resources/refund.rs create mode 100644 ft-stripe/src/resources/reserve_transaction.rs create mode 100644 ft-stripe/src/resources/review.rs create mode 100644 ft-stripe/src/resources/review_ext.rs create mode 100644 ft-stripe/src/resources/scheduled_query_run.rs create mode 100644 ft-stripe/src/resources/setup_intent.rs create mode 100644 ft-stripe/src/resources/sku.rs create mode 100644 ft-stripe/src/resources/source.rs create mode 100644 ft-stripe/src/resources/source_ext.rs create mode 100644 ft-stripe/src/resources/subscription.rs create mode 100644 ft-stripe/src/resources/subscription_ext.rs create mode 100644 ft-stripe/src/resources/subscription_item.rs create mode 100644 ft-stripe/src/resources/subscription_item_ext.rs create mode 100644 ft-stripe/src/resources/subscription_schedule.rs create mode 100644 ft-stripe/src/resources/tax_deducted_at_source.rs create mode 100644 ft-stripe/src/resources/tax_id.rs create mode 100644 ft-stripe/src/resources/tax_rate.rs create mode 100644 ft-stripe/src/resources/token.rs create mode 100644 ft-stripe/src/resources/token_ext.rs create mode 100644 ft-stripe/src/resources/topup.rs create mode 100644 ft-stripe/src/resources/transfer.rs create mode 100644 ft-stripe/src/resources/transfer_reversal.rs create mode 100644 ft-stripe/src/resources/types.rs create mode 100644 ft-stripe/src/resources/webhook_endpoint.rs create mode 100644 ft-stripe/src/resources/webhook_endpoint_ext.rs create mode 100644 ft-stripe/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 6aaaaa6..4ea7c59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,6 +214,21 @@ dependencies = [ "uuid", ] +[[package]] +name = "ft-stripe" +version = "0.1.0" +dependencies = [ + "bytes", + "ft-sdk", + "ft-sys", + "http", + "serde", + "serde_json", + "serde_urlencoded", + "smol_str", + "thiserror", +] + [[package]] name = "ft-sys" version = "0.1.3" @@ -521,17 +536,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] -name = "stripe" -version = "0.1.0" +name = "smol_str" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fad6c857cbab2627dcf01ec85a623ca4e7dcb5691cbaa3d7fb7653671f0d09c9" dependencies = [ - "bytes", - "ft-sdk", - "ft-sys", - "http", "serde", - "serde_json", - "serde_urlencoded", - "thiserror", ] [[package]] diff --git a/ft-stripe/Cargo.toml b/ft-stripe/Cargo.toml index b9cf0e8..9869ad9 100644 --- a/ft-stripe/Cargo.toml +++ b/ft-stripe/Cargo.toml @@ -17,3 +17,4 @@ serde.workspace = true serde_json.workspace = true serde_urlencoded.workspace = true ft-sys.workspace = true +smol_str = "0.1" diff --git a/ft-stripe/src/client.rs b/ft-stripe/src/client.rs new file mode 100644 index 0000000..aeb7365 --- /dev/null +++ b/ft-stripe/src/client.rs @@ -0,0 +1,167 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c + +use serde::de::DeserializeOwned; +use crate::params::{AppInfo, Headers}; +use crate::resources::ApiVersion; +use crate::config::Response; +use http::header::{HeaderMap, HeaderName, HeaderValue}; + +#[derive(Clone)] +pub struct Client { + host: String, + secret_key: String, + headers: Headers, + app_info: Option, +} + +impl Client { + /// Creates a new client pointed to `https://api.stripe.com/` + pub fn new(secret_key: impl Into) -> Client { + Client::from_url("https://api.stripe.com/", secret_key) + } + + /// Creates a new client posted to a custom `scheme://host/` + pub fn from_url(scheme_host: impl Into, secret_key: impl Into) -> Client { + let url = scheme_host.into(); + let host = if url.ends_with('/') { format!("{}v1", url) } else { format!("{}/v1", url) }; + let mut headers = Headers::default(); + // TODO: Automatically determine the latest supported api version in codegen? + headers.stripe_version = Some(ApiVersion::V2019_09_09); + + Client { + host, + secret_key: secret_key.into(), + headers, + app_info: Some(AppInfo::default()), + } + } + + + /// Clones a new client with different headers. + /// + /// This is the recommended way to send requests for many different Stripe accounts + /// or with different Meta, Extra, and Expand headers while using the same secret key. + pub fn with_headers(&self, headers: Headers) -> Client { + let mut client = self.clone(); + client.headers = headers; + client + } + + pub fn set_app_info(&mut self, name: String, version: Option, url: Option) { + self.app_info = Some(AppInfo { name, url, version }); + } + + /// Sets a value for the Stripe-Account header + /// + /// This is recommended if you are acting as only one Account for the lifetime of the client. + /// Otherwise, prefer `client.with(Headers{stripe_account: "acct_ABC", ..})`. + pub fn set_stripe_account>(&mut self, account_id: S) { + self.headers.stripe_account = Some(account_id.into()); + } + + /// Make a `GET` http request with just a path + pub fn get(&self, path: &str) -> Response { + todo!() + } + + /// Make a `GET` http request with url query parameters + pub fn get_query( + &self, + path: &str, + params: P, + ) -> Response { + todo!() + } + + /// Make a `DELETE` http request with just a path + pub fn delete(&self, path: &str) -> Response { + todo!() + } + + /// Make a `DELETE` http request with url query parameters + pub fn delete_query( + &self, + path: &str, + params: P, + ) -> Response { + todo!() + } + + /// Make a `POST` http request with just a path + pub fn post(&self, path: &str) -> Response { + todo!() + } + + /// Make a `POST` http request with urlencoded body + pub fn post_form( + &self, + path: &str, + form: F, + ) -> Response { + todo!() + } + + fn url(&self, path: &str) -> String { + format!("{}/{}", self.host, path.trim_start_matches('/')) + } + + // fn url_with_params(&self, path: &str, params: P) -> Result { + //todo: Result + fn url_with_params(&self, path: &str, params: P) -> Result { + todo!() + } + + fn headers(&self) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + HeaderName::from_static("authorization"), + HeaderValue::from_str(&format!("Bearer {}", self.secret_key)).unwrap(), + ); + if let Some(account) = &self.headers.stripe_account { + headers.insert( + HeaderName::from_static("stripe-account"), + HeaderValue::from_str(account).unwrap(), + ); + } + if let Some(client_id) = &self.headers.client_id { + headers.insert( + HeaderName::from_static("client-id"), + HeaderValue::from_str(client_id).unwrap(), + ); + } + if let Some(stripe_version) = &self.headers.stripe_version { + headers.insert( + HeaderName::from_static("stripe-version"), + HeaderValue::from_str(stripe_version.as_str()).unwrap(), + ); + } + const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION"); + let user_agent: String = format!("Stripe/v3 RustBindings/{}", CRATE_VERSION); + if let Some(app_info) = &self.app_info { + let formatted: String = format_app_info(app_info); + let user_agent_app_info: String = + format!("{} {}", user_agent, formatted).trim().to_owned(); + headers.insert( + HeaderName::from_static("user-agent"), + HeaderValue::from_str(user_agent_app_info.as_str()).unwrap(), + ); + } else { + headers.insert( + HeaderName::from_static("user-agent"), + HeaderValue::from_str(user_agent.as_str()).unwrap(), + ); + }; + headers + } +} + + +fn format_app_info(info: &AppInfo) -> String { + let formatted: String = match (&info.version, &info.url) { + (Some(a), Some(b)) => format!("{}/{} ({})", &info.name, a, b), + (Some(a), None) => format!("{}/{}", &info.name, a), + (None, Some(b)) => format!("{}/{}", &info.name, b), + _ => info.name.to_string(), + }; + formatted +} \ No newline at end of file diff --git a/ft-stripe/src/ids.rs b/ft-stripe/src/ids.rs new file mode 100644 index 0000000..4ab076a --- /dev/null +++ b/ft-stripe/src/ids.rs @@ -0,0 +1,626 @@ +macro_rules! def_id_serde_impls { + ($struct_name:ident) => { + impl serde::Serialize for $struct_name { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + self.as_str().serialize(serializer) + } + } + + impl<'de> serde::Deserialize<'de> for $struct_name { + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + let s: String = serde::Deserialize::deserialize(deserializer)?; + s.parse::().map_err(::serde::de::Error::custom) + } + } + }; + ($struct_name:ident, _) => {}; +} + +macro_rules! def_id { + ($struct_name:ident: String) => { + #[derive(Clone, Debug, Eq, PartialEq, Hash)] + pub struct $struct_name(smol_str::SmolStr); + + impl $struct_name { + /// Extracts a string slice containing the entire id. + #[inline(always)] + pub fn as_str(&self) -> &str { + self.0.as_str() + } + } + + impl PartialEq for $struct_name { + fn eq(&self, other: &str) -> bool { + self.as_str() == other + } + } + + impl PartialEq<&str> for $struct_name { + fn eq(&self, other: &&str) -> bool { + self.as_str() == *other + } + } + + impl PartialEq for $struct_name { + fn eq(&self, other: &String) -> bool { + self.as_str() == other + } + } + + impl PartialOrd for $struct_name { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for $struct_name { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.as_str().cmp(other.as_str()) + } + } + + impl AsRef for $struct_name { + fn as_ref(&self) -> &str { + self.as_str() + } + } + + impl crate::params::AsCursor for $struct_name {} + + impl std::ops::Deref for $struct_name { + type Target = str; + + fn deref(&self) -> &str { + self.as_str() + } + } + + impl std::fmt::Display for $struct_name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } + } + + impl std::str::FromStr for $struct_name { + type Err = ParseIdError; + + fn from_str(s: &str) -> Result { + Ok($struct_name(s.into())) + } + } + + impl serde::Serialize for $struct_name { + fn serialize(&self, serializer: S) -> Result + where S: serde::ser::Serializer + { + self.as_str().serialize(serializer) + } + } + + impl<'de> serde::Deserialize<'de> for $struct_name { + fn deserialize(deserializer: D) -> Result + where D: serde::de::Deserializer<'de> + { + let s: String = serde::Deserialize::deserialize(deserializer)?; + s.parse::().map_err(::serde::de::Error::custom) + } + } + }; + ($struct_name:ident, $prefix:literal $(| $alt_prefix:literal)* $(, { $generate_hint:tt })?) => { + /// An id for the corresponding object type. + /// + /// This type _typically_ will not allocate and + /// therefore is usually cheaply clonable. + #[derive(Clone, Debug, Eq, PartialEq, Hash)] + pub struct $struct_name(smol_str::SmolStr); + + impl $struct_name { + /// The prefix of the id type (e.g. `cus_` for a `CustomerId`). + #[inline(always)] + #[deprecated(note = "Please use prefixes or is_valid_prefix")] + pub fn prefix() -> &'static str { + $prefix + } + + /// The valid prefixes of the id type (e.g. [`ch_`, `py_`\ for a `ChargeId`). + #[inline(always)] + pub fn prefixes() -> &'static [&'static str] { + &[$prefix$(, $alt_prefix)*] + } + + /// Extracts a string slice containing the entire id. + #[inline(always)] + pub fn as_str(&self) -> &str { + self.0.as_str() + } + + /// Check is provided prefix would be a valid prefix for id's of this type + pub fn is_valid_prefix(prefix: &str) -> bool { + prefix == $prefix $( || prefix == $alt_prefix )* + } + } + + impl PartialEq for $struct_name { + fn eq(&self, other: &str) -> bool { + self.as_str() == other + } + } + + impl PartialEq<&str> for $struct_name { + fn eq(&self, other: &&str) -> bool { + self.as_str() == *other + } + } + + impl PartialEq for $struct_name { + fn eq(&self, other: &String) -> bool { + self.as_str() == other + } + } + + impl PartialOrd for $struct_name { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for $struct_name { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.as_str().cmp(other.as_str()) + } + } + + impl AsRef for $struct_name { + fn as_ref(&self) -> &str { + self.as_str() + } + } + + impl crate::params::AsCursor for $struct_name {} + + impl std::ops::Deref for $struct_name { + type Target = str; + + fn deref(&self) -> &str { + self.as_str() + } + } + + impl std::fmt::Display for $struct_name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } + } + + impl std::str::FromStr for $struct_name { + type Err = ParseIdError; + + fn from_str(s: &str) -> Result { + if !s.starts_with($prefix) $( + && !s.starts_with($alt_prefix) + )* { + + // N.B. For debugging + eprintln!("bad id is: {} (expected: {:?})", s, $prefix); + + Err(ParseIdError { + typename: stringify!($struct_name), + expected: stringify!(id to start with $prefix $(or $alt_prefix)*), + }) + } else { + Ok($struct_name(s.into())) + } + } + } + + def_id_serde_impls!($struct_name $(, $generate_hint )*); + }; + (#[optional] enum $enum_name:ident { $( $variant_name:ident($($variant_type:tt)*) ),* $(,)* }) => { + #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] + pub enum $enum_name { + None, + $( $variant_name($($variant_type)*), )* + } + + impl $enum_name { + pub fn as_str(&self) -> &str { + match *self { + $enum_name::None => "", + $( $enum_name::$variant_name(ref id) => id.as_str(), )* + } + } + } + + impl PartialEq for $enum_name { + fn eq(&self, other: &str) -> bool { + self.as_str() == other + } + } + + impl PartialEq<&str> for $enum_name { + fn eq(&self, other: &&str) -> bool { + self.as_str() == *other + } + } + + impl PartialEq for $enum_name { + fn eq(&self, other: &String) -> bool { + self.as_str() == other + } + } + + impl AsRef for $enum_name { + fn as_ref(&self) -> &str { + self.as_str() + } + } + + impl crate::params::AsCursor for $enum_name {} + + impl std::ops::Deref for $enum_name { + type Target = str; + + fn deref(&self) -> &str { + self.as_str() + } + } + + impl std::fmt::Display for $enum_name { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match *self { + $enum_name::None => Ok(()), + $( $enum_name::$variant_name(ref id) => id.fmt(f), )* + } + } + } + + impl std::str::FromStr for $enum_name { + type Err = ParseIdError; + + fn from_str(s: &str) -> Result { + let prefix = s.find('_') + .map(|i| &s[0..=i]) + .ok_or_else(|| ParseIdError { + typename: stringify!($enum_name), + expected: "id to start with a prefix (as in 'prefix_')" + })?; + + match prefix { + $(_ if $($variant_type)*::is_valid_prefix(prefix) => { + Ok($enum_name::$variant_name(s.parse()?)) + })* + _ => { + Err(ParseIdError { + typename: stringify!($enum_name), + expected: "unknown id prefix", + }) + } + } + } + } + + impl serde::Serialize for $enum_name { + fn serialize(&self, serializer: S) -> Result + where S: serde::ser::Serializer + { + self.as_str().serialize(serializer) + } + } + + impl<'de> serde::Deserialize<'de> for $enum_name { + fn deserialize(deserializer: D) -> Result + where D: serde::de::Deserializer<'de> + { + let s: String = serde::Deserialize::deserialize(deserializer)?; + s.parse::().map_err(::serde::de::Error::custom) + } + } + + $( + impl From<$($variant_type)*> for $enum_name { + fn from(id: $($variant_type)*) -> Self { + $enum_name::$variant_name(id) + } + } + )* + }; + (enum $enum_name:ident { $( $variant_name:ident($($variant_type:tt)*) ),* $(,)* }) => { + #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] + pub enum $enum_name { + $( $variant_name($($variant_type)*), )* + } + + impl $enum_name { + pub fn as_str(&self) -> &str { + match *self { + $( $enum_name::$variant_name(ref id) => id.as_str(), )* + } + } + } + + impl PartialEq for $enum_name { + fn eq(&self, other: &str) -> bool { + self.as_str() == other + } + } + + impl PartialEq<&str> for $enum_name { + fn eq(&self, other: &&str) -> bool { + self.as_str() == *other + } + } + + impl PartialEq for $enum_name { + fn eq(&self, other: &String) -> bool { + self.as_str() == other + } + } + + impl AsRef for $enum_name { + fn as_ref(&self) -> &str { + self.as_str() + } + } + + impl crate::params::AsCursor for $enum_name {} + + impl std::ops::Deref for $enum_name { + type Target = str; + + fn deref(&self) -> &str { + self.as_str() + } + } + + impl std::fmt::Display for $enum_name { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match *self { + $( $enum_name::$variant_name(ref id) => id.fmt(f), )* + } + } + } + + impl std::str::FromStr for $enum_name { + type Err = ParseIdError; + + fn from_str(s: &str) -> Result { + let prefix = s.find('_') + .map(|i| &s[0..=i]) + .ok_or_else(|| ParseIdError { + typename: stringify!($enum_name), + expected: "id to start with a prefix (as in 'prefix_')" + })?; + + match prefix { + $(_ if $($variant_type)*::is_valid_prefix(prefix) => { + Ok($enum_name::$variant_name(s.parse()?)) + })* + _ => { + Err(ParseIdError { + typename: stringify!($enum_name), + expected: "unknown id prefix", + }) + } + } + } + } + + impl serde::Serialize for $enum_name { + fn serialize(&self, serializer: S) -> Result + where S: serde::ser::Serializer + { + self.as_str().serialize(serializer) + } + } + + impl<'de> serde::Deserialize<'de> for $enum_name { + fn deserialize(deserializer: D) -> Result + where D: serde::de::Deserializer<'de> + { + let s: String = serde::Deserialize::deserialize(deserializer)?; + s.parse::().map_err(::serde::de::Error::custom) + } + } + + $( + impl From<$($variant_type)*> for $enum_name { + fn from(id: $($variant_type)*) -> Self { + $enum_name::$variant_name(id) + } + } + )* + }; +} + +#[derive(Clone, Debug)] +pub struct ParseIdError { + typename: &'static str, + expected: &'static str, +} + +impl std::fmt::Display for ParseIdError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "invalid `{}`, expected {}", self.typename, self.expected) + } +} + +impl std::error::Error for ParseIdError { + fn description(&self) -> &str { + "error parsing an id" + } +} + +def_id!(AccountId, "acct_"); +def_id!(AlipayAccountId, "aliacc_"); +def_id!(ApplicationId, "ca_"); +def_id!(ApplicationFeeId, "fee_"); +def_id!(ApplicationFeeRefundId, "fr_"); +def_id!(BalanceTransactionId, "txn_"); +def_id!(BankAccountId, "ba_"); +def_id!(BankTokenId, "btok_"); +def_id!( + #[optional] + enum BalanceTransactionSourceId { + ApplicationFee(ApplicationFeeId), + Charge(ChargeId), + Dispute(DisputeId), + ApplicationFeeRefund(ApplicationFeeRefundId), + IssuingAuthorization(IssuingAuthorizationId), + IssuingTransaction(IssuingTransactionId), + Payout(PayoutId), + Refund(RefundId), + Topup(TopupId), + Transfer(TransferId), + TransferReversal(TransferReversalId), + } +); +def_id!(CardId, "card_"); +def_id!(CardTokenId, "tok_"); +def_id!(ChargeId, "ch_" | "py_"); // TODO: Understand (and then document) why "py_" is a valid charge id +def_id!(CheckoutSessionId, "cs_"); +def_id!(CheckoutSessionItemId: String); // TODO: Figure out what prefix this id has +def_id!(CouponId: String); // N.B. A coupon id can be user-provided so can be any arbitrary string +def_id!(CustomerId, "cus_"); +def_id!(DisputeId, "dp_" | "du_"); +def_id!(EventId, "evt_"); +def_id!(FileId, "file_"); +def_id!(FileLinkId, "link_"); +def_id!(InvoiceId, "in_", { _ }); +def_id!(InvoiceItemId, "ii_"); +def_id!( + enum InvoiceLineItemId { + Item(InvoiceItemId), + Subscription(SubscriptionLineId), + } +); +def_id!(IssuingAuthorizationId, "iauth_"); +def_id!(IssuingCardId, "ic_"); +def_id!(IssuingCardholderId, "ich_"); +def_id!(IssuingDisputeId, "idp_"); +def_id!(IssuingTransactionId, "ipi_"); +def_id!(OrderId, "or_"); +def_id!(OrderReturnId, "orret_"); +def_id!(MandateId: String); // TODO: Figure out what prefix this id has +def_id!(PaymentIntentId, "pi_"); +def_id!(PaymentMethodId, "pm" | "card_"); +def_id!( + enum PaymentSourceId { + Account(AccountId), + AlipayAccount(AlipayAccountId), + BankAccount(BankAccountId), + Card(CardId), + Source(SourceId), + } +); +def_id!(PayoutId, "po_"); +def_id!( + enum PayoutDestinationId { + BankAccount(BankAccountId), + Card(CardId), + } +); +def_id!(PersonId, "person_"); +def_id!(PlanId: String); // N.B. A plan id can be user-provided so can be any arbitrary string +def_id!(PriceId: String); // TODO: Figure out what prefix this id has +def_id!(ProductId: String); // N.B. A product id can be user-provided so can be any arbitrary string +def_id!(RecipientId: String); // FIXME: This doesn't seem to be documented yet +def_id!(RefundId, "re_" | "pyr_"); +def_id!(ReviewId, "prv_"); +def_id!(ScheduledQueryRunId, "sqr_"); +def_id!(SetupIntentId, "seti_"); +def_id!(SkuId, "sku_"); +def_id!(SourceId, "src_"); +def_id!(SubscriptionId, "sub_"); +def_id!(SubscriptionItemId, "si_"); +def_id!(SubscriptionLineId, "sli_"); +def_id!(SubscriptionScheduleId, "sub_sched_"); +def_id!(TaxIdId, "txi_"); +def_id!(TaxRateId, "txr_"); +def_id!( + enum TokenId { + Card(CardTokenId), + Bank(BankTokenId), + } +); +def_id!(TopupId, "tu_"); +def_id!(TransferId, "tr_"); +def_id!(TransferReversalId, "trr_"); +def_id!(UsageRecordId, "mbur_"); +def_id!(UsageRecordSummaryId, "sis_"); +def_id!(WebhookEndpointId, "we_"); + +impl InvoiceId { + pub(crate) fn none() -> Self { + Self("".into()) + } + + /// An InvoiceId may have a `None` representation when + /// received from Stripe if the Invoice is an upcoming invoice. + pub fn is_none(&self) -> bool { + self.0.is_empty() + } +} +impl serde::Serialize for InvoiceId { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + if self.0.is_empty() { + let val: Option<&str> = None; + val.serialize(serializer) + } else { + self.as_str().serialize(serializer) + } + } +} +impl<'de> serde::Deserialize<'de> for InvoiceId { + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + let s: String = serde::Deserialize::deserialize(deserializer)?; + if s.is_empty() { + Ok(InvoiceId::none()) + } else { + s.parse::().map_err(::serde::de::Error::custom) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_customer() { + assert!("cus_123".parse::().is_ok()); + let bad_parse = "zzz_123".parse::(); + assert!(bad_parse.is_err()); + if let Err(err) = bad_parse { + assert_eq!( + format!("{}", err), + "invalid `CustomerId`, expected id to start with \"cus_\"" + ); + } + } + + #[test] + fn test_parse_charge() { + assert!("ch_123".parse::().is_ok()); + assert!("py_123".parse::().is_ok()); + let bad_parse = "zz_123".parse::(); + assert!(bad_parse.is_err()); + if let Err(err) = bad_parse { + assert_eq!( + format!("{}", err), + "invalid `ChargeId`, expected id to start with \"ch_\" or \"py_\"" + ); + } + } +} diff --git a/ft-stripe/src/lib.rs b/ft-stripe/src/lib.rs index 0383537..cbc6fc5 100644 --- a/ft-stripe/src/lib.rs +++ b/ft-stripe/src/lib.rs @@ -1,19 +1,36 @@ -pub struct CustomerID(pub String); +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c +extern crate self as ft_stripe; -pub fn create_customer( - conn: &mut ft_sdk::Connection, - session_id: &ft_sdk::auth::SessionID, - secret_token: &str, -) -> Result { - let user_data = ft_sdk::auth::ud_from_session_key(conn, session_id)? - .ok_or_else(|| CreateCustomerError::UserNotFound)?; +mod resources; +pub use ft_stripe::resources::*; +mod ids; +mod params; +pub use crate::ids::*; +pub use crate::params::{ + Expandable, Headers, IdOrCreate, List, Metadata, Object, RangeBounds, RangeQuery, Timestamp, +}; + + +mod client; +mod config { + pub type Client = crate::client::Client; + pub type Response = Result; +} - let body = match mobile_from_email(user_data.email.as_str()) { - Some(phone) => serde_json::json!({"phone": phone}), - None => serde_json::json!({"email": user_data.email}), - }; +pub use self::config::Client; +pub use self::config::Response; - call_create_customer_api(secret_token, &body) + + + +pub struct CustomerID(pub String); + +pub fn create_customer( + secret_key: &str, +) -> Response { + let client = Client::new(secret_key); + let create_customer = CreateCustomer::new(); + Customer::create(&client, create_customer) } fn call_create_customer_api( diff --git a/ft-stripe/src/params.rs b/ft-stripe/src/params.rs new file mode 100644 index 0000000..7b910f5 --- /dev/null +++ b/ft-stripe/src/params.rs @@ -0,0 +1,253 @@ +use crate::resources::ApiVersion; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +#[derive(Clone, Default)] +pub struct AppInfo { + pub name: String, + pub url: Option, + pub version: Option, +} + +#[derive(Clone, Default)] +pub struct Headers { + pub client_id: Option, + pub stripe_version: Option, + pub stripe_account: Option, + pub user_agent: Option, +} + +/// Implemented by types which represent stripe objects. +pub trait Object { + /// The canonical id type for this object. + type Id; + /// The id of the object. + fn id(&self) -> Self::Id; + /// The object's type, typically represented in wire format as the `object` property. + fn object(&self) -> &'static str; +} + +/// A deleted object. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Deleted { + /// Unique identifier for the object. + pub id: T, + /// Always true for a deleted object. + pub deleted: bool, +} + +/// The `Expand` struct is used to serialize `expand` arguments in retrieve and list apis. +#[doc(hidden)] +#[derive(Serialize)] +pub struct Expand<'a> { + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], +} + +impl Expand<'_> { + pub(crate) fn is_empty(expand: &[&str]) -> bool { + expand.is_empty() + } +} + +/// An id or object. +/// +/// By default stripe will return an id for most fields, but if more detail is +/// necessary the `expand` parameter can be provided to ask for the id to be +/// loaded as an object instead: +/// +/// ```rust,ignore +/// Charge::retrieve(&client, &charge_id, &["invoice.customer"]) +/// ``` +/// +/// See [https://stripe.com/docs/api/expanding_objects](https://stripe.com/docs/api/expanding_objects). +#[derive(Clone, Debug, Serialize, Deserialize)] // TODO: Implement deserialize by hand for better error messages +#[serde(untagged)] +pub enum Expandable { + Id(T::Id), + Object(Box), +} + +impl Expandable +where + T: Object, + T::Id: Clone, +{ + pub fn id(&self) -> T::Id { + match self { + Expandable::Id(id) => id.clone(), + Expandable::Object(obj) => obj.id(), + } + } +} + +impl Expandable { + pub fn is_object(&self) -> bool { + match self { + Expandable::Id(_) => false, + Expandable::Object(_) => true, + } + } + + pub fn as_object(&self) -> Option<&T> { + match self { + Expandable::Id(_) => None, + Expandable::Object(obj) => Some(&obj), + } + } + + #[deprecated( + note = "Renamed `into_object` per rust api design guidelines (may be removed in v0.12)" + )] + #[allow(clippy::wrong_self_convention)] + pub fn to_object(self) -> Option { + match self { + Expandable::Id(_) => None, + Expandable::Object(obj) => Some(*obj), + } + } + + pub fn into_object(self) -> Option { + match self { + Expandable::Id(_) => None, + Expandable::Object(obj) => Some(*obj), + } + } +} + +pub trait AsCursor: AsRef {} + +impl<'a> AsCursor for &'a str {} +impl AsCursor for String {} + +/// A single page of a cursor-paginated list of an object. +#[derive(Debug, Deserialize, Serialize)] +pub struct List { + pub data: Vec, + pub has_more: bool, + pub total_count: Option, + pub url: String, +} + +impl Default for List { + fn default() -> Self { + List { data: Vec::new(), has_more: false, total_count: None, url: String::new() } + } +} + +impl Clone for List { + fn clone(&self) -> Self { + List { + data: self.data.clone(), + has_more: self.has_more, + total_count: self.total_count, + url: self.url.clone(), + } + } +} + +pub type Metadata = HashMap; +pub type Timestamp = i64; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "lowercase")] +pub struct RangeBounds { + pub gt: Option, + pub gte: Option, + pub lt: Option, + pub lte: Option, +} + +impl Default for RangeBounds { + fn default() -> Self { + RangeBounds { gt: None, gte: None, lt: None, lte: None } + } +} + +/// A set of generic request parameters that can be used on +/// list endpoints to filter their results by some timestamp. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum RangeQuery { + Exact(T), + Bounds(RangeBounds), +} + +impl RangeQuery { + /// Filter results to exactly match a given value + pub fn eq(value: T) -> RangeQuery { + RangeQuery::Exact(value) + } + + /// Filter results to be after a given value + pub fn gt(value: T) -> RangeQuery { + let mut bounds = RangeBounds::default(); + bounds.gt = Some(value); + RangeQuery::Bounds(bounds) + } + + /// Filter results to be after or equal to a given value + pub fn gte(value: T) -> RangeQuery { + let mut bounds = RangeBounds::default(); + bounds.gte = Some(value); + RangeQuery::Bounds(bounds) + } + + /// Filter results to be before to a given value + pub fn lt(value: T) -> RangeQuery { + let mut bounds = RangeBounds::default(); + bounds.lt = Some(value); + RangeQuery::Bounds(bounds) + } + + /// Filter results to be before or equal to a given value + pub fn lte(value: T) -> RangeQuery { + let mut bounds = RangeBounds::default(); + bounds.lte = Some(value); + RangeQuery::Bounds(bounds) + } +} + +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum IdOrCreate<'a, T> { + Id(&'a str), + Create(&'a T), +} + +// NOTE: Only intended to handle conversion from ASCII CamelCase to SnakeCase +// This function is used to convert static Rust identifiers to snakecase +// TODO: pub(crate) fn +pub fn to_snakecase(camel: &str) -> String { + let mut i = 0; + let mut snake = String::new(); + let mut chars = camel.chars().peekable(); + while let Some(ch) = chars.next() { + if ch.is_uppercase() { + if i > 0 && !chars.peek().unwrap_or(&'A').is_uppercase() { + snake.push('_'); + } + snake.push(ch.to_lowercase().next().unwrap_or(ch)); + } else { + snake.push(ch); + } + i += 1; + } + + snake +} + +#[cfg(test)] +mod tests { + #[test] + fn to_snakecase() { + use super::to_snakecase; + + assert_eq!(to_snakecase("snake_case").as_str(), "snake_case"); + assert_eq!(to_snakecase("CamelCase").as_str(), "camel_case"); + assert_eq!(to_snakecase("XMLHttpRequest").as_str(), "xml_http_request"); + assert_eq!(to_snakecase("UPPER").as_str(), "upper"); + assert_eq!(to_snakecase("lower").as_str(), "lower"); + } +} diff --git a/ft-stripe/src/payment_source.rs b/ft-stripe/src/payment_source.rs new file mode 100644 index 0000000..7fbedc7 --- /dev/null +++ b/ft-stripe/src/payment_source.rs @@ -0,0 +1,108 @@ +use serde::{Deserialize, Serialize}; +use serde::ser::SerializeStruct; +use stripe::{Account, AlipayAccount, BankAccount, Card, Currency, Object, PaymentSourceId, Source}; + +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum PaymentSourceParams { + /// Creates a payment method (e.g. card or bank account) from tokenized data, + /// using a token typically received from Stripe Elements. + Token(ft_stripe::TokenId), + + /// Attach an existing source to an existing customer or + /// create a new customer from an existing source. + Source(ft_stripe::SourceId), +} + + +/// A PaymentSource represents a payment method _associated with a customer or charge_. +/// This value is usually returned as a subresource on another request. +/// +/// Not to be confused with `Source` which represents a "generic" payment method +/// returned by the `Source::get` (which could still be a credit card, etc) +/// but is not necessarily attached to either a customer or charge. + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum PaymentSource { + Card(Card), + Source(Source), + Account(Account), + BankAccount(BankAccount), + AlipayAccount(AlipayAccount), +} + +impl ft_stripe::Object for stripe::PaymentSource { + type Id = PaymentSourceId; + fn id(&self) -> Self::Id { + match self { + PaymentSource::Card(x) => PaymentSourceId::Card(x.id()), + PaymentSource::Source(x) => PaymentSourceId::Source(x.id()), + PaymentSource::Account(x) => PaymentSourceId::Account(x.id()), + PaymentSource::BankAccount(x) => PaymentSourceId::BankAccount(x.id()), + PaymentSource::AlipayAccount(x) => PaymentSourceId::AlipayAccount(x.id()), + } + } + fn object(&self) -> &'static str { + match self { + PaymentSource::Card(x) => x.object(), + PaymentSource::Source(x) => x.object(), + PaymentSource::Account(x) => x.object(), + PaymentSource::BankAccount(x) => x.object(), + PaymentSource::AlipayAccount(x) => x.object(), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +pub struct BankAccountParams<'a> { + pub country: &'a str, + pub currency: Currency, + pub account_holder_name: Option<&'a str>, + pub account_holder_type: Option<&'a str>, + pub routing_number: Option<&'a str>, + pub account_number: &'a str, +} + +impl<'a> serde::ser::Serialize for BankAccountParams<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + let mut s = serializer.serialize_struct("BankAccountParams", 6)?; + s.serialize_field("object", "bank_account")?; + s.serialize_field("country", &self.country)?; + s.serialize_field("currency", &self.currency)?; + s.serialize_field("account_holder_name", &self.account_holder_name)?; + s.serialize_field("routing_number", &self.routing_number)?; + s.serialize_field("account_number", &self.account_number)?; + s.end() + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +pub struct CardParams<'a> { + pub exp_month: &'a str, // eg. "12" + pub exp_year: &'a str, // eg. "17" or 2017" + + pub number: &'a str, // card number + pub name: Option<&'a str>, // cardholder's full name + pub cvc: Option<&'a str>, // card security code +} + +impl<'a> serde::ser::Serialize for CardParams<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + let mut s = serializer.serialize_struct("CardParams", 6)?; + s.serialize_field("object", "card")?; + s.serialize_field("exp_month", &self.exp_month)?; + s.serialize_field("exp_year", &self.exp_year)?; + s.serialize_field("number", &self.number)?; + s.serialize_field("name", &self.name)?; + s.serialize_field("cvc", &self.cvc)?; + s.end() + } +} \ No newline at end of file diff --git a/ft-stripe/src/resources.rs b/ft-stripe/src/resources.rs new file mode 100644 index 0000000..6f56471 --- /dev/null +++ b/ft-stripe/src/resources.rs @@ -0,0 +1,304 @@ +// Builtin types +mod currency; +mod types; +pub use self::currency::*; +pub use self::types::*; + +// Core Resources +mod balance; +mod balance_transaction; +mod balance_transaction_ext; +mod charge; +mod charge_ext; +mod customer; +mod customer_ext; +mod dispute; +mod file; +mod file_link; +mod mandate; +mod payment_intent; +mod payment_source; +mod payout; +mod payout_ext; +mod platform_tax_fee; +mod product; +mod refund; +mod reserve_transaction; +mod setup_intent; +mod tax_deducted_at_source; +mod token; +mod token_ext; +pub use self::balance::*; +pub use self::balance_transaction::*; +pub use self::balance_transaction_ext::*; +pub use self::charge::*; +pub use self::charge_ext::*; +pub use self::customer::*; +pub use self::customer_ext::*; +pub use self::dispute::*; +pub use self::file::*; +pub use self::file_link::*; +pub use self::mandate::*; +pub use self::payment_intent::*; +pub use self::payment_source::*; +pub use self::payout::*; +pub use self::payout_ext::*; +pub use self::platform_tax_fee::*; +pub use self::product::*; +pub use self::refund::*; +pub use self::reserve_transaction::*; +pub use self::setup_intent::*; +pub use self::tax_deducted_at_source::*; +pub use self::token::*; +pub use self::token_ext::*; + +// Payment Methods +mod alipay_account; +mod bank_account; +mod bank_account_ext; +mod card; +mod payment_method; +mod payment_method_ext; +mod source; +mod source_ext; +pub use self::alipay_account::*; +pub use self::bank_account::*; +pub use self::bank_account_ext::*; +pub use self::card::*; +pub use self::payment_method::*; +pub use self::payment_method_ext::*; +pub use self::source::*; +pub use self::source_ext::*; + +// Events +#[cfg(feature = "events")] +mod event; +#[cfg(feature = "events")] +pub use self::event::*; + +// Checkout +#[cfg(feature = "checkout")] +mod checkout_session; +#[cfg(feature = "checkout")] +mod item; +#[cfg(feature = "checkout")] +pub use self::checkout_session::*; +#[cfg(feature = "checkout")] +pub use self::item::*; + +// Billing +#[cfg(feature = "billing")] +mod coupon; +#[cfg(feature = "billing")] +mod discount; +#[cfg(feature = "billing")] +mod invoice; +#[cfg(feature = "billing")] +mod invoice_ext; +#[cfg(feature = "billing")] +mod invoiceitem; +#[cfg(feature = "billing")] +mod line_item; +#[cfg(feature = "billing")] +mod line_item_ext; +#[cfg(feature = "billing")] +mod plan; +#[cfg(feature = "billing")] +mod price; +#[cfg(feature = "billing")] +mod subscription; +#[cfg(feature = "billing")] +mod subscription_ext; +#[cfg(feature = "billing")] +mod subscription_item; +#[cfg(feature = "billing")] +mod subscription_item_ext; +#[cfg(feature = "billing")] +mod subscription_schedule; +#[cfg(feature = "billing")] +mod tax_id; +#[cfg(feature = "billing")] +mod tax_rate; +#[cfg(feature = "billing")] +pub use self::coupon::*; +#[cfg(feature = "billing")] +pub use self::discount::*; +#[cfg(feature = "billing")] +pub use self::invoice::*; +#[cfg(feature = "billing")] +pub use self::invoice_ext::*; +#[cfg(feature = "billing")] +pub use self::invoiceitem::*; +#[cfg(feature = "billing")] +pub use self::line_item::*; +#[cfg(feature = "billing")] +pub use self::line_item_ext::*; +#[cfg(feature = "billing")] +pub use self::plan::*; +#[cfg(feature = "billing")] +pub use self::price::*; +#[cfg(feature = "billing")] +pub use self::subscription::*; +#[cfg(feature = "billing")] +pub use self::subscription_ext::*; +#[cfg(feature = "billing")] +pub use self::subscription_item::*; +#[cfg(feature = "billing")] +pub use self::subscription_item_ext::*; +#[cfg(feature = "billing")] +pub use self::subscription_schedule::*; +#[cfg(feature = "billing")] +pub use self::tax_id::*; +#[cfg(feature = "billing")] +pub use self::tax_rate::*; + +// Connect +#[cfg(feature = "connect")] +mod account; +#[cfg(feature = "connect")] +mod application; +#[cfg(feature = "connect")] +mod application_fee; +#[cfg(feature = "connect")] +mod connect_collection_transfer; +#[cfg(feature = "connect")] +mod fee_refund; +#[cfg(feature = "connect")] +mod person; +#[cfg(feature = "connect")] +mod recipient; +#[cfg(feature = "connect")] +mod topup; +#[cfg(feature = "connect")] +mod transfer; +#[cfg(feature = "connect")] +mod transfer_reversal; +#[cfg(feature = "connect")] +pub use self::account::*; +#[cfg(feature = "connect")] +pub use self::application::*; +#[cfg(feature = "connect")] +pub use self::application_fee::*; +#[cfg(feature = "connect")] +pub use self::connect_collection_transfer::*; +#[cfg(feature = "connect")] +pub use self::fee_refund::*; +#[cfg(feature = "connect")] +pub use self::person::*; +#[cfg(feature = "connect")] +pub use self::recipient::*; +#[cfg(feature = "connect")] +pub use self::topup::*; +#[cfg(feature = "connect")] +pub use self::transfer::*; +#[cfg(feature = "connect")] +pub use self::transfer_reversal::*; + +// Fraud +#[cfg(feature = "fraud")] +mod review; +#[cfg(feature = "fraud")] +mod review_ext; +#[cfg(feature = "fraud")] +pub use self::review::*; +#[cfg(feature = "fraud")] +pub use self::review_ext::*; + +// Issuing +#[cfg(feature = "issuing")] +mod issuing_authorization; +#[cfg(feature = "issuing")] +mod issuing_authorization_ext; +#[cfg(feature = "issuing")] +mod issuing_card; +#[cfg(feature = "issuing")] +mod issuing_card_ext; +#[cfg(feature = "issuing")] +mod issuing_cardholder; +#[cfg(feature = "issuing")] +mod issuing_dispute; +#[cfg(feature = "issuing")] +mod issuing_dispute_ext; +#[cfg(feature = "issuing")] +mod issuing_merchant_data; +#[cfg(feature = "issuing")] +mod issuing_transaction; +#[cfg(feature = "issuing")] +mod issuing_transaction_ext; +#[cfg(feature = "issuing")] +pub use self::issuing_authorization::*; +#[cfg(feature = "issuing")] +pub use self::issuing_authorization_ext::*; +#[cfg(feature = "issuing")] +pub use self::issuing_card::*; +#[cfg(feature = "issuing")] +pub use self::issuing_card_ext::*; +#[cfg(feature = "issuing")] +pub use self::issuing_cardholder::*; +#[cfg(feature = "issuing")] +pub use self::issuing_dispute::*; +#[cfg(feature = "issuing")] +pub use self::issuing_dispute_ext::*; +#[cfg(feature = "issuing")] +pub use self::issuing_merchant_data::*; +#[cfg(feature = "issuing")] +pub use self::issuing_transaction::*; +#[cfg(feature = "issuing")] +pub use self::issuing_transaction_ext::*; + +// Orders +#[cfg(feature = "orders")] +mod order; +#[cfg(feature = "orders")] +mod order_ext; +#[cfg(feature = "orders")] +mod order_item; +#[cfg(feature = "orders")] +mod order_return; +#[cfg(feature = "orders")] +mod sku; +#[cfg(feature = "orders")] +pub use self::order::*; +#[cfg(feature = "orders")] +pub use self::order_ext::*; +#[cfg(feature = "orders")] +pub use self::order_item::*; +#[cfg(feature = "orders")] +pub use self::order_return::*; +#[cfg(feature = "orders")] +pub use self::sku::*; + +#[cfg(feature = "sigma")] +mod scheduled_query_run; +#[cfg(feature = "sigma")] +pub use self::scheduled_query_run::*; + +// Not-yet-implemented feature flags +#[cfg(feature = "webhook-endpoints")] +mod webhook_endpoint; +#[cfg(feature = "webhook-endpoints")] +mod webhook_endpoint_ext; +#[cfg(feature = "webhook-endpoints")] +pub use self::webhook_endpoint::*; +#[cfg(feature = "webhook-endpoints")] +pub use self::webhook_endpoint_ext::*; + +// Fallback types +#[cfg(not(feature = "full"))] +mod placeholders; +#[cfg(not(feature = "full"))] +pub use self::placeholders::*; + +#[cfg(not(feature = "account"))] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct CompanyParams { + #[serde(default)] + pub metadata: crate::params::Metadata, +} + +#[cfg(not(feature = "account"))] +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct PersonParams { + #[serde(default)] + pub metadata: crate::params::Metadata, +} diff --git a/ft-stripe/src/resources/account.rs b/ft-stripe/src/resources/account.rs new file mode 100644 index 0000000..7e35747 --- /dev/null +++ b/ft-stripe/src/resources/account.rs @@ -0,0 +1,1420 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::AccountId; +use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Address, BankAccount, BusinessType, Card, Currency, DelayDays, Dob, File, Person, + PersonVerificationParams, VerificationDocumentParams, Weekday, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Account". +/// +/// For more details see [https://stripe.com/docs/api/accounts/object](https://stripe.com/docs/api/accounts/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Account { + /// Unique identifier for the object. + pub id: AccountId, + + /// Business information about the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_profile: Option, + + /// The business type. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub capabilities: Option, + + /// Whether the account can create live charges. + #[serde(skip_serializing_if = "Option::is_none")] + pub charges_enabled: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub company: Option, + + /// The account's country. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter ISO currency code representing the default currency for the account. + /// + /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + #[serde(skip_serializing_if = "Option::is_none")] + pub default_currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Whether account details have been submitted. + /// + /// Standard accounts cannot receive payouts before this is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub details_submitted: Option, + + /// The primary user's email address. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// External accounts (bank accounts and debit cards) currently attached to this account. + #[serde(default)] + pub external_accounts: List, + + #[serde(skip_serializing_if = "Option::is_none")] + pub individual: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// Whether Stripe can send payouts to this account. + #[serde(skip_serializing_if = "Option::is_none")] + pub payouts_enabled: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub requirements: Option, + + /// Options for customizing how the account functions within Stripe. + #[serde(skip_serializing_if = "Option::is_none")] + pub settings: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tos_acceptance: Option, + + /// The Stripe account type. + /// + /// Can be `standard`, `express`, or `custom`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +impl Account { + /// Returns a list of accounts connected to your platform via [Connect](https://stripe.com/docs/connect). + /// + /// If you’re not a platform, the list is empty. + pub fn list(client: &Client, params: ListAccounts<'_>) -> Response> { + client.get_query("/accounts", ¶ms) + } + + /// With [Connect](https://stripe.com/docs/connect), you can create Stripe accounts for your users. + /// To do this, you’ll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). + pub fn create(client: &Client, params: CreateAccount<'_>) -> Response { + client.post_form("/accounts", ¶ms) + } + + /// Retrieves the details of an account. + pub fn retrieve(client: &Client, id: &AccountId, expand: &[&str]) -> Response { + client.get_query(&format!("/accounts/{}", id), &Expand { expand }) + } + + /// Updates a connected [Express or Custom account](https://stripe.com/docs/connect/accounts) by setting the values of the parameters passed. + /// + /// Any parameters not provided are left unchanged. + /// Most parameters can be changed only for Custom accounts. + /// (These are marked **Custom Only** below.) Parameters marked **Custom and Express** are supported by both account types. To update your own account, use the [Dashboard](https://dashboard.stripe.com/account). + /// Refer to our [Connect](https://stripe.com/docs/connect/updating-accounts) documentation to learn more about updating accounts. + pub fn update(client: &Client, id: &AccountId, params: UpdateAccount<'_>) -> Response { + client.post_form(&format!("/accounts/{}", id), ¶ms) + } + + /// With [Connect](https://stripe.com/docs/connect), you can delete Custom or Express accounts you manage. + /// + /// Accounts created using test-mode keys can be deleted at any time. + /// + /// Accounts created using live-mode keys can only be deleted once all balances are zero. If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/account) instead. + pub fn delete(client: &Client, id: &AccountId) -> Response> { + client.delete(&format!("/accounts/{}", id)) + } +} + +impl Object for Account { + type Id = AccountId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "account" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BusinessProfile { + /// [The merchant category code for the account](https://stripe.com/docs/connect/setting-mcc). + /// + /// MCCs are used to classify businesses based on the goods or services they provide. + #[serde(skip_serializing_if = "Option::is_none")] + pub mcc: Option, + + /// The customer-facing business name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// Internal-only description of the product sold or service provided by the business. + /// + /// It's used by Stripe for risk and underwriting purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub product_description: Option, + + /// A publicly available mailing address for sending support issues to. + #[serde(skip_serializing_if = "Option::is_none")] + pub support_address: Option
, + + /// A publicly available email address for sending support issues to. + #[serde(skip_serializing_if = "Option::is_none")] + pub support_email: Option, + + /// A publicly available phone number to call with support issues. + #[serde(skip_serializing_if = "Option::is_none")] + pub support_phone: Option, + + /// A publicly available website for handling support issues. + #[serde(skip_serializing_if = "Option::is_none")] + pub support_url: Option, + + /// The business's publicly available website. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountCapabilities { + /// The status of the BECS Direct Debit (AU) payments capability of the account, or whether the account can directly process BECS Direct Debit (AU) charges. + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit_payments: Option, + + /// The status of the card issuing capability of the account, or whether you can use Issuing to distribute funds on cards. + #[serde(skip_serializing_if = "Option::is_none")] + pub card_issuing: Option, + + /// The status of the card payments capability of the account, or whether the account can directly process credit and debit card charges. + #[serde(skip_serializing_if = "Option::is_none")] + pub card_payments: Option, + + /// The status of the JCB payments capability of the account, or whether the account (Japan only) can directly process JCB credit card charges in JPY currency. + #[serde(skip_serializing_if = "Option::is_none")] + pub jcb_payments: Option, + + /// The status of the legacy payments capability of the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub legacy_payments: Option, + + /// The status of the tax reporting 1099-K (US) capability of the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_reporting_us_1099_k: Option, + + /// The status of the tax reporting 1099-MISC (US) capability of the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_reporting_us_1099_misc: Option, + + /// The status of the transfers capability of the account, or whether your platform can transfer funds to the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfers: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountRequirements { + /// The date the fields in `currently_due` must be collected by to keep payouts enabled for the account. + /// + /// These fields might block payouts sooner if the next threshold is reached before these fields are collected. + #[serde(skip_serializing_if = "Option::is_none")] + pub current_deadline: Option, + + /// The fields that need to be collected to keep the account enabled. + /// + /// If not collected by the `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub currently_due: Option>, + + /// If the account is disabled, this string describes why the account can’t create charges or receive payouts. + /// + /// Can be `requirements.past_due`, `requirements.pending_verification`, `rejected.fraud`, `rejected.terms_of_service`, `rejected.listed`, `rejected.other`, `listed`, `under_review`, or `other`. + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled_reason: Option, + + /// The fields that need to be collected again because validation or verification failed for some reason. + #[serde(skip_serializing_if = "Option::is_none")] + pub errors: Option>, + + /// The fields that need to be collected assuming all volume thresholds are reached. + /// + /// As they become required, these fields appear in `currently_due` as well, and the `current_deadline` is set. + #[serde(skip_serializing_if = "Option::is_none")] + pub eventually_due: Option>, + + /// The fields that weren't collected by the `current_deadline`. + /// + /// These fields need to be collected to re-enable the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub past_due: Option>, + + /// Fields that may become required depending on the results of verification or review. + /// + /// An empty array unless an asynchronous verification is pending. + /// If verification fails, the fields in this array become required and move to `currently_due` or `past_due`. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_verification: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountRequirementsError { + /// The code for the type of error. + pub code: AccountRequirementsErrorCode, + + /// An informative message that indicates the error type and provides additional details about the error. + pub reason: String, + + /// The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + pub requirement: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountSettings { + pub branding: BrandingSettings, + + pub card_payments: CardPaymentsSettings, + + pub dashboard: DashboardSettings, + + pub payments: PaymentsSettings, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payouts: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BrandingSettings { + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. + /// + /// Must be square and at least 128px x 128px. + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option>, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. + /// + /// Must be at least 128px x 128px. + #[serde(skip_serializing_if = "Option::is_none")] + pub logo: Option>, + + /// A CSS hex color value representing the primary branding color for this account. + #[serde(skip_serializing_if = "Option::is_none")] + pub primary_color: Option, + + /// A CSS hex color value representing the secondary branding color for this account. + #[serde(skip_serializing_if = "Option::is_none")] + pub secondary_color: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CardPaymentsSettings { + #[serde(skip_serializing_if = "Option::is_none")] + pub decline_on: Option, + + /// The default text that appears on credit card statements when a charge is made. + /// + /// This field prefixes any dynamic `statement_descriptor` specified on the charge. + /// `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_prefix: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DashboardSettings { + /// The display name for this account. + /// + /// This is used on the Stripe Dashboard to differentiate between accounts. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_name: Option, + + /// The timezone used in the Stripe Dashboard for this account. + /// + /// A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). + #[serde(skip_serializing_if = "Option::is_none")] + pub timezone: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DeclineChargeOn { + /// Whether Stripe automatically declines charges with an incorrect ZIP or postal code. + /// + /// This setting only applies when a ZIP or postal code is provided and they fail bank verification. + pub avs_failure: bool, + + /// Whether Stripe automatically declines charges with an incorrect CVC. + /// + /// This setting only applies when a CVC is provided and it fails bank verification. + pub cvc_failure: bool, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentsSettings { + /// The default text that appears on credit card statements when a charge is made. + /// + /// This field prefixes any dynamic `statement_descriptor` specified on the charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_kana: Option, + + /// The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_kanji: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PayoutSettings { + /// A Boolean indicating if Stripe should try to reclaim negative balances from an attached bank account. + /// + /// See our [Understanding Connect Account Balances](https://stripe.com/docs/connect/account-balances) documentation for details. + /// Default value is `true` for Express accounts and `false` for Custom accounts. + pub debit_negative_balances: bool, + + pub schedule: TransferSchedule, + + /// The text that appears on the bank account statement for payouts. + /// + /// If not set, this defaults to the platform's bank descriptor as set in the Dashboard. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TosAcceptance { + /// The Unix timestamp marking when the Stripe Services Agreement was accepted by the account representative. + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + /// The IP address from which the Stripe Services Agreement was accepted by the account representative. + #[serde(skip_serializing_if = "Option::is_none")] + pub ip: Option, + + /// The user agent of the browser from which the Stripe Services Agreement was accepted by the account representative. + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Company { + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + /// The Kana variation of the company's primary address (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kana: Option
, + + /// The Kanji variation of the company's primary address (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kanji: Option
, + + /// Whether the company's directors have been provided. + /// + /// This Boolean will be `true` if you've manually indicated that all directors are provided via [the `directors_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-directors_provided). + #[serde(skip_serializing_if = "Option::is_none")] + pub directors_provided: Option, + + /// Whether the company's executives have been provided. + /// + /// This Boolean will be `true` if you've manually indicated that all executives are provided via [the `executives_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-executives_provided), or if Stripe determined that sufficient executives were provided. + #[serde(skip_serializing_if = "Option::is_none")] + pub executives_provided: Option, + + /// The company's legal name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// The Kana variation of the company's legal name (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub name_kana: Option, + + /// The Kanji variation of the company's legal name (Japan only). + #[serde(skip_serializing_if = "Option::is_none")] + pub name_kanji: Option, + + /// Whether the company's owners have been provided. + /// + /// This Boolean will be `true` if you've manually indicated that all owners are provided via [the `owners_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-owners_provided), or if Stripe determined that sufficient owners were provided. + /// Stripe determines ownership requirements using both the number of owners provided and their total percent ownership (calculated by adding the `percent_ownership` of each owner together). + #[serde(skip_serializing_if = "Option::is_none")] + pub owners_provided: Option, + + /// The company's phone number (used for verification). + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + /// The category identifying the legal structure of the company or legal entity. + /// + /// See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. + #[serde(skip_serializing_if = "Option::is_none")] + pub structure: Option, + + /// Whether the company's business ID number was provided. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id_provided: Option, + + /// The jurisdiction in which the `tax_id` is registered (Germany-based companies only). + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id_registrar: Option, + + /// Whether the company's business VAT number was provided. + #[serde(skip_serializing_if = "Option::is_none")] + pub vat_id_provided: Option, + + /// Information on the verification state of the company. + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CompanyVerification { + pub document: CompanyVerificationDocument, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CompanyVerificationDocument { + /// The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. + #[serde(skip_serializing_if = "Option::is_none")] + pub back: Option>, + + /// A user-displayable string describing the verification state of this document. + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option, + + /// One of `document_corrupt`, `document_expired`, `document_failed_copy`, `document_failed_greyscale`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_not_readable`, `document_not_uploaded`, `document_type_not_supported`, or `document_too_large`. + /// + /// A machine-readable code specifying the verification state for this document. + #[serde(skip_serializing_if = "Option::is_none")] + pub details_code: Option, + + /// The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. + #[serde(skip_serializing_if = "Option::is_none")] + pub front: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferSchedule { + /// The number of days charges for the account will be held before being paid out. + pub delay_days: u32, + + /// How frequently funds will be paid out. + /// + /// One of `manual` (payouts only created via API call), `daily`, `weekly`, or `monthly`. + pub interval: String, + + /// The day of the month funds will be paid out. + /// + /// Only shown if `interval` is monthly. + /// Payouts scheduled between the 29th and 31st of the month are sent on the last day of shorter months. + #[serde(skip_serializing_if = "Option::is_none")] + pub monthly_anchor: Option, + + /// The day of the week funds will be paid out, of the style 'monday', 'tuesday', etc. + /// + /// Only shown if `interval` is weekly. + #[serde(skip_serializing_if = "Option::is_none")] + pub weekly_anchor: Option, +} + +/// The parameters for `Account::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateAccount<'a> { + /// An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_token: Option<&'a str>, + + /// Business information about the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_profile: Option, + + /// The business type. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_type: Option, + + /// Information about the company or business. + /// + /// This field is null unless `business_type` is set to `company`, `government_entity`, or `non_profit`. + #[serde(skip_serializing_if = "Option::is_none")] + pub company: Option, + + /// The country in which the account holder resides, or in which the business is legally established. + /// + /// This should be an ISO 3166-1 alpha-2 country code. + /// For example, if you are in the United States and the business for which you're creating an account is legally represented in Canada, you would use `CA` as the country for the account being created. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option<&'a str>, + + /// Three-letter ISO currency code representing the default currency for the account. + /// + /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + #[serde(skip_serializing_if = "Option::is_none")] + pub default_currency: Option, + + /// The email address of the account holder. + /// + /// For Custom accounts, this is only to make the account easier to identify to you: Stripe will never directly email your users. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A card or bank account to attach to the account. + /// + /// You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe.js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. + /// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. + /// To add additional external accounts without replacing the existing default for the currency, use the bank account or card creation API. + #[serde(skip_serializing_if = "Option::is_none")] + pub external_account: Option<&'a str>, + + /// Information about the person represented by the account. + /// + /// This field is null unless `business_type` is set to `individual`. + #[serde(skip_serializing_if = "Option::is_none")] + pub individual: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The set of capabilities you want to unlock for this account. + /// + /// Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. + /// An account may have some of its requested capabilities be active and some be inactive. + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_capabilities: Option>, + + /// Options for customizing how the account functions within Stripe. + #[serde(skip_serializing_if = "Option::is_none")] + pub settings: Option, + + /// Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance). + #[serde(skip_serializing_if = "Option::is_none")] + pub tos_acceptance: Option, + + /// The type of Stripe account to create. + /// + /// Currently must be `custom`, as only [Custom accounts](https://stripe.com/docs/connect/custom-accounts) may be created via the API. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +impl<'a> CreateAccount<'a> { + pub fn new() -> Self { + CreateAccount { + account_token: Default::default(), + business_profile: Default::default(), + business_type: Default::default(), + company: Default::default(), + country: Default::default(), + default_currency: Default::default(), + email: Default::default(), + expand: Default::default(), + external_account: Default::default(), + individual: Default::default(), + metadata: Default::default(), + requested_capabilities: Default::default(), + settings: Default::default(), + tos_acceptance: Default::default(), + type_: Default::default(), + } + } +} + +/// The parameters for `Account::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListAccounts<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListAccounts<'a> { + pub fn new() -> Self { + ListAccounts { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Account::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateAccount<'a> { + /// An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_token: Option<&'a str>, + + /// Business information about the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_profile: Option, + + /// The business type. + #[serde(skip_serializing_if = "Option::is_none")] + pub business_type: Option, + + /// Information about the company or business. + /// + /// This field is null unless `business_type` is set to `company`, `government_entity`, or `non_profit`. + #[serde(skip_serializing_if = "Option::is_none")] + pub company: Option, + + /// Three-letter ISO currency code representing the default currency for the account. + /// + /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). + #[serde(skip_serializing_if = "Option::is_none")] + pub default_currency: Option, + + /// Email address of the account representative. + /// + /// For Standard accounts, this is used to ask them to claim their Stripe account. + /// For Custom accounts, this only makes the account easier to identify to platforms; Stripe does not email the account representative. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A card or bank account to attach to the account. + /// + /// You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe.js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. + /// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. + /// To add additional external accounts without replacing the existing default for the currency, use the bank account or card creation API. + #[serde(skip_serializing_if = "Option::is_none")] + pub external_account: Option<&'a str>, + + /// Information about the person represented by the account. + /// + /// This field is null unless `business_type` is set to `individual`. + #[serde(skip_serializing_if = "Option::is_none")] + pub individual: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The set of capabilities you want to unlock for this account. + /// + /// Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. + /// An account may have some of its requested capabilities be active and some be inactive. + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_capabilities: Option>, + + /// Options for customizing how the account functions within Stripe. + #[serde(skip_serializing_if = "Option::is_none")] + pub settings: Option, + + /// Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance). + #[serde(skip_serializing_if = "Option::is_none")] + pub tos_acceptance: Option, +} + +impl<'a> UpdateAccount<'a> { + pub fn new() -> Self { + UpdateAccount { + account_token: Default::default(), + business_profile: Default::default(), + business_type: Default::default(), + company: Default::default(), + default_currency: Default::default(), + email: Default::default(), + expand: Default::default(), + external_account: Default::default(), + individual: Default::default(), + metadata: Default::default(), + requested_capabilities: Default::default(), + settings: Default::default(), + tos_acceptance: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AcceptTos { + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ip: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub branding: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card_payments: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payments: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payouts: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CompanyParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kana: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kanji: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub directors_provided: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub executives_provided: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub owners_provided: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub structure: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id_registrar: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub vat_id: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kana: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kanji: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dob: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub gender: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub maiden_name: Option, + + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ssn_last_4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BrandingSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub logo: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub primary_color: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub secondary_color: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CardPaymentsSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub decline_on: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_prefix: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CompanyVerificationParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub document: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentsSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_kanji: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PayoutSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub debit_negative_balances: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub schedule: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DeclineChargeOnParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub avs_failure: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc_failure: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferScheduleParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub delay_days: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub monthly_anchor: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub weekly_anchor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum ExternalAccount { + BankAccount(BankAccount), + Card(Card), +} + +/// An enum representing the possible values of an `AccountRequirementsError`'s `code` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum AccountRequirementsErrorCode { + InvalidAddressCityStatePostalCode, + InvalidStreetAddress, + InvalidValueOther, + VerificationDocumentAddressMismatch, + VerificationDocumentAddressMissing, + VerificationDocumentCorrupt, + VerificationDocumentCountryNotSupported, + VerificationDocumentDobMismatch, + VerificationDocumentDuplicateType, + VerificationDocumentExpired, + VerificationDocumentFailedCopy, + VerificationDocumentFailedGreyscale, + VerificationDocumentFailedOther, + VerificationDocumentFailedTestMode, + VerificationDocumentFraudulent, + VerificationDocumentIdNumberMismatch, + VerificationDocumentIdNumberMissing, + VerificationDocumentIncomplete, + VerificationDocumentInvalid, + VerificationDocumentManipulated, + VerificationDocumentMissingBack, + VerificationDocumentMissingFront, + VerificationDocumentNameMismatch, + VerificationDocumentNameMissing, + VerificationDocumentNationalityMismatch, + VerificationDocumentNotReadable, + VerificationDocumentNotUploaded, + VerificationDocumentPhotoMismatch, + VerificationDocumentTooLarge, + VerificationDocumentTypeNotSupported, + VerificationFailedAddressMatch, + VerificationFailedBusinessIecNumber, + VerificationFailedDocumentMatch, + VerificationFailedIdNumberMatch, + VerificationFailedKeyedIdentity, + VerificationFailedKeyedMatch, + VerificationFailedNameMatch, + VerificationFailedOther, +} + +impl AccountRequirementsErrorCode { + pub fn as_str(self) -> &'static str { + match self { + AccountRequirementsErrorCode::InvalidAddressCityStatePostalCode => { + "invalid_address_city_state_postal_code" + } + AccountRequirementsErrorCode::InvalidStreetAddress => "invalid_street_address", + AccountRequirementsErrorCode::InvalidValueOther => "invalid_value_other", + AccountRequirementsErrorCode::VerificationDocumentAddressMismatch => { + "verification_document_address_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentAddressMissing => { + "verification_document_address_missing" + } + AccountRequirementsErrorCode::VerificationDocumentCorrupt => { + "verification_document_corrupt" + } + AccountRequirementsErrorCode::VerificationDocumentCountryNotSupported => { + "verification_document_country_not_supported" + } + AccountRequirementsErrorCode::VerificationDocumentDobMismatch => { + "verification_document_dob_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentDuplicateType => { + "verification_document_duplicate_type" + } + AccountRequirementsErrorCode::VerificationDocumentExpired => { + "verification_document_expired" + } + AccountRequirementsErrorCode::VerificationDocumentFailedCopy => { + "verification_document_failed_copy" + } + AccountRequirementsErrorCode::VerificationDocumentFailedGreyscale => { + "verification_document_failed_greyscale" + } + AccountRequirementsErrorCode::VerificationDocumentFailedOther => { + "verification_document_failed_other" + } + AccountRequirementsErrorCode::VerificationDocumentFailedTestMode => { + "verification_document_failed_test_mode" + } + AccountRequirementsErrorCode::VerificationDocumentFraudulent => { + "verification_document_fraudulent" + } + AccountRequirementsErrorCode::VerificationDocumentIdNumberMismatch => { + "verification_document_id_number_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentIdNumberMissing => { + "verification_document_id_number_missing" + } + AccountRequirementsErrorCode::VerificationDocumentIncomplete => { + "verification_document_incomplete" + } + AccountRequirementsErrorCode::VerificationDocumentInvalid => { + "verification_document_invalid" + } + AccountRequirementsErrorCode::VerificationDocumentManipulated => { + "verification_document_manipulated" + } + AccountRequirementsErrorCode::VerificationDocumentMissingBack => { + "verification_document_missing_back" + } + AccountRequirementsErrorCode::VerificationDocumentMissingFront => { + "verification_document_missing_front" + } + AccountRequirementsErrorCode::VerificationDocumentNameMismatch => { + "verification_document_name_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentNameMissing => { + "verification_document_name_missing" + } + AccountRequirementsErrorCode::VerificationDocumentNationalityMismatch => { + "verification_document_nationality_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentNotReadable => { + "verification_document_not_readable" + } + AccountRequirementsErrorCode::VerificationDocumentNotUploaded => { + "verification_document_not_uploaded" + } + AccountRequirementsErrorCode::VerificationDocumentPhotoMismatch => { + "verification_document_photo_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentTooLarge => { + "verification_document_too_large" + } + AccountRequirementsErrorCode::VerificationDocumentTypeNotSupported => { + "verification_document_type_not_supported" + } + AccountRequirementsErrorCode::VerificationFailedAddressMatch => { + "verification_failed_address_match" + } + AccountRequirementsErrorCode::VerificationFailedBusinessIecNumber => { + "verification_failed_business_iec_number" + } + AccountRequirementsErrorCode::VerificationFailedDocumentMatch => { + "verification_failed_document_match" + } + AccountRequirementsErrorCode::VerificationFailedIdNumberMatch => { + "verification_failed_id_number_match" + } + AccountRequirementsErrorCode::VerificationFailedKeyedIdentity => { + "verification_failed_keyed_identity" + } + AccountRequirementsErrorCode::VerificationFailedKeyedMatch => { + "verification_failed_keyed_match" + } + AccountRequirementsErrorCode::VerificationFailedNameMatch => { + "verification_failed_name_match" + } + AccountRequirementsErrorCode::VerificationFailedOther => "verification_failed_other", + } + } +} + +impl AsRef for AccountRequirementsErrorCode { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for AccountRequirementsErrorCode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateAccount`'s `type_` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum AccountType { + Custom, + Express, + Standard, +} + +impl AccountType { + pub fn as_str(self) -> &'static str { + match self { + AccountType::Custom => "custom", + AccountType::Express => "express", + AccountType::Standard => "standard", + } + } +} + +impl AsRef for AccountType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for AccountType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `AccountCapabilities`'s `au_becs_debit_payments` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CapabilityStatus { + Active, + Inactive, + Pending, +} + +impl CapabilityStatus { + pub fn as_str(self) -> &'static str { + match self { + CapabilityStatus::Active => "active", + CapabilityStatus::Inactive => "inactive", + CapabilityStatus::Pending => "pending", + } + } +} + +impl AsRef for CapabilityStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CapabilityStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CompanyParams`'s `structure` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CompanyParamsStructure { + GovernmentInstrumentality, + GovernmentalUnit, + IncorporatedNonProfit, + LimitedLiabilityPartnership, + MultiMemberLlc, + PrivateCompany, + PrivateCorporation, + PrivatePartnership, + PublicCompany, + PublicCorporation, + PublicPartnership, + SoleProprietorship, + TaxExemptGovernmentInstrumentality, + UnincorporatedAssociation, + UnincorporatedNonProfit, +} + +impl CompanyParamsStructure { + pub fn as_str(self) -> &'static str { + match self { + CompanyParamsStructure::GovernmentInstrumentality => "government_instrumentality", + CompanyParamsStructure::GovernmentalUnit => "governmental_unit", + CompanyParamsStructure::IncorporatedNonProfit => "incorporated_non_profit", + CompanyParamsStructure::LimitedLiabilityPartnership => "limited_liability_partnership", + CompanyParamsStructure::MultiMemberLlc => "multi_member_llc", + CompanyParamsStructure::PrivateCompany => "private_company", + CompanyParamsStructure::PrivateCorporation => "private_corporation", + CompanyParamsStructure::PrivatePartnership => "private_partnership", + CompanyParamsStructure::PublicCompany => "public_company", + CompanyParamsStructure::PublicCorporation => "public_corporation", + CompanyParamsStructure::PublicPartnership => "public_partnership", + CompanyParamsStructure::SoleProprietorship => "sole_proprietorship", + CompanyParamsStructure::TaxExemptGovernmentInstrumentality => { + "tax_exempt_government_instrumentality" + } + CompanyParamsStructure::UnincorporatedAssociation => "unincorporated_association", + CompanyParamsStructure::UnincorporatedNonProfit => "unincorporated_non_profit", + } + } +} + +impl AsRef for CompanyParamsStructure { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CompanyParamsStructure { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Company`'s `structure` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CompanyStructure { + GovernmentInstrumentality, + GovernmentalUnit, + IncorporatedNonProfit, + LimitedLiabilityPartnership, + MultiMemberLlc, + PrivateCompany, + PrivateCorporation, + PrivatePartnership, + PublicCompany, + PublicCorporation, + PublicPartnership, + SoleProprietorship, + TaxExemptGovernmentInstrumentality, + UnincorporatedAssociation, + UnincorporatedNonProfit, +} + +impl CompanyStructure { + pub fn as_str(self) -> &'static str { + match self { + CompanyStructure::GovernmentInstrumentality => "government_instrumentality", + CompanyStructure::GovernmentalUnit => "governmental_unit", + CompanyStructure::IncorporatedNonProfit => "incorporated_non_profit", + CompanyStructure::LimitedLiabilityPartnership => "limited_liability_partnership", + CompanyStructure::MultiMemberLlc => "multi_member_llc", + CompanyStructure::PrivateCompany => "private_company", + CompanyStructure::PrivateCorporation => "private_corporation", + CompanyStructure::PrivatePartnership => "private_partnership", + CompanyStructure::PublicCompany => "public_company", + CompanyStructure::PublicCorporation => "public_corporation", + CompanyStructure::PublicPartnership => "public_partnership", + CompanyStructure::SoleProprietorship => "sole_proprietorship", + CompanyStructure::TaxExemptGovernmentInstrumentality => { + "tax_exempt_government_instrumentality" + } + CompanyStructure::UnincorporatedAssociation => "unincorporated_association", + CompanyStructure::UnincorporatedNonProfit => "unincorporated_non_profit", + } + } +} + +impl AsRef for CompanyStructure { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CompanyStructure { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateAccount`'s `requested_capabilities` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RequestedCapability { + AuBecsDebitPayments, + CardIssuing, + CardPayments, + JcbPayments, + LegacyPayments, + #[serde(rename = "tax_reporting_us_1099_k")] + TaxReportingUs1099K, + #[serde(rename = "tax_reporting_us_1099_misc")] + TaxReportingUs1099Misc, + Transfers, +} + +impl RequestedCapability { + pub fn as_str(self) -> &'static str { + match self { + RequestedCapability::AuBecsDebitPayments => "au_becs_debit_payments", + RequestedCapability::CardIssuing => "card_issuing", + RequestedCapability::CardPayments => "card_payments", + RequestedCapability::JcbPayments => "jcb_payments", + RequestedCapability::LegacyPayments => "legacy_payments", + RequestedCapability::TaxReportingUs1099K => "tax_reporting_us_1099_k", + RequestedCapability::TaxReportingUs1099Misc => "tax_reporting_us_1099_misc", + RequestedCapability::Transfers => "transfers", + } + } +} + +impl AsRef for RequestedCapability { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RequestedCapability { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `TransferScheduleParams`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TransferScheduleInterval { + Daily, + Manual, + Monthly, + Weekly, +} + +impl TransferScheduleInterval { + pub fn as_str(self) -> &'static str { + match self { + TransferScheduleInterval::Daily => "daily", + TransferScheduleInterval::Manual => "manual", + TransferScheduleInterval::Monthly => "monthly", + TransferScheduleInterval::Weekly => "weekly", + } + } +} + +impl AsRef for TransferScheduleInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TransferScheduleInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/alipay_account.rs b/ft-stripe/src/resources/alipay_account.rs new file mode 100644 index 0000000..cae8cc3 --- /dev/null +++ b/ft-stripe/src/resources/alipay_account.rs @@ -0,0 +1,75 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::AlipayAccountId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{Currency, Customer}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "AlipayAccount". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AlipayAccount { + /// Unique identifier for the object. + pub id: AlipayAccountId, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// The ID of the customer associated with this Alipay Account. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Uniquely identifies the account and will be the same across all Alipay account objects that are linked to the same Alipay account. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// If the Alipay account object is not reusable, the exact amount that you can create a charge for. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_amount: Option, + + /// If the Alipay account object is not reusable, the exact currency that you can create a charge for. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_currency: Option, + + /// True if you can create multiple payments using this account. + /// + /// If the account is reusable, then you can freely choose the amount of each payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub reusable: Option, + + /// Whether this Alipay account object has ever been used for a payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub used: Option, + + /// The username for the Alipay account. + #[serde(skip_serializing_if = "Option::is_none")] + pub username: Option, +} + +impl Object for AlipayAccount { + type Id = AlipayAccountId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "alipay_account" + } +} diff --git a/ft-stripe/src/resources/application.rs b/ft-stripe/src/resources/application.rs new file mode 100644 index 0000000..c0ae4b4 --- /dev/null +++ b/ft-stripe/src/resources/application.rs @@ -0,0 +1,28 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::ApplicationId; +use crate::params::Object; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Application". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Application { + /// Unique identifier for the object. + pub id: ApplicationId, + + /// The name of the application. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, +} + +impl Object for Application { + type Id = ApplicationId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "application" + } +} diff --git a/ft-stripe/src/resources/application_fee.rs b/ft-stripe/src/resources/application_fee.rs new file mode 100644 index 0000000..bf1a892 --- /dev/null +++ b/ft-stripe/src/resources/application_fee.rs @@ -0,0 +1,145 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ApplicationFeeId, ChargeId}; +use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Account, Application, ApplicationFeeRefund, BalanceTransaction, Charge, Currency, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "PlatformFee". +/// +/// For more details see [https://stripe.com/docs/api/application_fees/object](https://stripe.com/docs/api/application_fees/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ApplicationFee { + /// Unique identifier for the object. + pub id: ApplicationFeeId, + + /// ID of the Stripe account this fee was taken from. + pub account: Expandable, + + /// Amount earned, in %s. + pub amount: i64, + + /// Amount in %s refunded (can be less than the amount attribute on the fee if a partial refund was issued). + pub amount_refunded: i64, + + /// ID of the Connect application that earned the fee. + pub application: Expandable, + + /// Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds). + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// ID of the charge that the application fee was taken from. + pub charge: Expandable, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// ID of the corresponding charge on the platform account, if this fee was the result of a charge using the `destination` parameter. + #[serde(skip_serializing_if = "Option::is_none")] + pub originating_transaction: Option>, + + /// Whether the fee has been fully refunded. + /// + /// If the fee is only partially refunded, this attribute will still be false. + pub refunded: bool, + + /// A list of refunds that have been applied to the fee. + pub refunds: List, +} + +impl ApplicationFee { + /// Returns a list of application fees you’ve previously collected. + /// + /// The application fees are returned in sorted order, with the most recent fees appearing first. + pub fn list( + client: &Client, + params: ListApplicationFees<'_>, + ) -> Response> { + client.get_query("/application_fees", ¶ms) + } + + /// Retrieves the details of an application fee that your account has collected. + /// + /// The same information is returned when refunding the application fee. + pub fn retrieve( + client: &Client, + id: &ApplicationFeeId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/application_fees/{}", id), &Expand { expand }) + } +} + +impl Object for ApplicationFee { + type Id = ApplicationFeeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "application_fee" + } +} + +/// The parameters for `ApplicationFee::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListApplicationFees<'a> { + /// Only return application fees for the charge specified by this charge ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListApplicationFees<'a> { + pub fn new() -> Self { + ListApplicationFees { + charge: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/balance.rs b/ft-stripe/src/resources/balance.rs new file mode 100644 index 0000000..ce360f5 --- /dev/null +++ b/ft-stripe/src/resources/balance.rs @@ -0,0 +1,76 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::Object; +use crate::resources::Currency; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Balance". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Balance { + /// Funds that are available to be transferred or paid out, whether automatically by Stripe or explicitly via the [Transfers API](https://stripe.com/docs/api#transfers) or [Payouts API](https://stripe.com/docs/api#payouts). + /// + /// The available balance for each currency and payment type can be found in the `source_types` property. + pub available: Vec, + + /// Funds held due to negative balances on connected Custom accounts. + /// + /// The connect reserve balance for each currency and payment type can be found in the `source_types` property. + #[serde(skip_serializing_if = "Option::is_none")] + pub connect_reserved: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub issuing: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Funds that are not yet available in the balance, due to the 7-day rolling pay cycle. + /// + /// The pending balance for each currency, and for each payment type, can be found in the `source_types` property. + pub pending: Vec, +} + +impl Object for Balance { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "balance" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BalanceAmount { + /// Balance amount. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + #[serde(skip_serializing_if = "Option::is_none")] + pub source_types: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BalanceAmountBySourceType { + /// Amount for bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_account: Option, + + /// Amount for card. + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + /// Amount for FPX. + #[serde(skip_serializing_if = "Option::is_none")] + pub fpx: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BalanceDetail { + /// Funds that are available for use. + pub available: Vec, +} diff --git a/ft-stripe/src/resources/balance_transaction.rs b/ft-stripe/src/resources/balance_transaction.rs new file mode 100644 index 0000000..ccb4808 --- /dev/null +++ b/ft-stripe/src/resources/balance_transaction.rs @@ -0,0 +1,320 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{BalanceTransactionId, PayoutId, SourceId}; +use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; +use crate::resources::{ + ApplicationFee, ApplicationFeeRefund, BalanceTransactionStatus, Charge, + ConnectCollectionTransfer, Currency, Dispute, FeeType, IssuingAuthorization, + IssuingTransaction, Payout, PlatformTaxFee, Refund, ReserveTransaction, TaxDeductedAtSource, + Topup, Transfer, TransferReversal, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "BalanceTransaction". +/// +/// For more details see [https://stripe.com/docs/api/balance_transactions/object](https://stripe.com/docs/api/balance_transactions/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BalanceTransaction { + /// Unique identifier for the object. + pub id: BalanceTransactionId, + + /// Gross amount of the transaction, in %s. + pub amount: i64, + + /// The date the transaction's net funds will become available in the Stripe balance. + pub available_on: Timestamp, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The exchange rate used, if applicable, for this transaction. + /// + /// Specifically, if money was converted from currency A to currency B, then the `amount` in currency A, times `exchange_rate`, would be the `amount` in currency B. + /// For example, suppose you charged a customer 10.00 EUR. + /// Then the PaymentIntent's `amount` would be `1000` and `currency` would be `eur`. + /// Suppose this was converted into 12.34 USD in your Stripe account. + /// Then the BalanceTransaction's `amount` would be `1234`, `currency` would be `usd`, and `exchange_rate` would be `1.234`. + #[serde(skip_serializing_if = "Option::is_none")] + pub exchange_rate: Option, + + /// Fees (in %s) paid for this transaction. + pub fee: i64, + + /// Detailed breakdown of fees (in %s) paid for this transaction. + pub fee_details: Vec, + + /// Net amount of the transaction, in %s. + pub net: i64, + + /// [Learn more](https://stripe.com/docs/reports/reporting-categories) about how reporting categories can help you understand balance transactions from an accounting perspective. + pub reporting_category: String, + + /// The Stripe object to which this transaction is related. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option>, + + /// If the transaction's net funds are available in the Stripe balance yet. + /// + /// Either `available` or `pending`. + pub status: BalanceTransactionStatus, + + /// Transaction type: `adjustment`, `advance`, `advance_funding`, `application_fee`, `application_fee_refund`, `charge`, `connect_collection_transfer`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_transaction`, `payment`, `payment_failure_refund`, `payment_refund`, `payout`, `payout_cancel`, `payout_failure`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. + /// + /// [Learn more](https://stripe.com/docs/reports/balance-transaction-types) about balance transaction types and what they represent. + /// If you are looking to classify transactions for accounting purposes, you might want to consider `reporting_category` instead. + #[serde(rename = "type")] + pub type_: BalanceTransactionType, +} + +impl BalanceTransaction { + /// Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). + /// + /// The transactions are returned in sorted order, with the most recent transactions appearing first. Note that this endpoint was previously called “Balance history” and used the path `/v1/balance/history`. + pub fn list( + client: &Client, + params: ListBalanceTransactions<'_>, + ) -> Response> { + client.get_query("/balance_transactions", ¶ms) + } + + /// Retrieves the balance transaction with the given ID. + /// + /// Note that this endpoint previously used the path `/v1/balance/history/:id`. + pub fn retrieve( + client: &Client, + id: &BalanceTransactionId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/balance_transactions/{}", id), &Expand { expand }) + } +} + +impl Object for BalanceTransaction { + type Id = BalanceTransactionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "balance_transaction" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Fee { + /// Amount of the fee, in cents. + pub amount: i64, + + /// ID of the Connect application that earned the fee. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// Type of the fee, one of: `application_fee`, `stripe_fee` or `tax`. + #[serde(rename = "type")] + pub type_: FeeType, +} + +/// The parameters for `BalanceTransaction::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListBalanceTransactions<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub available_on: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return transactions in a certain currency. + /// + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// For automatic Stripe payouts only, only returns transactions that were paid out on the specified payout ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub payout: Option, + + /// Only returns the original transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only returns transactions of the given type. + /// + /// One of: `charge`, `refund`, `adjustment`, `application_fee`, `application_fee_refund`, `transfer`, `payment`, `payout`, `payout_failure`, `stripe_fee`, or `network_cost`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option<&'a str>, +} + +impl<'a> ListBalanceTransactions<'a> { + pub fn new() -> Self { + ListBalanceTransactions { + available_on: Default::default(), + created: Default::default(), + currency: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + payout: Default::default(), + source: Default::default(), + starting_after: Default::default(), + type_: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum BalanceTransactionSource { + ApplicationFee(ApplicationFee), + Charge(Charge), + ConnectCollectionTransfer(ConnectCollectionTransfer), + Dispute(Dispute), + #[serde(rename = "fee_refund")] + ApplicationFeeRefund(ApplicationFeeRefund), + #[serde(rename = "issuing.authorization")] + IssuingAuthorization(IssuingAuthorization), + #[serde(rename = "issuing.transaction")] + IssuingTransaction(IssuingTransaction), + Payout(Payout), + PlatformTaxFee(PlatformTaxFee), + Refund(Refund), + ReserveTransaction(ReserveTransaction), + TaxDeductedAtSource(TaxDeductedAtSource), + Topup(Topup), + Transfer(Transfer), + TransferReversal(TransferReversal), +} + +/// An enum representing the possible values of an `BalanceTransaction`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum BalanceTransactionType { + Adjustment, + Advance, + AdvanceFunding, + ApplicationFee, + ApplicationFeeRefund, + Charge, + ConnectCollectionTransfer, + IssuingAuthorizationHold, + IssuingAuthorizationRelease, + IssuingTransaction, + Payment, + PaymentFailureRefund, + PaymentRefund, + Payout, + PayoutCancel, + PayoutFailure, + Refund, + RefundFailure, + ReserveTransaction, + ReservedFunds, + StripeFee, + StripeFxFee, + TaxFee, + Topup, + TopupReversal, + Transfer, + TransferCancel, + TransferFailure, + TransferRefund, +} + +impl BalanceTransactionType { + pub fn as_str(self) -> &'static str { + match self { + BalanceTransactionType::Adjustment => "adjustment", + BalanceTransactionType::Advance => "advance", + BalanceTransactionType::AdvanceFunding => "advance_funding", + BalanceTransactionType::ApplicationFee => "application_fee", + BalanceTransactionType::ApplicationFeeRefund => "application_fee_refund", + BalanceTransactionType::Charge => "charge", + BalanceTransactionType::ConnectCollectionTransfer => "connect_collection_transfer", + BalanceTransactionType::IssuingAuthorizationHold => "issuing_authorization_hold", + BalanceTransactionType::IssuingAuthorizationRelease => "issuing_authorization_release", + BalanceTransactionType::IssuingTransaction => "issuing_transaction", + BalanceTransactionType::Payment => "payment", + BalanceTransactionType::PaymentFailureRefund => "payment_failure_refund", + BalanceTransactionType::PaymentRefund => "payment_refund", + BalanceTransactionType::Payout => "payout", + BalanceTransactionType::PayoutCancel => "payout_cancel", + BalanceTransactionType::PayoutFailure => "payout_failure", + BalanceTransactionType::Refund => "refund", + BalanceTransactionType::RefundFailure => "refund_failure", + BalanceTransactionType::ReserveTransaction => "reserve_transaction", + BalanceTransactionType::ReservedFunds => "reserved_funds", + BalanceTransactionType::StripeFee => "stripe_fee", + BalanceTransactionType::StripeFxFee => "stripe_fx_fee", + BalanceTransactionType::TaxFee => "tax_fee", + BalanceTransactionType::Topup => "topup", + BalanceTransactionType::TopupReversal => "topup_reversal", + BalanceTransactionType::Transfer => "transfer", + BalanceTransactionType::TransferCancel => "transfer_cancel", + BalanceTransactionType::TransferFailure => "transfer_failure", + BalanceTransactionType::TransferRefund => "transfer_refund", + } + } +} + +impl AsRef for BalanceTransactionType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for BalanceTransactionType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/balance_transaction_ext.rs b/ft-stripe/src/resources/balance_transaction_ext.rs new file mode 100644 index 0000000..a833485 --- /dev/null +++ b/ft-stripe/src/resources/balance_transaction_ext.rs @@ -0,0 +1,111 @@ +use crate::ids::BalanceTransactionSourceId; +use crate::params::Object; +use crate::resources::BalanceTransactionSource; +use serde::{Deserialize, Serialize}; + +impl Object for BalanceTransactionSource { + type Id = BalanceTransactionSourceId; + fn id(&self) -> Self::Id { + use BalanceTransactionSource as Source; + use BalanceTransactionSourceId as Id; + + match self { + Source::ApplicationFee(x) => Id::ApplicationFee(x.id()), + Source::ApplicationFeeRefund(x) => Id::ApplicationFeeRefund(x.id()), + Source::Charge(x) => Id::Charge(x.id()), + Source::ConnectCollectionTransfer(_) => Id::None, + Source::Dispute(x) => Id::Dispute(x.id()), + Source::IssuingAuthorization(x) => Id::IssuingAuthorization(x.id()), + Source::IssuingTransaction(x) => Id::IssuingTransaction(x.id()), + Source::PlatformTaxFee(_) => Id::None, + Source::Payout(x) => Id::Payout(x.id()), + Source::Refund(x) => Id::Refund(x.id()), + Source::ReserveTransaction(_) => Id::None, + Source::TaxDeductedAtSource(_) => Id::None, + Source::Topup(x) => Id::Topup(x.id()), + Source::Transfer(x) => Id::Transfer(x.id()), + Source::TransferReversal(x) => Id::TransferReversal(x.id()), + } + } + fn object(&self) -> &'static str { + use BalanceTransactionSource as Source; + + match self { + Source::ApplicationFee(x) => x.object(), + Source::ApplicationFeeRefund(x) => x.object(), + Source::Charge(x) => x.object(), + Source::ConnectCollectionTransfer(x) => x.object(), + Source::Dispute(x) => x.object(), + Source::IssuingAuthorization(x) => x.object(), + Source::IssuingTransaction(x) => x.object(), + Source::PlatformTaxFee(x) => x.object(), + Source::Payout(x) => x.object(), + Source::Refund(x) => x.object(), + Source::ReserveTransaction(x) => x.object(), + Source::TaxDeductedAtSource(x) => x.object(), + Source::Topup(x) => x.object(), + Source::Transfer(x) => x.object(), + Source::TransferReversal(x) => x.object(), + } + } +} + +/// An enum representing the possible values of an `BalanceTransaction`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum BalanceTransactionStatus { + Available, + Pending, +} + +impl BalanceTransactionStatus { + pub fn as_str(self) -> &'static str { + match self { + BalanceTransactionStatus::Available => "available", + BalanceTransactionStatus::Pending => "pending", + } + } +} + +impl AsRef for BalanceTransactionStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for BalanceTransactionStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Fee`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum FeeType { + ApplicationFee, + StripeFee, + Tax, +} + +impl FeeType { + pub fn as_str(self) -> &'static str { + match self { + FeeType::ApplicationFee => "application_fee", + FeeType::StripeFee => "stripe_fee", + FeeType::Tax => "tax", + } + } +} + +impl AsRef for FeeType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for FeeType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/bank_account.rs b/ft-stripe/src/resources/bank_account.rs new file mode 100644 index 0000000..4862d2e --- /dev/null +++ b/ft-stripe/src/resources/bank_account.rs @@ -0,0 +1,96 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::BankAccountId; +use crate::params::{Expandable, Metadata, Object}; +use crate::resources::{Account, AccountHolderType, BankAccountStatus, Currency, Customer}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "BankAccount". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BankAccount { + /// Unique identifier for the object. + pub id: BankAccountId, + + /// The ID of the account that the bank account is associated with. + #[serde(skip_serializing_if = "Option::is_none")] + pub account: Option>, + + /// The name of the person or business that owns the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_holder_name: Option, + + /// The type of entity that holds the account. + /// + /// This can be either `individual` or `company`. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_holder_type: Option, + + /// Name of the bank associated with the routing number (e.g., `WELLS FARGO`). + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + /// Two-letter ISO code representing the country the bank account is located in. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) paid out to the bank account. + pub currency: Currency, + + /// The ID of the customer that the bank account is associated with. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// Whether this bank account is the default external account for its currency. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_for_currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Uniquely identifies this particular bank account. + /// + /// You can use this attribute to check whether two bank accounts are the same. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// The last four digits of the bank account number. + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The routing transit number for the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub routing_number: Option, + + /// For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. + /// + /// A bank account that hasn't had any activity or validation performed is `new`. + /// If Stripe can determine that the bank account exists, its status will be `validated`. + /// Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. + /// If customer bank account verification has succeeded, the bank account status will be `verified`. + /// If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. + /// If a transfer sent to this bank account fails, we'll set the status to `errored` and will not continue to send transfers until the bank details are updated. For external accounts, possible values are `new` and `errored`. + /// Validations aren't run against external accounts because they're only used for payouts. + /// This means the other statuses don't apply. + /// If a transfer fails, the status is set to `errored` and transfers are stopped until account details are updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl Object for BankAccount { + type Id = BankAccountId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "bank_account" + } +} diff --git a/ft-stripe/src/resources/bank_account_ext.rs b/ft-stripe/src/resources/bank_account_ext.rs new file mode 100644 index 0000000..0da1534 --- /dev/null +++ b/ft-stripe/src/resources/bank_account_ext.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `BankAccount`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum BankAccountStatus { + Errored, + New, + Validated, + VerificationFailed, + Verified, +} + +impl BankAccountStatus { + pub fn as_str(self) -> &'static str { + match self { + BankAccountStatus::Errored => "errored", + BankAccountStatus::New => "new", + BankAccountStatus::Validated => "validated", + BankAccountStatus::VerificationFailed => "verification_failed", + BankAccountStatus::Verified => "verified", + } + } +} + +impl AsRef for BankAccountStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for BankAccountStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/card.rs b/ft-stripe/src/resources/card.rs new file mode 100644 index 0000000..d62f0ab --- /dev/null +++ b/ft-stripe/src/resources/card.rs @@ -0,0 +1,217 @@ +use crate::ids::CardId; +use crate::params::{Expandable, Metadata, Object}; +use crate::resources::{Account, Currency, Customer, Recipient}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Card". +/// +/// For more details see [https://stripe.com/docs/api/cards/object](https://stripe.com/docs/api/cards/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Card { + /// Unique identifier for the object. + pub id: CardId, + + /// The account this card belongs to. + /// + /// This attribute will not be in the card object if the card belongs to a customer or recipient instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub account: Option>, + + /// City/District/Suburb/Town/Village. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_city: Option, + + /// Billing address country, if provided when creating card. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_country: Option, + + /// Address line 1 (Street address/PO Box/Company name). + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line1: Option, + + /// If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line1_check: Option, + + /// Address line 2 (Apartment/Suite/Unit/Building). + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line2: Option, + + /// State/County/Province/Region. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_state: Option, + + /// ZIP or postal code. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_zip: Option, + + /// If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_zip_check: Option, + + /// A set of available payout methods for this card. + /// + /// Will be either `["standard"]` or `["standard", "instant"]`. + /// Only values from this set should be passed as the `method` when creating a transfer. + #[serde(skip_serializing_if = "Option::is_none")] + pub available_payout_methods: Option>, + + /// Card brand. + /// + /// Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option, + + /// Two-letter ISO code representing the country of the card. + /// + /// You could use this attribute to get a sense of the international breakdown of cards you've collected. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The customer that this card belongs to. + /// + /// This attribute will not be in the card object if the card belongs to an account or recipient instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc_check: Option, + + /// Whether this card is the default external account for its currency. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_for_currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// (For tokenized numbers only.) The last four digits of the device account number. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_last4: Option, + + /// Two-digit number representing the card's expiration month. + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_month: Option, + + /// Four-digit number representing the card's expiration year. + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_year: Option, + + /// Uniquely identifies this particular card number. + /// + /// You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// Card funding type. + /// + /// Can be `credit`, `debit`, `prepaid`, or `unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub funding: Option, + + /// The last four digits of the card. + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// Cardholder name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// The recipient that this card belongs to. + /// + /// This attribute will not be in the card object if the card belongs to a customer or account instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub recipient: Option>, + + /// If the card number is tokenized, this is the method that was used. + /// + /// Can be `apple_pay` or `google_pay`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tokenization_method: Option, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +pub enum CheckResult { + #[serde(rename = "pass")] + Pass, + #[serde(rename = "fail")] + Failed, + #[serde(rename = "unavailable")] + Unavailable, + #[serde(rename = "unchecked")] + Unchecked, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +pub enum CardBrand { + #[serde(rename = "American Express")] + AmericanExpress, + #[serde(rename = "Diners Club")] + DinersClub, + #[serde(rename = "Discover")] + Discover, + #[serde(rename = "JCB")] + JCB, + #[serde(rename = "Visa")] + Visa, + #[serde(rename = "MasterCard")] + MasterCard, + #[serde(rename = "UnionPay")] + UnionPay, + + /// An unknown card brand. + /// + /// May also be a variant not yet supported by the library. + #[serde(other)] + #[serde(rename = "Unknown")] + Unknown, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +pub enum CardType { + #[serde(rename = "credit")] + Credit, + #[serde(rename = "debit")] + Debit, + #[serde(rename = "prepaid")] + Prepaid, + + /// An unknown card type. + /// + /// May also be a variant not yet supported by the library. + #[serde(other)] + #[serde(rename = "unknown")] + Unknown, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TokenizationMethod { + ApplePay, + AndroidPay, + + /// A variant not yet supported by the library. + /// It is an error to send `Other` as part of a request. + #[serde(other, skip_serializing)] + Other, +} + +impl Object for Card { + type Id = CardId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "card" + } +} diff --git a/ft-stripe/src/resources/charge.rs b/ft-stripe/src/resources/charge.rs new file mode 100644 index 0000000..490223b --- /dev/null +++ b/ft-stripe/src/resources/charge.rs @@ -0,0 +1,626 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ChargeId, CustomerId, PaymentIntentId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Account, Application, ApplicationFee, BalanceTransaction, BillingDetails, ChargeSourceParams, + Currency, Customer, FraudDetailsReport, Invoice, Order, PaymentIntent, PaymentMethodDetails, + PaymentSource, Refund, Review, Shipping, Transfer, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Charge". +/// +/// For more details see [https://stripe.com/docs/api/charges/object](https://stripe.com/docs/api/charges/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Charge { + /// Unique identifier for the object. + pub id: ChargeId, + + /// Amount intended to be collected by this payment. + /// + /// A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). + /// The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). + /// The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + pub amount: i64, + + /// Amount in %s refunded (can be less than the amount attribute on the charge if a partial refund was issued). + pub amount_refunded: i64, + + /// ID of the Connect application that created the charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option>, + + /// The application fee (if any) for the charge. + /// + /// [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee: Option>, + + /// The amount of the application fee (if any) for the charge. + /// + /// [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + + /// ID of the balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes). + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + pub billing_details: BillingDetails, + + /// The full statement descriptor that is passed to card networks, and that is displayed on your customers' credit card and bank statements. + /// + /// Allows you to see what the statement descriptor looks like after the static and dynamic portions are combined. + #[serde(skip_serializing_if = "Option::is_none")] + pub calculated_statement_descriptor: Option, + + /// If the charge was created without capturing, this Boolean represents whether it is still uncaptured or has since been captured. + pub captured: bool, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// ID of the customer this charge is for if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// Whether the charge has been disputed. + pub disputed: bool, + + /// Error code explaining reason for charge failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_code: Option, + + /// Message to user further explaining reason for charge failure if available. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_message: Option, + + /// Information on fraud assessments for the charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub fraud_details: Option, + + /// ID of the invoice this charge is for if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The account (if any) the charge was made on behalf of without triggering an automatic transfer. + /// + /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option>, + + /// ID of the order this charge is for if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub order: Option>, + + /// Details about whether the payment was accepted, and why. + /// + /// See [understanding declines](https://stripe.com/docs/declines) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, + + /// `true` if the charge succeeded, or was successfully authorized for later capture. + pub paid: bool, + + /// ID of the PaymentIntent associated with this charge, if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// ID of the payment method used in this charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// Details about the payment method at the time of the transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_details: Option, + + /// This is the email address that the receipt for this charge was sent to. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option, + + /// This is the transaction number that appears on email receipts sent for this charge. + /// + /// This attribute will be `null` until a receipt has been sent. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_number: Option, + + /// This is the URL to view the receipt for this charge. + /// + /// The receipt is kept up-to-date to the latest state of the charge, including any refunds. + /// If the charge is for an Invoice, the receipt will be stylized as an Invoice receipt. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_url: Option, + + /// Whether the charge has been fully refunded. + /// + /// If the charge is only partially refunded, this attribute will still be false. + pub refunded: bool, + + /// A list of refunds that have been applied to the charge. + pub refunds: List, + + /// ID of the review associated with this charge if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub review: Option>, + + /// Shipping information for the charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// Source information for the charge. + pub source: Option, + + /// The transfer ID which created this charge. + /// + /// Only present if the charge came from another Stripe account. + /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_transfer: Option>, + + /// For card charges, use `statement_descriptor_suffix` instead. + /// + /// Otherwise, you can use this value as the complete description of a charge on your customers’ statements. + /// Must contain at least one letter, maximum 22 characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// Provides information about the charge that customers see on their statements. + /// + /// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. + /// Maximum 22 characters for the concatenated descriptor. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_suffix: Option, + + /// The status of the payment is either `succeeded`, `pending`, or `failed`. + pub status: String, + + /// ID of the transfer to the `destination` account (only applicable if the charge was created using the `destination` parameter). + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer: Option>, + + /// An optional dictionary including the account to automatically transfer to as part of a destination charge. + /// + /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_data: Option, + + /// A string that identifies this transaction as part of a group. + /// + /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option, +} + +impl Charge { + /// Returns a list of charges you’ve previously created. + /// + /// The charges are returned in sorted order, with the most recent charges appearing first. + pub fn list(client: &Client, params: ListCharges<'_>) -> Response> { + client.get_query("/charges", ¶ms) + } + + /// To charge a credit card or other payment source, you create a `Charge` object. + /// + /// If your API key is in test mode, the supplied payment source (e.g., card) won’t actually be charged, although everything else will occur as if in live mode. + /// (Stripe assumes that the charge would have completed successfully). + pub fn create(client: &Client, params: CreateCharge<'_>) -> Response { + client.post_form("/charges", ¶ms) + } + + /// Retrieves the details of a charge that has previously been created. + /// + /// Supply the unique charge ID that was returned from your previous request, and Stripe will return the corresponding charge information. + /// The same information is returned when creating or refunding the charge. + pub fn retrieve(client: &Client, id: &ChargeId, expand: &[&str]) -> Response { + client.get_query(&format!("/charges/{}", id), &Expand { expand }) + } + + /// Updates the specified charge by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. + pub fn update(client: &Client, id: &ChargeId, params: UpdateCharge<'_>) -> Response { + client.post_form(&format!("/charges/{}", id), ¶ms) + } +} + +impl Object for Charge { + type Id = ChargeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "charge" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct FraudDetails { + /// Assessments from Stripe. + /// + /// If set, the value is `fraudulent`. + #[serde(skip_serializing_if = "Option::is_none")] + pub stripe_report: Option, + + /// Assessments reported by you. + /// + /// If set, possible values of are `safe` and `fraudulent`. + #[serde(skip_serializing_if = "Option::is_none")] + pub user_report: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ChargeOutcome { + /// Possible values are `approved_by_network`, `declined_by_network`, `not_sent_to_network`, and `reversed_after_approval`. + /// + /// The value `reversed_after_approval` indicates the payment was [blocked by Stripe](https://stripe.com/docs/declines#blocked-payments) after bank authorization, and may temporarily appear as "pending" on a cardholder's statement. + #[serde(skip_serializing_if = "Option::is_none")] + pub network_status: Option, + + /// An enumerated value providing a more detailed explanation of the outcome's `type`. + /// + /// Charges blocked by Radar's default block rule have the value `highest_risk_level`. + /// Charges placed in review by Radar's default review rule have the value `elevated_risk_level`. + /// Charges authorized, blocked, or placed in review by custom rules have the value `rule`. + /// See [understanding declines](https://stripe.com/docs/declines) for more details. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + + /// Stripe's evaluation of the riskiness of the payment. + /// + /// Possible values for evaluated payments are `normal`, `elevated`, `highest`. + /// For non-card payments, and card-based payments predating the public assignment of risk levels, this field will have the value `not_assessed`. + /// In the event of an error in the evaluation, this field will have the value `unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub risk_level: Option, + + /// Stripe's evaluation of the riskiness of the payment. + /// + /// Possible values for evaluated payments are between 0 and 100. + /// For non-card payments, card-based payments predating the public assignment of risk scores, or in the event of an error during evaluation, this field will not be present. + /// This field is only available with Radar for Fraud Teams. + #[serde(skip_serializing_if = "Option::is_none")] + pub risk_score: Option, + + /// The ID of the Radar rule that matched the payment, if applicable. + #[serde(skip_serializing_if = "Option::is_none")] + pub rule: Option>, + + /// A human-readable description of the outcome type and reason, designed for you (the recipient of the payment), not your customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub seller_message: Option, + + /// Possible values are `authorized`, `manual_review`, `issuer_declined`, `blocked`, and `invalid`. + /// + /// See [understanding declines](https://stripe.com/docs/declines) and [Radar reviews](https://stripe.com/docs/radar/reviews) for details. + #[serde(rename = "type")] + pub type_: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferData { + /// The amount transferred to the destination account, if specified. + /// + /// By default, the entire charge amount is transferred to the destination account. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// ID of an existing, connected Stripe account to transfer funds to if `transfer_data` was specified in the charge request. + pub destination: Expandable, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Rule { + /// The action taken on the payment. + pub action: String, + + /// Unique identifier for the object. + pub id: String, + + /// The predicate to evaluate the payment against. + pub predicate: String, +} + +/// The parameters for `Charge::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateCharge<'a> { + /// Amount intended to be collected by this payment. + /// + /// A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). + /// The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). + /// The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee: Option, + + /// A fee in %s that will be applied to the charge and transferred to the application owner's Stripe account. + /// + /// The request must be made with an OAuth key or the `Stripe-Account` header in order to take an application fee. + /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees). + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + + /// Whether to immediately capture the charge. + /// + /// Defaults to `true`. + /// When `false`, the charge issues an authorization (or pre-authorization), and will need to be [captured](https://stripe.com/docs/api#capture_charge) later. + /// Uncaptured charges expire in _seven days_. + /// For more information, see the [authorizing charges and settling later](https://stripe.com/docs/charges/placing-a-hold) documentation. + #[serde(skip_serializing_if = "Option::is_none")] + pub capture: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The ID of an existing customer that will be charged in this request. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// An arbitrary string which you can attach to a `Charge` object. + /// + /// It is displayed when in the web interface alongside the charge. + /// Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The Stripe account ID for which these funds are intended. + /// + /// Automatically set if you use the `destination` parameter. + /// For details, see [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/charges-transfers#on-behalf-of). + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option<&'a str>, + + /// The email address to which this charge's [receipt](https://stripe.com/docs/dashboard/receipts) will be sent. + /// + /// The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. + /// If this charge is for a [Customer](https://stripe.com/docs/api/customers/object), the email address specified here will override the customer's email address. + /// If `receipt_email` is specified for a charge in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + + /// Shipping information for the charge. + /// + /// Helps prevent fraud on charges for physical goods. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// A payment source to be charged. + /// + /// This can be the ID of a [card](https://stripe.com/docs/api#cards) (i.e., credit or debit card), a [bank account](https://stripe.com/docs/api#bank_accounts), a [source](https://stripe.com/docs/api#sources), a [token](https://stripe.com/docs/api#tokens), or a [connected account](https://stripe.com/docs/connect/account-debits#charging-a-connected-account). + /// For certain sources---namely, [cards](https://stripe.com/docs/api#cards), [bank accounts](https://stripe.com/docs/api#bank_accounts), and attached [sources](https://stripe.com/docs/api#sources)---you must also pass the ID of the associated customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + + /// For card charges, use `statement_descriptor_suffix` instead. + /// + /// Otherwise, you can use this value as the complete description of a charge on your customers’ statements. + /// Must contain at least one letter, maximum 22 characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + + /// Provides information about the charge that customers see on their statements. + /// + /// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. + /// Maximum 22 characters for the concatenated descriptor. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor_suffix: Option<&'a str>, + + /// An optional dictionary including the account to automatically transfer to as part of a destination charge. + /// + /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_data: Option, + + /// A string that identifies this transaction as part of a group. + /// + /// For details, see [Grouping transactions](https://stripe.com/docs/connect/charges-transfers#transfer-options). + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> CreateCharge<'a> { + pub fn new() -> Self { + CreateCharge { + amount: Default::default(), + application_fee: Default::default(), + application_fee_amount: Default::default(), + capture: Default::default(), + currency: Default::default(), + customer: Default::default(), + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + on_behalf_of: Default::default(), + receipt_email: Default::default(), + shipping: Default::default(), + source: Default::default(), + statement_descriptor: Default::default(), + statement_descriptor_suffix: Default::default(), + transfer_data: Default::default(), + transfer_group: Default::default(), + } + } +} + +/// The parameters for `Charge::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListCharges<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return charges for the customer specified by this customer ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return charges that were created by the PaymentIntent specified by this PaymentIntent ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return charges for this transfer group. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> ListCharges<'a> { + pub fn new() -> Self { + ListCharges { + created: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + payment_intent: Default::default(), + starting_after: Default::default(), + transfer_group: Default::default(), + } + } +} + +/// The parameters for `Charge::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateCharge<'a> { + /// The ID of an existing customer that will be associated with this request. + /// + /// This field may only be updated if there is no existing associated customer with this charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// An arbitrary string which you can attach to a charge object. + /// + /// It is displayed when in the web interface alongside the charge. + /// Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A set of key-value pairs you can attach to a charge giving information about its riskiness. + /// + /// If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. + /// If you believe a charge is safe, include a `user_report` key with a value of `safe`. + /// Stripe will use the information you send to improve our fraud detection algorithms. + #[serde(skip_serializing_if = "Option::is_none")] + pub fraud_details: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// This is the email address that the receipt for this charge will be sent to. + /// + /// If this field is updated, then a new email receipt will be sent to the updated address. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + + /// Shipping information for the charge. + /// + /// Helps prevent fraud on charges for physical goods. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// A string that identifies this transaction as part of a group. + /// + /// `transfer_group` may only be provided if it has not been set. + /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> UpdateCharge<'a> { + pub fn new() -> Self { + UpdateCharge { + customer: Default::default(), + description: Default::default(), + expand: Default::default(), + fraud_details: Default::default(), + metadata: Default::default(), + receipt_email: Default::default(), + shipping: Default::default(), + transfer_group: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct FraudDetailsParams { + pub user_report: FraudDetailsReport, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferDataParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + pub destination: String, +} diff --git a/ft-stripe/src/resources/charge_ext.rs b/ft-stripe/src/resources/charge_ext.rs new file mode 100644 index 0000000..dcf66d3 --- /dev/null +++ b/ft-stripe/src/resources/charge_ext.rs @@ -0,0 +1,55 @@ +use crate::config::{Client, Response}; +use crate::ids::{BankAccountId, CardId, ChargeId, SourceId, TokenId}; +use crate::params::Object; +use crate::resources::{Charge, Rule}; +use serde::{Deserialize, Serialize}; + +/// The set of PaymentSource parameters that can be used to create a charge. +/// +/// For more details see [https://stripe.com/docs/api/charges/create#create_charge-source](https://stripe.com/docs/api/charges/create#create_charge-source). +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum ChargeSourceParams { + Token(TokenId), + Source(SourceId), + Card(CardId), + BankAccount(BankAccountId), +} + +/// The set of parameters that can be used when capturing a charge object. +/// +/// For more details see [https://stripe.com/docs/api#charge_capture](https://stripe.com/docs/api#charge_capture). +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct CaptureCharge<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, +} + +impl Charge { + /// Capture captures a previously created charge with capture set to false. + /// + /// For more details see [https://stripe.com/docs/api#charge_capture](https://stripe.com/docs/api#charge_capture). + pub fn capture( + client: &Client, + charge_id: &ChargeId, + params: CaptureCharge<'_>, + ) -> Response { + client.post_form(&format!("/charges/{}/capture", charge_id), params) + } +} + +impl Object for Rule { + type Id = String; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "" + } +} diff --git a/ft-stripe/src/resources/checkout_session.rs b/ft-stripe/src/resources/checkout_session.rs new file mode 100644 index 0000000..cfebabf --- /dev/null +++ b/ft-stripe/src/resources/checkout_session.rs @@ -0,0 +1,1042 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::CheckoutSessionId; +use crate::params::{Expandable, List, Metadata, Object}; +use crate::resources::{ + CheckoutSessionItem, Currency, Customer, PaymentIntent, Plan, SetupIntent, Shipping, Sku, + Subscription, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Session". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CheckoutSession { + /// Unique identifier for the object. + /// + /// Used to pass to `redirectToCheckout` in Stripe.js. + pub id: CheckoutSessionId, + + /// The value (`auto` or `required`) for whether Checkout collected the + /// customer's billing address. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_address_collection: Option, + + /// The URL the customer will be directed to if they decide to cancel payment and return to your website. + pub cancel_url: String, + + /// A unique string to reference the Checkout Session. + /// + /// This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_reference_id: Option, + + /// The ID of the customer for this session. + /// For Checkout Sessions in `payment` or `subscription` mode, Checkout + /// will create a new customer object based on information provided + /// during the session unless an existing customer was provided when + /// the session was created. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// If provided, this value will be used when the Customer object is created. + /// If not provided, customers will be asked to enter their email address. + /// Use this parameter to prefill customer data if you already have an email + /// on file. + /// + /// To access information about the customer once a session is complete, use the `customer` field. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_email: Option, + + /// The line items, plans, or SKUs purchased by the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_items: Option>, + + /// The line items purchased by the customer. + /// + /// [Expand](https://stripe.com/docs/api/expanding_objects) this field to include it in the response. + #[serde(default)] + pub line_items: List, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// The IETF language tag of the locale Checkout is displayed in. + /// + /// If blank or `auto`, the browser's locale is used. + #[serde(skip_serializing_if = "Option::is_none")] + pub locale: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The mode of the Checkout Session, one of `payment`, `setup`, or `subscription`. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + + /// The ID of the PaymentIntent for Checkout Sessions in `payment` mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// A list of the types of payment methods (e.g. + /// + /// card) this Checkout Session is allowed to accept. + pub payment_method_types: Vec, + + /// The ID of the SetupIntent for Checkout Sessions in `setup` mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub setup_intent: Option>, + + /// Shipping information for this Checkout Session. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// When set, provides configuration for Checkout to collect a shipping address from a customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_address_collection: Option, + + /// Describes the type of transaction being performed by Checkout in order to customize + /// relevant text on the page, such as the submit button. + /// + /// `submit_type` can only be specified on Checkout Sessions in `payment` mode, but not Checkout Sessions in `subscription` or `setup` mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub submit_type: Option, + + /// The ID of the subscription for Checkout Sessions in `subscription` mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option>, + + /// The URL the customer will be directed to after the payment or + /// subscription creation is successful. + pub success_url: String, +} + +impl Object for CheckoutSession { + type Id = CheckoutSessionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "checkout.session" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CheckoutSessionDisplayItem { + /// Amount for the display item. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub custom: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// Quantity of the display item being purchased. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sku: Option, + + /// The type of display item. + /// + /// One of `custom`, `plan` or `sku`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CheckoutSessionCustomDisplayItemDescription { + /// The description of the line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The images of the line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub images: Option>, + + /// The name of the line item. + pub name: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ShippingAddressCollection { + /// An array of two-letter ISO country codes representing which countries Checkout should provide as options for + /// shipping locations. + /// + /// Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. + pub allowed_countries: Vec, +} + +/// An enum representing the possible values of an `CheckoutSession`'s `locale` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CheckoutSessionLocale { + Auto, + Da, + De, + En, + Es, + Fi, + Fr, + It, + Ja, + Ms, + Nb, + Nl, + Pl, + Pt, + #[serde(rename = "pt-BR")] + PtBr, + Sv, + Zh, +} + +impl CheckoutSessionLocale { + pub fn as_str(self) -> &'static str { + match self { + CheckoutSessionLocale::Auto => "auto", + CheckoutSessionLocale::Da => "da", + CheckoutSessionLocale::De => "de", + CheckoutSessionLocale::En => "en", + CheckoutSessionLocale::Es => "es", + CheckoutSessionLocale::Fi => "fi", + CheckoutSessionLocale::Fr => "fr", + CheckoutSessionLocale::It => "it", + CheckoutSessionLocale::Ja => "ja", + CheckoutSessionLocale::Ms => "ms", + CheckoutSessionLocale::Nb => "nb", + CheckoutSessionLocale::Nl => "nl", + CheckoutSessionLocale::Pl => "pl", + CheckoutSessionLocale::Pt => "pt", + CheckoutSessionLocale::PtBr => "pt-BR", + CheckoutSessionLocale::Sv => "sv", + CheckoutSessionLocale::Zh => "zh", + } + } +} + +impl AsRef for CheckoutSessionLocale { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CheckoutSessionLocale { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CheckoutSession`'s `mode` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CheckoutSessionMode { + Payment, + Setup, + Subscription, +} + +impl CheckoutSessionMode { + pub fn as_str(self) -> &'static str { + match self { + CheckoutSessionMode::Payment => "payment", + CheckoutSessionMode::Setup => "setup", + CheckoutSessionMode::Subscription => "subscription", + } + } +} + +impl AsRef for CheckoutSessionMode { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CheckoutSessionMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CheckoutSession`'s `submit_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CheckoutSessionSubmitType { + Auto, + Book, + Donate, + Pay, +} + +impl CheckoutSessionSubmitType { + pub fn as_str(self) -> &'static str { + match self { + CheckoutSessionSubmitType::Auto => "auto", + CheckoutSessionSubmitType::Book => "book", + CheckoutSessionSubmitType::Donate => "donate", + CheckoutSessionSubmitType::Pay => "pay", + } + } +} + +impl AsRef for CheckoutSessionSubmitType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CheckoutSessionSubmitType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ShippingAddressCollection`'s `allowed_countries` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ShippingAddressCollectionAllowedCountries { + #[serde(rename = "AC")] + Ac, + #[serde(rename = "AD")] + Ad, + #[serde(rename = "AE")] + Ae, + #[serde(rename = "AF")] + Af, + #[serde(rename = "AG")] + Ag, + #[serde(rename = "AI")] + Ai, + #[serde(rename = "AL")] + Al, + #[serde(rename = "AM")] + Am, + #[serde(rename = "AO")] + Ao, + #[serde(rename = "AQ")] + Aq, + #[serde(rename = "AR")] + Ar, + #[serde(rename = "AT")] + At, + #[serde(rename = "AU")] + Au, + #[serde(rename = "AW")] + Aw, + #[serde(rename = "AX")] + Ax, + #[serde(rename = "AZ")] + Az, + #[serde(rename = "BA")] + Ba, + #[serde(rename = "BB")] + Bb, + #[serde(rename = "BD")] + Bd, + #[serde(rename = "BE")] + Be, + #[serde(rename = "BF")] + Bf, + #[serde(rename = "BG")] + Bg, + #[serde(rename = "BH")] + Bh, + #[serde(rename = "BI")] + Bi, + #[serde(rename = "BJ")] + Bj, + #[serde(rename = "BL")] + Bl, + #[serde(rename = "BM")] + Bm, + #[serde(rename = "BN")] + Bn, + #[serde(rename = "BO")] + Bo, + #[serde(rename = "BQ")] + Bq, + #[serde(rename = "BR")] + Br, + #[serde(rename = "BS")] + Bs, + #[serde(rename = "BT")] + Bt, + #[serde(rename = "BV")] + Bv, + #[serde(rename = "BW")] + Bw, + #[serde(rename = "BY")] + By, + #[serde(rename = "BZ")] + Bz, + #[serde(rename = "CA")] + Ca, + #[serde(rename = "CD")] + Cd, + #[serde(rename = "CF")] + Cf, + #[serde(rename = "CG")] + Cg, + #[serde(rename = "CH")] + Ch, + #[serde(rename = "CI")] + Ci, + #[serde(rename = "CK")] + Ck, + #[serde(rename = "CL")] + Cl, + #[serde(rename = "CM")] + Cm, + #[serde(rename = "CN")] + Cn, + #[serde(rename = "CO")] + Co, + #[serde(rename = "CR")] + Cr, + #[serde(rename = "CV")] + Cv, + #[serde(rename = "CW")] + Cw, + #[serde(rename = "CY")] + Cy, + #[serde(rename = "CZ")] + Cz, + #[serde(rename = "DE")] + De, + #[serde(rename = "DJ")] + Dj, + #[serde(rename = "DK")] + Dk, + #[serde(rename = "DM")] + Dm, + #[serde(rename = "DO")] + Do, + #[serde(rename = "DZ")] + Dz, + #[serde(rename = "EC")] + Ec, + #[serde(rename = "EE")] + Ee, + #[serde(rename = "EG")] + Eg, + #[serde(rename = "EH")] + Eh, + #[serde(rename = "ER")] + Er, + #[serde(rename = "ES")] + Es, + #[serde(rename = "ET")] + Et, + #[serde(rename = "FI")] + Fi, + #[serde(rename = "FJ")] + Fj, + #[serde(rename = "FK")] + Fk, + #[serde(rename = "FO")] + Fo, + #[serde(rename = "FR")] + Fr, + #[serde(rename = "GA")] + Ga, + #[serde(rename = "GB")] + Gb, + #[serde(rename = "GD")] + Gd, + #[serde(rename = "GE")] + Ge, + #[serde(rename = "GF")] + Gf, + #[serde(rename = "GG")] + Gg, + #[serde(rename = "GH")] + Gh, + #[serde(rename = "GI")] + Gi, + #[serde(rename = "GL")] + Gl, + #[serde(rename = "GM")] + Gm, + #[serde(rename = "GN")] + Gn, + #[serde(rename = "GP")] + Gp, + #[serde(rename = "GQ")] + Gq, + #[serde(rename = "GR")] + Gr, + #[serde(rename = "GS")] + Gs, + #[serde(rename = "GT")] + Gt, + #[serde(rename = "GU")] + Gu, + #[serde(rename = "GW")] + Gw, + #[serde(rename = "GY")] + Gy, + #[serde(rename = "HK")] + Hk, + #[serde(rename = "HN")] + Hn, + #[serde(rename = "HR")] + Hr, + #[serde(rename = "HT")] + Ht, + #[serde(rename = "HU")] + Hu, + #[serde(rename = "ID")] + Id, + #[serde(rename = "IE")] + Ie, + #[serde(rename = "IL")] + Il, + #[serde(rename = "IM")] + Im, + #[serde(rename = "IN")] + In, + #[serde(rename = "IO")] + Io, + #[serde(rename = "IQ")] + Iq, + #[serde(rename = "IS")] + Is, + #[serde(rename = "IT")] + It, + #[serde(rename = "JE")] + Je, + #[serde(rename = "JM")] + Jm, + #[serde(rename = "JO")] + Jo, + #[serde(rename = "JP")] + Jp, + #[serde(rename = "KE")] + Ke, + #[serde(rename = "KG")] + Kg, + #[serde(rename = "KH")] + Kh, + #[serde(rename = "KI")] + Ki, + #[serde(rename = "KM")] + Km, + #[serde(rename = "KN")] + Kn, + #[serde(rename = "KR")] + Kr, + #[serde(rename = "KW")] + Kw, + #[serde(rename = "KY")] + Ky, + #[serde(rename = "KZ")] + Kz, + #[serde(rename = "LA")] + La, + #[serde(rename = "LB")] + Lb, + #[serde(rename = "LC")] + Lc, + #[serde(rename = "LI")] + Li, + #[serde(rename = "LK")] + Lk, + #[serde(rename = "LR")] + Lr, + #[serde(rename = "LS")] + Ls, + #[serde(rename = "LT")] + Lt, + #[serde(rename = "LU")] + Lu, + #[serde(rename = "LV")] + Lv, + #[serde(rename = "LY")] + Ly, + #[serde(rename = "MA")] + Ma, + #[serde(rename = "MC")] + Mc, + #[serde(rename = "MD")] + Md, + #[serde(rename = "ME")] + Me, + #[serde(rename = "MF")] + Mf, + #[serde(rename = "MG")] + Mg, + #[serde(rename = "MK")] + Mk, + #[serde(rename = "ML")] + Ml, + #[serde(rename = "MM")] + Mm, + #[serde(rename = "MN")] + Mn, + #[serde(rename = "MO")] + Mo, + #[serde(rename = "MQ")] + Mq, + #[serde(rename = "MR")] + Mr, + #[serde(rename = "MS")] + Ms, + #[serde(rename = "MT")] + Mt, + #[serde(rename = "MU")] + Mu, + #[serde(rename = "MV")] + Mv, + #[serde(rename = "MW")] + Mw, + #[serde(rename = "MX")] + Mx, + #[serde(rename = "MY")] + My, + #[serde(rename = "MZ")] + Mz, + #[serde(rename = "NA")] + Na, + #[serde(rename = "NC")] + Nc, + #[serde(rename = "NE")] + Ne, + #[serde(rename = "NG")] + Ng, + #[serde(rename = "NI")] + Ni, + #[serde(rename = "NL")] + Nl, + #[serde(rename = "NO")] + No, + #[serde(rename = "NP")] + Np, + #[serde(rename = "NR")] + Nr, + #[serde(rename = "NU")] + Nu, + #[serde(rename = "NZ")] + Nz, + #[serde(rename = "OM")] + Om, + #[serde(rename = "PA")] + Pa, + #[serde(rename = "PE")] + Pe, + #[serde(rename = "PF")] + Pf, + #[serde(rename = "PG")] + Pg, + #[serde(rename = "PH")] + Ph, + #[serde(rename = "PK")] + Pk, + #[serde(rename = "PL")] + Pl, + #[serde(rename = "PM")] + Pm, + #[serde(rename = "PN")] + Pn, + #[serde(rename = "PR")] + Pr, + #[serde(rename = "PS")] + Ps, + #[serde(rename = "PT")] + Pt, + #[serde(rename = "PY")] + Py, + #[serde(rename = "QA")] + Qa, + #[serde(rename = "RE")] + Re, + #[serde(rename = "RO")] + Ro, + #[serde(rename = "RS")] + Rs, + #[serde(rename = "RU")] + Ru, + #[serde(rename = "RW")] + Rw, + #[serde(rename = "SA")] + Sa, + #[serde(rename = "SB")] + Sb, + #[serde(rename = "SC")] + Sc, + #[serde(rename = "SE")] + Se, + #[serde(rename = "SG")] + Sg, + #[serde(rename = "SH")] + Sh, + #[serde(rename = "SI")] + Si, + #[serde(rename = "SJ")] + Sj, + #[serde(rename = "SK")] + Sk, + #[serde(rename = "SL")] + Sl, + #[serde(rename = "SM")] + Sm, + #[serde(rename = "SN")] + Sn, + #[serde(rename = "SO")] + So, + #[serde(rename = "SR")] + Sr, + #[serde(rename = "SS")] + Ss, + #[serde(rename = "ST")] + St, + #[serde(rename = "SV")] + Sv, + #[serde(rename = "SX")] + Sx, + #[serde(rename = "SZ")] + Sz, + #[serde(rename = "TA")] + Ta, + #[serde(rename = "TC")] + Tc, + #[serde(rename = "TD")] + Td, + #[serde(rename = "TF")] + Tf, + #[serde(rename = "TG")] + Tg, + #[serde(rename = "TH")] + Th, + #[serde(rename = "TJ")] + Tj, + #[serde(rename = "TK")] + Tk, + #[serde(rename = "TL")] + Tl, + #[serde(rename = "TM")] + Tm, + #[serde(rename = "TN")] + Tn, + #[serde(rename = "TO")] + To, + #[serde(rename = "TR")] + Tr, + #[serde(rename = "TT")] + Tt, + #[serde(rename = "TV")] + Tv, + #[serde(rename = "TW")] + Tw, + #[serde(rename = "TZ")] + Tz, + #[serde(rename = "UA")] + Ua, + #[serde(rename = "UG")] + Ug, + #[serde(rename = "US")] + Us, + #[serde(rename = "UY")] + Uy, + #[serde(rename = "UZ")] + Uz, + #[serde(rename = "VA")] + Va, + #[serde(rename = "VC")] + Vc, + #[serde(rename = "VE")] + Ve, + #[serde(rename = "VG")] + Vg, + #[serde(rename = "VN")] + Vn, + #[serde(rename = "VU")] + Vu, + #[serde(rename = "WF")] + Wf, + #[serde(rename = "WS")] + Ws, + #[serde(rename = "XK")] + Xk, + #[serde(rename = "YE")] + Ye, + #[serde(rename = "YT")] + Yt, + #[serde(rename = "ZA")] + Za, + #[serde(rename = "ZM")] + Zm, + #[serde(rename = "ZW")] + Zw, + #[serde(rename = "ZZ")] + Zz, +} + +impl ShippingAddressCollectionAllowedCountries { + pub fn as_str(self) -> &'static str { + match self { + ShippingAddressCollectionAllowedCountries::Ac => "AC", + ShippingAddressCollectionAllowedCountries::Ad => "AD", + ShippingAddressCollectionAllowedCountries::Ae => "AE", + ShippingAddressCollectionAllowedCountries::Af => "AF", + ShippingAddressCollectionAllowedCountries::Ag => "AG", + ShippingAddressCollectionAllowedCountries::Ai => "AI", + ShippingAddressCollectionAllowedCountries::Al => "AL", + ShippingAddressCollectionAllowedCountries::Am => "AM", + ShippingAddressCollectionAllowedCountries::Ao => "AO", + ShippingAddressCollectionAllowedCountries::Aq => "AQ", + ShippingAddressCollectionAllowedCountries::Ar => "AR", + ShippingAddressCollectionAllowedCountries::At => "AT", + ShippingAddressCollectionAllowedCountries::Au => "AU", + ShippingAddressCollectionAllowedCountries::Aw => "AW", + ShippingAddressCollectionAllowedCountries::Ax => "AX", + ShippingAddressCollectionAllowedCountries::Az => "AZ", + ShippingAddressCollectionAllowedCountries::Ba => "BA", + ShippingAddressCollectionAllowedCountries::Bb => "BB", + ShippingAddressCollectionAllowedCountries::Bd => "BD", + ShippingAddressCollectionAllowedCountries::Be => "BE", + ShippingAddressCollectionAllowedCountries::Bf => "BF", + ShippingAddressCollectionAllowedCountries::Bg => "BG", + ShippingAddressCollectionAllowedCountries::Bh => "BH", + ShippingAddressCollectionAllowedCountries::Bi => "BI", + ShippingAddressCollectionAllowedCountries::Bj => "BJ", + ShippingAddressCollectionAllowedCountries::Bl => "BL", + ShippingAddressCollectionAllowedCountries::Bm => "BM", + ShippingAddressCollectionAllowedCountries::Bn => "BN", + ShippingAddressCollectionAllowedCountries::Bo => "BO", + ShippingAddressCollectionAllowedCountries::Bq => "BQ", + ShippingAddressCollectionAllowedCountries::Br => "BR", + ShippingAddressCollectionAllowedCountries::Bs => "BS", + ShippingAddressCollectionAllowedCountries::Bt => "BT", + ShippingAddressCollectionAllowedCountries::Bv => "BV", + ShippingAddressCollectionAllowedCountries::Bw => "BW", + ShippingAddressCollectionAllowedCountries::By => "BY", + ShippingAddressCollectionAllowedCountries::Bz => "BZ", + ShippingAddressCollectionAllowedCountries::Ca => "CA", + ShippingAddressCollectionAllowedCountries::Cd => "CD", + ShippingAddressCollectionAllowedCountries::Cf => "CF", + ShippingAddressCollectionAllowedCountries::Cg => "CG", + ShippingAddressCollectionAllowedCountries::Ch => "CH", + ShippingAddressCollectionAllowedCountries::Ci => "CI", + ShippingAddressCollectionAllowedCountries::Ck => "CK", + ShippingAddressCollectionAllowedCountries::Cl => "CL", + ShippingAddressCollectionAllowedCountries::Cm => "CM", + ShippingAddressCollectionAllowedCountries::Cn => "CN", + ShippingAddressCollectionAllowedCountries::Co => "CO", + ShippingAddressCollectionAllowedCountries::Cr => "CR", + ShippingAddressCollectionAllowedCountries::Cv => "CV", + ShippingAddressCollectionAllowedCountries::Cw => "CW", + ShippingAddressCollectionAllowedCountries::Cy => "CY", + ShippingAddressCollectionAllowedCountries::Cz => "CZ", + ShippingAddressCollectionAllowedCountries::De => "DE", + ShippingAddressCollectionAllowedCountries::Dj => "DJ", + ShippingAddressCollectionAllowedCountries::Dk => "DK", + ShippingAddressCollectionAllowedCountries::Dm => "DM", + ShippingAddressCollectionAllowedCountries::Do => "DO", + ShippingAddressCollectionAllowedCountries::Dz => "DZ", + ShippingAddressCollectionAllowedCountries::Ec => "EC", + ShippingAddressCollectionAllowedCountries::Ee => "EE", + ShippingAddressCollectionAllowedCountries::Eg => "EG", + ShippingAddressCollectionAllowedCountries::Eh => "EH", + ShippingAddressCollectionAllowedCountries::Er => "ER", + ShippingAddressCollectionAllowedCountries::Es => "ES", + ShippingAddressCollectionAllowedCountries::Et => "ET", + ShippingAddressCollectionAllowedCountries::Fi => "FI", + ShippingAddressCollectionAllowedCountries::Fj => "FJ", + ShippingAddressCollectionAllowedCountries::Fk => "FK", + ShippingAddressCollectionAllowedCountries::Fo => "FO", + ShippingAddressCollectionAllowedCountries::Fr => "FR", + ShippingAddressCollectionAllowedCountries::Ga => "GA", + ShippingAddressCollectionAllowedCountries::Gb => "GB", + ShippingAddressCollectionAllowedCountries::Gd => "GD", + ShippingAddressCollectionAllowedCountries::Ge => "GE", + ShippingAddressCollectionAllowedCountries::Gf => "GF", + ShippingAddressCollectionAllowedCountries::Gg => "GG", + ShippingAddressCollectionAllowedCountries::Gh => "GH", + ShippingAddressCollectionAllowedCountries::Gi => "GI", + ShippingAddressCollectionAllowedCountries::Gl => "GL", + ShippingAddressCollectionAllowedCountries::Gm => "GM", + ShippingAddressCollectionAllowedCountries::Gn => "GN", + ShippingAddressCollectionAllowedCountries::Gp => "GP", + ShippingAddressCollectionAllowedCountries::Gq => "GQ", + ShippingAddressCollectionAllowedCountries::Gr => "GR", + ShippingAddressCollectionAllowedCountries::Gs => "GS", + ShippingAddressCollectionAllowedCountries::Gt => "GT", + ShippingAddressCollectionAllowedCountries::Gu => "GU", + ShippingAddressCollectionAllowedCountries::Gw => "GW", + ShippingAddressCollectionAllowedCountries::Gy => "GY", + ShippingAddressCollectionAllowedCountries::Hk => "HK", + ShippingAddressCollectionAllowedCountries::Hn => "HN", + ShippingAddressCollectionAllowedCountries::Hr => "HR", + ShippingAddressCollectionAllowedCountries::Ht => "HT", + ShippingAddressCollectionAllowedCountries::Hu => "HU", + ShippingAddressCollectionAllowedCountries::Id => "ID", + ShippingAddressCollectionAllowedCountries::Ie => "IE", + ShippingAddressCollectionAllowedCountries::Il => "IL", + ShippingAddressCollectionAllowedCountries::Im => "IM", + ShippingAddressCollectionAllowedCountries::In => "IN", + ShippingAddressCollectionAllowedCountries::Io => "IO", + ShippingAddressCollectionAllowedCountries::Iq => "IQ", + ShippingAddressCollectionAllowedCountries::Is => "IS", + ShippingAddressCollectionAllowedCountries::It => "IT", + ShippingAddressCollectionAllowedCountries::Je => "JE", + ShippingAddressCollectionAllowedCountries::Jm => "JM", + ShippingAddressCollectionAllowedCountries::Jo => "JO", + ShippingAddressCollectionAllowedCountries::Jp => "JP", + ShippingAddressCollectionAllowedCountries::Ke => "KE", + ShippingAddressCollectionAllowedCountries::Kg => "KG", + ShippingAddressCollectionAllowedCountries::Kh => "KH", + ShippingAddressCollectionAllowedCountries::Ki => "KI", + ShippingAddressCollectionAllowedCountries::Km => "KM", + ShippingAddressCollectionAllowedCountries::Kn => "KN", + ShippingAddressCollectionAllowedCountries::Kr => "KR", + ShippingAddressCollectionAllowedCountries::Kw => "KW", + ShippingAddressCollectionAllowedCountries::Ky => "KY", + ShippingAddressCollectionAllowedCountries::Kz => "KZ", + ShippingAddressCollectionAllowedCountries::La => "LA", + ShippingAddressCollectionAllowedCountries::Lb => "LB", + ShippingAddressCollectionAllowedCountries::Lc => "LC", + ShippingAddressCollectionAllowedCountries::Li => "LI", + ShippingAddressCollectionAllowedCountries::Lk => "LK", + ShippingAddressCollectionAllowedCountries::Lr => "LR", + ShippingAddressCollectionAllowedCountries::Ls => "LS", + ShippingAddressCollectionAllowedCountries::Lt => "LT", + ShippingAddressCollectionAllowedCountries::Lu => "LU", + ShippingAddressCollectionAllowedCountries::Lv => "LV", + ShippingAddressCollectionAllowedCountries::Ly => "LY", + ShippingAddressCollectionAllowedCountries::Ma => "MA", + ShippingAddressCollectionAllowedCountries::Mc => "MC", + ShippingAddressCollectionAllowedCountries::Md => "MD", + ShippingAddressCollectionAllowedCountries::Me => "ME", + ShippingAddressCollectionAllowedCountries::Mf => "MF", + ShippingAddressCollectionAllowedCountries::Mg => "MG", + ShippingAddressCollectionAllowedCountries::Mk => "MK", + ShippingAddressCollectionAllowedCountries::Ml => "ML", + ShippingAddressCollectionAllowedCountries::Mm => "MM", + ShippingAddressCollectionAllowedCountries::Mn => "MN", + ShippingAddressCollectionAllowedCountries::Mo => "MO", + ShippingAddressCollectionAllowedCountries::Mq => "MQ", + ShippingAddressCollectionAllowedCountries::Mr => "MR", + ShippingAddressCollectionAllowedCountries::Ms => "MS", + ShippingAddressCollectionAllowedCountries::Mt => "MT", + ShippingAddressCollectionAllowedCountries::Mu => "MU", + ShippingAddressCollectionAllowedCountries::Mv => "MV", + ShippingAddressCollectionAllowedCountries::Mw => "MW", + ShippingAddressCollectionAllowedCountries::Mx => "MX", + ShippingAddressCollectionAllowedCountries::My => "MY", + ShippingAddressCollectionAllowedCountries::Mz => "MZ", + ShippingAddressCollectionAllowedCountries::Na => "NA", + ShippingAddressCollectionAllowedCountries::Nc => "NC", + ShippingAddressCollectionAllowedCountries::Ne => "NE", + ShippingAddressCollectionAllowedCountries::Ng => "NG", + ShippingAddressCollectionAllowedCountries::Ni => "NI", + ShippingAddressCollectionAllowedCountries::Nl => "NL", + ShippingAddressCollectionAllowedCountries::No => "NO", + ShippingAddressCollectionAllowedCountries::Np => "NP", + ShippingAddressCollectionAllowedCountries::Nr => "NR", + ShippingAddressCollectionAllowedCountries::Nu => "NU", + ShippingAddressCollectionAllowedCountries::Nz => "NZ", + ShippingAddressCollectionAllowedCountries::Om => "OM", + ShippingAddressCollectionAllowedCountries::Pa => "PA", + ShippingAddressCollectionAllowedCountries::Pe => "PE", + ShippingAddressCollectionAllowedCountries::Pf => "PF", + ShippingAddressCollectionAllowedCountries::Pg => "PG", + ShippingAddressCollectionAllowedCountries::Ph => "PH", + ShippingAddressCollectionAllowedCountries::Pk => "PK", + ShippingAddressCollectionAllowedCountries::Pl => "PL", + ShippingAddressCollectionAllowedCountries::Pm => "PM", + ShippingAddressCollectionAllowedCountries::Pn => "PN", + ShippingAddressCollectionAllowedCountries::Pr => "PR", + ShippingAddressCollectionAllowedCountries::Ps => "PS", + ShippingAddressCollectionAllowedCountries::Pt => "PT", + ShippingAddressCollectionAllowedCountries::Py => "PY", + ShippingAddressCollectionAllowedCountries::Qa => "QA", + ShippingAddressCollectionAllowedCountries::Re => "RE", + ShippingAddressCollectionAllowedCountries::Ro => "RO", + ShippingAddressCollectionAllowedCountries::Rs => "RS", + ShippingAddressCollectionAllowedCountries::Ru => "RU", + ShippingAddressCollectionAllowedCountries::Rw => "RW", + ShippingAddressCollectionAllowedCountries::Sa => "SA", + ShippingAddressCollectionAllowedCountries::Sb => "SB", + ShippingAddressCollectionAllowedCountries::Sc => "SC", + ShippingAddressCollectionAllowedCountries::Se => "SE", + ShippingAddressCollectionAllowedCountries::Sg => "SG", + ShippingAddressCollectionAllowedCountries::Sh => "SH", + ShippingAddressCollectionAllowedCountries::Si => "SI", + ShippingAddressCollectionAllowedCountries::Sj => "SJ", + ShippingAddressCollectionAllowedCountries::Sk => "SK", + ShippingAddressCollectionAllowedCountries::Sl => "SL", + ShippingAddressCollectionAllowedCountries::Sm => "SM", + ShippingAddressCollectionAllowedCountries::Sn => "SN", + ShippingAddressCollectionAllowedCountries::So => "SO", + ShippingAddressCollectionAllowedCountries::Sr => "SR", + ShippingAddressCollectionAllowedCountries::Ss => "SS", + ShippingAddressCollectionAllowedCountries::St => "ST", + ShippingAddressCollectionAllowedCountries::Sv => "SV", + ShippingAddressCollectionAllowedCountries::Sx => "SX", + ShippingAddressCollectionAllowedCountries::Sz => "SZ", + ShippingAddressCollectionAllowedCountries::Ta => "TA", + ShippingAddressCollectionAllowedCountries::Tc => "TC", + ShippingAddressCollectionAllowedCountries::Td => "TD", + ShippingAddressCollectionAllowedCountries::Tf => "TF", + ShippingAddressCollectionAllowedCountries::Tg => "TG", + ShippingAddressCollectionAllowedCountries::Th => "TH", + ShippingAddressCollectionAllowedCountries::Tj => "TJ", + ShippingAddressCollectionAllowedCountries::Tk => "TK", + ShippingAddressCollectionAllowedCountries::Tl => "TL", + ShippingAddressCollectionAllowedCountries::Tm => "TM", + ShippingAddressCollectionAllowedCountries::Tn => "TN", + ShippingAddressCollectionAllowedCountries::To => "TO", + ShippingAddressCollectionAllowedCountries::Tr => "TR", + ShippingAddressCollectionAllowedCountries::Tt => "TT", + ShippingAddressCollectionAllowedCountries::Tv => "TV", + ShippingAddressCollectionAllowedCountries::Tw => "TW", + ShippingAddressCollectionAllowedCountries::Tz => "TZ", + ShippingAddressCollectionAllowedCountries::Ua => "UA", + ShippingAddressCollectionAllowedCountries::Ug => "UG", + ShippingAddressCollectionAllowedCountries::Us => "US", + ShippingAddressCollectionAllowedCountries::Uy => "UY", + ShippingAddressCollectionAllowedCountries::Uz => "UZ", + ShippingAddressCollectionAllowedCountries::Va => "VA", + ShippingAddressCollectionAllowedCountries::Vc => "VC", + ShippingAddressCollectionAllowedCountries::Ve => "VE", + ShippingAddressCollectionAllowedCountries::Vg => "VG", + ShippingAddressCollectionAllowedCountries::Vn => "VN", + ShippingAddressCollectionAllowedCountries::Vu => "VU", + ShippingAddressCollectionAllowedCountries::Wf => "WF", + ShippingAddressCollectionAllowedCountries::Ws => "WS", + ShippingAddressCollectionAllowedCountries::Xk => "XK", + ShippingAddressCollectionAllowedCountries::Ye => "YE", + ShippingAddressCollectionAllowedCountries::Yt => "YT", + ShippingAddressCollectionAllowedCountries::Za => "ZA", + ShippingAddressCollectionAllowedCountries::Zm => "ZM", + ShippingAddressCollectionAllowedCountries::Zw => "ZW", + ShippingAddressCollectionAllowedCountries::Zz => "ZZ", + } + } +} + +impl AsRef for ShippingAddressCollectionAllowedCountries { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ShippingAddressCollectionAllowedCountries { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/connect_collection_transfer.rs b/ft-stripe/src/resources/connect_collection_transfer.rs new file mode 100644 index 0000000..69e1f4b --- /dev/null +++ b/ft-stripe/src/resources/connect_collection_transfer.rs @@ -0,0 +1,33 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::{Expandable, Object}; +use crate::resources::{Account, Currency}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "ConnectCollectionTransfer". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ConnectCollectionTransfer { + /// Amount transferred, in %s. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// ID of the account that funds are being collected for. + pub destination: Expandable, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, +} + +impl Object for ConnectCollectionTransfer { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "connect_collection_transfer" + } +} diff --git a/ft-stripe/src/resources/coupon.rs b/ft-stripe/src/resources/coupon.rs new file mode 100644 index 0000000..4edfd12 --- /dev/null +++ b/ft-stripe/src/resources/coupon.rs @@ -0,0 +1,318 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::CouponId; +use crate::params::{Deleted, Expand, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::Currency; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Coupon". +/// +/// For more details see [https://stripe.com/docs/api/coupons/object](https://stripe.com/docs/api/coupons/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Coupon { + /// Unique identifier for the object. + pub id: CouponId, + + /// Amount (in the `currency` specified) that will be taken off the subtotal of any invoices for this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_off: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// If `amount_off` has been set, the three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the amount to take off. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// One of `forever`, `once`, and `repeating`. + /// + /// Describes how long a customer who applies this coupon will get the discount. + #[serde(skip_serializing_if = "Option::is_none")] + pub duration: Option, + + /// If `duration` is `repeating`, the number of months the coupon applies. + /// + /// Null if coupon `duration` is `forever` or `once`. + #[serde(skip_serializing_if = "Option::is_none")] + pub duration_in_months: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Maximum number of times this coupon can be redeemed, in total, across all customers, before it is no longer valid. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_redemptions: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// Name of the coupon displayed to customers on for instance invoices or receipts. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon. + /// + /// For example, a coupon with percent_off of 50 will make a %s100 invoice %s50 instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub percent_off: Option, + + /// Date after which the coupon can no longer be redeemed. + #[serde(skip_serializing_if = "Option::is_none")] + pub redeem_by: Option, + + /// Number of times this coupon has been applied to a customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub times_redeemed: Option, + + /// Taking account of the above properties, whether this coupon can still be applied to a customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub valid: Option, +} + +impl Coupon { + /// Returns a list of your coupons. + pub fn list(client: &Client, params: ListCoupons<'_>) -> Response> { + client.get_query("/coupons", ¶ms) + } + + /// You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. + /// + /// Coupon creation is also accessible via the API if you need to create coupons on the fly. A coupon has either a `percent_off` or an `amount_off` and `currency`. + /// If you set an `amount_off`, that amount will be subtracted from any invoice’s subtotal. + /// For example, an invoice with a subtotal of $100 will have a final total of $0 if a coupon with an `amount_off` of 20000 is applied to it and an invoice with a subtotal of $300 will have a final total of $100 if a coupon with an `amount_off` of 20000 is applied to it. + pub fn create(client: &Client, params: CreateCoupon<'_>) -> Response { + client.post_form("/coupons", ¶ms) + } + + /// Retrieves the coupon with the given ID. + pub fn retrieve(client: &Client, id: &CouponId, expand: &[&str]) -> Response { + client.get_query(&format!("/coupons/{}", id), &Expand { expand }) + } + + /// Updates the metadata of a coupon. + /// + /// Other coupon details (currency, duration, amount_off) are, by design, not editable. + pub fn update(client: &Client, id: &CouponId, params: UpdateCoupon<'_>) -> Response { + client.post_form(&format!("/coupons/{}", id), ¶ms) + } + + /// You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. + /// + /// However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can’t redeem the coupon. + /// You can also delete coupons via the API. + pub fn delete(client: &Client, id: &CouponId) -> Response> { + client.delete(&format!("/coupons/{}", id)) + } +} + +impl Object for Coupon { + type Id = CouponId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "coupon" + } +} + +/// The parameters for `Coupon::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateCoupon<'a> { + /// A positive integer representing the amount to subtract from an invoice total (required if `percent_off` is not passed). + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_off: Option, + + /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `amount_off` parameter (required if `amount_off` is passed). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// Specifies how long the discount will be in effect. + /// + /// Can be `forever`, `once`, or `repeating`. + pub duration: CouponDuration, + + /// Required only if `duration` is `repeating`, in which case it must be a positive integer that specifies the number of months the discount will be in effect. + #[serde(skip_serializing_if = "Option::is_none")] + pub duration_in_months: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Unique string of your choice that will be used to identify this coupon when applying it to a customer. + /// + /// If you don't want to specify a particular code, you can leave the ID blank and we'll generate a random code for you. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option<&'a str>, + + /// A positive integer specifying the number of times the coupon can be redeemed before it's no longer valid. + /// + /// For example, you might have a 50% off coupon that the first 20 readers of your blog can use. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_redemptions: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Name of the coupon displayed to customers on, for instance invoices, or receipts. + /// + /// By default the `id` is shown if `name` is not set. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + + /// A positive float larger than 0, and smaller or equal to 100, that represents the discount the coupon will apply (required if `amount_off` is not passed). + #[serde(skip_serializing_if = "Option::is_none")] + pub percent_off: Option, + + /// Unix timestamp specifying the last time at which the coupon can be redeemed. + /// + /// After the redeem_by date, the coupon can no longer be applied to new customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub redeem_by: Option, +} + +impl<'a> CreateCoupon<'a> { + pub fn new(duration: CouponDuration) -> Self { + CreateCoupon { + amount_off: Default::default(), + currency: Default::default(), + duration, + duration_in_months: Default::default(), + expand: Default::default(), + id: Default::default(), + max_redemptions: Default::default(), + metadata: Default::default(), + name: Default::default(), + percent_off: Default::default(), + redeem_by: Default::default(), + } + } +} + +/// The parameters for `Coupon::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListCoupons<'a> { + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListCoupons<'a> { + pub fn new() -> Self { + ListCoupons { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Coupon::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateCoupon<'a> { + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Name of the coupon displayed to customers on, for instance invoices, or receipts. + /// + /// By default the `id` is shown if `name` is not set. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, +} + +impl<'a> UpdateCoupon<'a> { + pub fn new() -> Self { + UpdateCoupon { + expand: Default::default(), + metadata: Default::default(), + name: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Coupon`'s `duration` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CouponDuration { + Forever, + Once, + Repeating, +} + +impl CouponDuration { + pub fn as_str(self) -> &'static str { + match self { + CouponDuration::Forever => "forever", + CouponDuration::Once => "once", + CouponDuration::Repeating => "repeating", + } + } +} + +impl AsRef for CouponDuration { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CouponDuration { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/currency.rs b/ft-stripe/src/resources/currency.rs new file mode 100644 index 0000000..93f9c59 --- /dev/null +++ b/ft-stripe/src/resources/currency.rs @@ -0,0 +1,463 @@ +use crate::params::to_snakecase; +use serde::{Deserialize, Serialize}; + +/// Currency is the list of supported currencies. +/// +/// For more details see https://support.stripe.com/questions/which-currencies-does-stripe-support. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] +pub enum Currency { + #[serde(rename = "aed")] + AED, // United Arab Emirates Dirham + #[serde(rename = "afn")] + AFN, // Afghan Afghani + #[serde(rename = "all")] + ALL, // Albanian Lek + #[serde(rename = "amd")] + AMD, // Armenian Dram + #[serde(rename = "ang")] + ANG, // Netherlands Antillean Gulden + #[serde(rename = "aoa")] + AOA, // Angolan Kwanza + #[serde(rename = "ars")] + ARS, // Argentine Peso + #[serde(rename = "aud")] + AUD, // Australian Dollar + #[serde(rename = "awg")] + AWG, // Aruban Florin + #[serde(rename = "azn")] + AZN, // Azerbaijani Manat + #[serde(rename = "bam")] + BAM, // Bosnia & Herzegovina Convertible Mark + #[serde(rename = "bbd")] + BBD, // Barbadian Dollar + #[serde(rename = "bdt")] + BDT, // Bangladeshi Taka + #[serde(rename = "bgn")] + BGN, // Bulgarian Lev + #[serde(rename = "bif")] + BIF, // Burundian Franc + #[serde(rename = "bmd")] + BMD, // Bermudian Dollar + #[serde(rename = "bnd")] + BND, // Brunei Dollar + #[serde(rename = "bob")] + BOB, // Bolivian Boliviano + #[serde(rename = "brl")] + BRL, // Brazilian Real + #[serde(rename = "bsd")] + BSD, // Bahamian Dollar + #[serde(rename = "bwp")] + BWP, // Botswana Pula + #[serde(rename = "bzd")] + BZD, // Belize Dollar + #[serde(rename = "cad")] + CAD, // Canadian Dollar + #[serde(rename = "cdf")] + CDF, // Congolese Franc + #[serde(rename = "chf")] + CHF, // Swiss Franc + #[serde(rename = "clp")] + CLP, // Chilean Peso + #[serde(rename = "cny")] + CNY, // Chinese Renminbi Yuan + #[serde(rename = "cop")] + COP, // Colombian Peso + #[serde(rename = "crc")] + CRC, // Costa Rican Colón + #[serde(rename = "cve")] + CVE, // Cape Verdean Escudo + #[serde(rename = "czk")] + CZK, // Czech Koruna + #[serde(rename = "djf")] + DJF, // Djiboutian Franc + #[serde(rename = "dkk")] + DKK, // Danish Krone + #[serde(rename = "dop")] + DOP, // Dominican Peso + #[serde(rename = "dzd")] + DZD, // Algerian Dinar + #[serde(rename = "eek")] + EEK, // Estonian Kroon + #[serde(rename = "egp")] + EGP, // Egyptian Pound + #[serde(rename = "etb")] + ETB, // Ethiopian Birr + #[serde(rename = "eur")] + EUR, // Euro + #[serde(rename = "fjd")] + FJD, // Fijian Dollar + #[serde(rename = "fkp")] + FKP, // Falkland Islands Pound + #[serde(rename = "gbp")] + GBP, // British Pound + #[serde(rename = "gel")] + GEL, // Georgian Lari + #[serde(rename = "gip")] + GIP, // Gibraltar Pound + #[serde(rename = "gmd")] + GMD, // Gambian Dalasi + #[serde(rename = "gnf")] + GNF, // Guinean Franc + #[serde(rename = "gtq")] + GTQ, // Guatemalan Quetzal + #[serde(rename = "gyd")] + GYD, // Guyanese Dollar + #[serde(rename = "hkd")] + HKD, // Hong Kong Dollar + #[serde(rename = "hnl")] + HNL, // Honduran Lempira + #[serde(rename = "hrk")] + HRK, // Croatian Kuna + #[serde(rename = "htg")] + HTG, // Haitian Gourde + #[serde(rename = "huf")] + HUF, // Hungarian Forint + #[serde(rename = "idr")] + IDR, // Indonesian Rupiah + #[serde(rename = "ils")] + ILS, // Israeli New Sheqel + #[serde(rename = "inr")] + INR, // Indian Rupee + #[serde(rename = "isk")] + ISK, // Icelandic Króna + #[serde(rename = "jmd")] + JMD, // Jamaican Dollar + #[serde(rename = "jpy")] + JPY, // Japanese Yen + #[serde(rename = "kes")] + KES, // Kenyan Shilling + #[serde(rename = "kgs")] + KGS, // Kyrgyzstani Som + #[serde(rename = "khr")] + KHR, // Cambodian Riel + #[serde(rename = "kmf")] + KMF, // Comorian Franc + #[serde(rename = "krw")] + KRW, // South Korean Won + #[serde(rename = "kyd")] + KYD, // Cayman Islands Dollar + #[serde(rename = "kzt")] + KZT, // Kazakhstani Tenge + #[serde(rename = "lak")] + LAK, // Lao Kip + #[serde(rename = "lbp")] + LBP, // Lebanese Pound + #[serde(rename = "lkr")] + LKR, // Sri Lankan Rupee + #[serde(rename = "lrd")] + LRD, // Liberian Dollar + #[serde(rename = "lsl")] + LSL, // Lesotho Loti + #[serde(rename = "ltl")] + LTL, // Lithuanian Litas + #[serde(rename = "lvl")] + LVL, // Latvian Lats + #[serde(rename = "mad")] + MAD, // Moroccan Dirham + #[serde(rename = "mdl")] + MDL, // Moldovan Leu + #[serde(rename = "mga")] + MGA, // Malagasy Ariary + #[serde(rename = "mkd")] + MKD, // Macedonian Denar + #[serde(rename = "mnt")] + MNT, // Mongolian Tögrög + #[serde(rename = "mop")] + MOP, // Macanese Pataca + #[serde(rename = "mro")] + MRO, // Mauritanian Ouguiya + #[serde(rename = "mur")] + MUR, // Mauritian Rupee + #[serde(rename = "mvr")] + MVR, // Maldivian Rufiyaa + #[serde(rename = "mwk")] + MWK, // Malawian Kwacha + #[serde(rename = "mxn")] + MXN, // Mexican Peso + #[serde(rename = "myr")] + MYR, // Malaysian Ringgit + #[serde(rename = "mzn")] + MZN, // Mozambican Metical + #[serde(rename = "nad")] + NAD, // Namibian Dollar + #[serde(rename = "ngn")] + NGN, // Nigerian Naira + #[serde(rename = "nio")] + NIO, // Nicaraguan Córdoba + #[serde(rename = "nok")] + NOK, // Norwegian Krone + #[serde(rename = "npr")] + NPR, // Nepalese Rupee + #[serde(rename = "nzd")] + NZD, // New Zealand Dollar + #[serde(rename = "pab")] + PAB, // Panamanian Balboa + #[serde(rename = "pen")] + PEN, // Peruvian Nuevo Sol + #[serde(rename = "pgk")] + PGK, // Papua New Guinean Kina + #[serde(rename = "php")] + PHP, // Philippine Peso + #[serde(rename = "pkr")] + PKR, // Pakistani Rupee + #[serde(rename = "pln")] + PLN, // Polish Złoty + #[serde(rename = "pyg")] + PYG, // Paraguayan Guaraní + #[serde(rename = "qar")] + QAR, // Qatari Riyal + #[serde(rename = "ron")] + RON, // Romanian Leu + #[serde(rename = "rsd")] + RSD, // Serbian Dinar + #[serde(rename = "rub")] + RUB, // Russian Ruble + #[serde(rename = "rwf")] + RWF, // Rwandan Franc + #[serde(rename = "sar")] + SAR, // Saudi Riyal + #[serde(rename = "sbd")] + SBD, // Solomon Islands Dollar + #[serde(rename = "scr")] + SCR, // Seychellois Rupee + #[serde(rename = "sek")] + SEK, // Swedish Krona + #[serde(rename = "sgd")] + SGD, // Singapore Dollar + #[serde(rename = "shp")] + SHP, // Saint Helenian Pound + #[serde(rename = "sll")] + SLL, // Sierra Leonean Leone + #[serde(rename = "sos")] + SOS, // Somali Shilling + #[serde(rename = "srd")] + SRD, // Surinamese Dollar + #[serde(rename = "std")] + STD, // São Tomé and Príncipe Dobra + #[serde(rename = "svc")] + SVC, // Salvadoran Colón + #[serde(rename = "szl")] + SZL, // Swazi Lilangeni + #[serde(rename = "thb")] + THB, // Thai Baht + #[serde(rename = "tjs")] + TJS, // Tajikistani Somoni + #[serde(rename = "top")] + TOP, // Tongan Paʻanga + #[serde(rename = "try")] + TRY, // Turkish Lira + #[serde(rename = "ttd")] + TTD, // Trinidad and Tobago Dollar + #[serde(rename = "twd")] + TWD, // New Taiwan Dollar + #[serde(rename = "tzs")] + TZS, // Tanzanian Shilling + #[serde(rename = "uah")] + UAH, // Ukrainian Hryvnia + #[serde(rename = "ugx")] + UGX, // Ugandan Shilling + #[serde(rename = "usd")] + USD, // United States Dollar + #[serde(rename = "uyu")] + UYU, // Uruguayan Peso + #[serde(rename = "uzs")] + UZS, // Uzbekistani Som + #[serde(rename = "vef")] + VEF, // Venezuelan Bolívar + #[serde(rename = "vnd")] + VND, // Vietnamese Đồng + #[serde(rename = "vuv")] + VUV, // Vanuatu Vatu + #[serde(rename = "wst")] + WST, // Samoan Tala + #[serde(rename = "xaf")] + XAF, // Central African Cfa Franc + #[serde(rename = "xcd")] + XCD, // East Caribbean Dollar + #[serde(rename = "xof")] + XOF, // West African Cfa Franc + #[serde(rename = "xpf")] + XPF, // Cfp Franc + #[serde(rename = "yer")] + YER, // Yemeni Rial + #[serde(rename = "zar")] + ZAR, // South African Rand + #[serde(rename = "zmw")] + ZMW, // Zambian Kwacha +} + +impl Default for Currency { + fn default() -> Self { + Currency::USD + } +} + +impl std::fmt::Display for Currency { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", to_snakecase(&format!("{:?}", self))) + } +} + +impl std::str::FromStr for Currency { + type Err = ParseCurrencyError; + fn from_str(s: &str) -> Result { + match s { + "aed" => Ok(Currency::AED), + "afn" => Ok(Currency::AFN), + "all" => Ok(Currency::ALL), + "amd" => Ok(Currency::AMD), + "ang" => Ok(Currency::ANG), + "aoa" => Ok(Currency::AOA), + "ars" => Ok(Currency::ARS), + "aud" => Ok(Currency::AUD), + "awg" => Ok(Currency::AWG), + "azn" => Ok(Currency::AZN), + "bam" => Ok(Currency::BAM), + "bbd" => Ok(Currency::BBD), + "bdt" => Ok(Currency::BDT), + "bgn" => Ok(Currency::BGN), + "bif" => Ok(Currency::BIF), + "bmd" => Ok(Currency::BMD), + "bnd" => Ok(Currency::BND), + "bob" => Ok(Currency::BOB), + "brl" => Ok(Currency::BRL), + "bsd" => Ok(Currency::BSD), + "bwp" => Ok(Currency::BWP), + "bzd" => Ok(Currency::BZD), + "cad" => Ok(Currency::CAD), + "cdf" => Ok(Currency::CDF), + "chf" => Ok(Currency::CHF), + "clp" => Ok(Currency::CLP), + "cny" => Ok(Currency::CNY), + "cop" => Ok(Currency::COP), + "crc" => Ok(Currency::CRC), + "cve" => Ok(Currency::CVE), + "czk" => Ok(Currency::CZK), + "djf" => Ok(Currency::DJF), + "dkk" => Ok(Currency::DKK), + "dop" => Ok(Currency::DOP), + "dzd" => Ok(Currency::DZD), + "eek" => Ok(Currency::EEK), + "egp" => Ok(Currency::EGP), + "etb" => Ok(Currency::ETB), + "eur" => Ok(Currency::EUR), + "fjd" => Ok(Currency::FJD), + "fkp" => Ok(Currency::FKP), + "gbp" => Ok(Currency::GBP), + "gel" => Ok(Currency::GEL), + "gip" => Ok(Currency::GIP), + "gmd" => Ok(Currency::GMD), + "gnf" => Ok(Currency::GNF), + "gtq" => Ok(Currency::GTQ), + "gyd" => Ok(Currency::GYD), + "hkd" => Ok(Currency::HKD), + "hnl" => Ok(Currency::HNL), + "hrk" => Ok(Currency::HRK), + "htg" => Ok(Currency::HTG), + "huf" => Ok(Currency::HUF), + "idr" => Ok(Currency::IDR), + "ils" => Ok(Currency::ILS), + "inr" => Ok(Currency::INR), + "isk" => Ok(Currency::ISK), + "jmd" => Ok(Currency::JMD), + "jpy" => Ok(Currency::JPY), + "kes" => Ok(Currency::KES), + "kgs" => Ok(Currency::KGS), + "khr" => Ok(Currency::KHR), + "kmf" => Ok(Currency::KMF), + "krw" => Ok(Currency::KRW), + "kyd" => Ok(Currency::KYD), + "kzt" => Ok(Currency::KZT), + "lak" => Ok(Currency::LAK), + "lbp" => Ok(Currency::LBP), + "lkr" => Ok(Currency::LKR), + "lrd" => Ok(Currency::LRD), + "lsl" => Ok(Currency::LSL), + "ltl" => Ok(Currency::LTL), + "lvl" => Ok(Currency::LVL), + "mad" => Ok(Currency::MAD), + "mdl" => Ok(Currency::MDL), + "mga" => Ok(Currency::MGA), + "mkd" => Ok(Currency::MKD), + "mnt" => Ok(Currency::MNT), + "mop" => Ok(Currency::MOP), + "mro" => Ok(Currency::MRO), + "mur" => Ok(Currency::MUR), + "mvr" => Ok(Currency::MVR), + "mwk" => Ok(Currency::MWK), + "mxn" => Ok(Currency::MXN), + "myr" => Ok(Currency::MYR), + "mzn" => Ok(Currency::MZN), + "nad" => Ok(Currency::NAD), + "ngn" => Ok(Currency::NGN), + "nio" => Ok(Currency::NIO), + "nok" => Ok(Currency::NOK), + "npr" => Ok(Currency::NPR), + "nzd" => Ok(Currency::NZD), + "pab" => Ok(Currency::PAB), + "pen" => Ok(Currency::PEN), + "pgk" => Ok(Currency::PGK), + "php" => Ok(Currency::PHP), + "pkr" => Ok(Currency::PKR), + "pln" => Ok(Currency::PLN), + "pyg" => Ok(Currency::PYG), + "qar" => Ok(Currency::QAR), + "ron" => Ok(Currency::RON), + "rsd" => Ok(Currency::RSD), + "rub" => Ok(Currency::RUB), + "rwf" => Ok(Currency::RWF), + "sar" => Ok(Currency::SAR), + "sbd" => Ok(Currency::SBD), + "scr" => Ok(Currency::SCR), + "sek" => Ok(Currency::SEK), + "sgd" => Ok(Currency::SGD), + "shp" => Ok(Currency::SHP), + "sll" => Ok(Currency::SLL), + "sos" => Ok(Currency::SOS), + "srd" => Ok(Currency::SRD), + "std" => Ok(Currency::STD), + "svc" => Ok(Currency::SVC), + "szl" => Ok(Currency::SZL), + "thb" => Ok(Currency::THB), + "tjs" => Ok(Currency::TJS), + "top" => Ok(Currency::TOP), + "try" => Ok(Currency::TRY), + "ttd" => Ok(Currency::TTD), + "twd" => Ok(Currency::TWD), + "tzs" => Ok(Currency::TZS), + "uah" => Ok(Currency::UAH), + "ugx" => Ok(Currency::UGX), + "usd" => Ok(Currency::USD), + "uyu" => Ok(Currency::UYU), + "uzs" => Ok(Currency::UZS), + "vef" => Ok(Currency::VEF), + "vnd" => Ok(Currency::VND), + "vuv" => Ok(Currency::VUV), + "wst" => Ok(Currency::WST), + "xaf" => Ok(Currency::XAF), + "xcd" => Ok(Currency::XCD), + "xof" => Ok(Currency::XOF), + "xpf" => Ok(Currency::XPF), + "yer" => Ok(Currency::YER), + "zar" => Ok(Currency::ZAR), + "zmw" => Ok(Currency::ZMW), + _ => Err(ParseCurrencyError(())), + } + } +} + +#[derive(Debug)] +pub struct ParseCurrencyError(/* private */ ()); + +impl std::fmt::Display for ParseCurrencyError { + fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + #[allow(deprecated)] + fmt.write_str(::std::error::Error::description(self)) + } +} + +impl std::error::Error for ParseCurrencyError { + fn description(&self) -> &str { + "unknown currency code" + } +} diff --git a/ft-stripe/src/resources/customer.rs b/ft-stripe/src/resources/customer.rs new file mode 100644 index 0000000..7c0c615 --- /dev/null +++ b/ft-stripe/src/resources/customer.rs @@ -0,0 +1,678 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ + AlipayAccountId, BankAccountId, CardId, CouponId, CustomerId, PaymentMethodId, PaymentSourceId, +}; +use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Address, Currency, CustomField, Discount, PaymentMethod, PaymentSource, PaymentSourceParams, + Scheduled, Shipping, ShippingParams, Subscription, TaxId, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Customer". +/// +/// For more details see [https://stripe.com/docs/api/customers/object](https://stripe.com/docs/api/customers/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Customer { + /// Unique identifier for the object. + pub id: CustomerId, + + /// The customer's address. + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + /// Current balance, if any, being stored on the customer. + /// + /// If negative, the customer has credit to apply to their next invoice. + /// If positive, the customer has an amount owed that will be added to their next invoice. + /// The balance does not refer to any unpaid invoices; it solely takes into account amounts that have yet to be successfully applied to any invoice. + /// This balance is only taken into account as invoices are finalized. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) the customer can be charged in for recurring billing purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// ID of the default payment source for the customer. + /// + /// If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) field instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// When the customer's latest invoice is billed by charging automatically, delinquent is true if the invoice's latest charge is failed. + /// + /// When the customer's latest invoice is billed by sending an invoice, delinquent is true if the invoice is not paid by its due date. + #[serde(skip_serializing_if = "Option::is_none")] + pub delinquent: Option, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// Describes the current discount active on the customer, if there is one. + #[serde(skip_serializing_if = "Option::is_none")] + pub discount: Option, + + /// The customer's email address. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// The prefix for the customer used to generate unique invoice numbers. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_prefix: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The customer's full name or business name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// The suffix of the customer's next invoice number, e.g., 0001. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_invoice_sequence: Option, + + /// The customer's phone number. + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + /// The customer's preferred locales (languages), ordered by preference. + #[serde(skip_serializing_if = "Option::is_none")] + pub preferred_locales: Option>, + + /// Mailing and shipping address for the customer. + /// + /// Appears on invoices emailed to this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// The customer's payment sources, if any. + #[serde(default)] + pub sources: List, + + /// The customer's current subscriptions, if any. + #[serde(default)] + pub subscriptions: List, + + /// Describes the customer's tax exemption status. + /// + /// One of `none`, `exempt`, or `reverse`. + /// When set to `reverse`, invoice and receipt PDFs include the text **"Reverse charge"**. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_exempt: Option, + + /// The customer's tax IDs. + #[serde(default)] + pub tax_ids: List, +} + +impl Customer { + /// Returns a list of your customers. + /// + /// The customers are returned sorted by creation date, with the most recent customers appearing first. + pub fn list(client: &Client, params: ListCustomers<'_>) -> Response> { + client.get_query("/customers", ¶ms) + } + + /// Creates a new customer object. + pub fn create(client: &Client, params: CreateCustomer<'_>) -> Response { + client.post_form("/customers", ¶ms) + } + + /// Retrieves the details of an existing customer. + /// + /// You need only supply the unique customer identifier that was returned upon customer creation. + pub fn retrieve(client: &Client, id: &CustomerId, expand: &[&str]) -> Response { + client.get_query(&format!("/customers/{}", id), &Expand { expand }) + } + + /// Updates the specified customer by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. + /// For example, if you pass the **source** parameter, that becomes the customer’s active source (e.g., a card) to be used for all charges in the future. + /// When you update a customer to a new valid card source by passing the **source** parameter: for each of the customer’s current subscriptions, if the subscription bills automatically and is in the `past_due` state, then the latest open invoice for the subscription with automatic collection enabled will be retried. + /// This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. + /// Changing the **default_source** for a customer will not trigger this behavior. This request accepts mostly the same arguments as the customer creation call. + pub fn update( + client: &Client, + id: &CustomerId, + params: UpdateCustomer<'_>, + ) -> Response { + client.post_form(&format!("/customers/{}", id), ¶ms) + } + + /// Permanently deletes a customer. + /// + /// It cannot be undone. + /// Also immediately cancels any active subscriptions on the customer. + pub fn delete(client: &Client, id: &CustomerId) -> Response> { + client.delete(&format!("/customers/{}", id)) + } +} + +impl Object for Customer { + type Id = CustomerId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "customer" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceSettingCustomerSetting { + /// Default custom fields to be displayed on invoices for this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_fields: Option>, + + /// ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option>, + + /// Default footer to be displayed on invoices for this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub footer: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceSettingCustomField { + /// The name of the custom field. + pub name: String, + + /// The value of the custom field. + pub value: String, +} + +/// The parameters for `Customer::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateCustomer<'a> { + /// The customer's address. + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + /// An integer amount in %s that represents the customer's current balance, which affect the customer's future invoices. + /// + /// A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// An arbitrary string that you can attach to a customer object. + /// + /// It is displayed alongside the customer in the dashboard. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Customer's email address. + /// + /// It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. + /// This may be up to *512 characters*. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The prefix for the customer used to generate unique invoice numbers. + /// + /// Must be 3–12 uppercase letters or numbers. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_prefix: Option<&'a str>, + + /// Default invoice settings for this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The customer's full name or business name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + + /// The sequence to be used on the customer's next invoice. + /// + /// Defaults to 1. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_invoice_sequence: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// The customer's phone number. + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option<&'a str>, + + /// Customer's preferred languages, ordered by preference. + #[serde(skip_serializing_if = "Option::is_none")] + pub preferred_locales: Option>, + + /// The customer's shipping information. + /// + /// Appears on invoices emailed to this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + + /// The customer's tax exemption. + /// + /// One of `none`, `exempt`, or `reverse`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_exempt: Option, + + /// The customer's tax IDs. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id_data: Option>, +} + +impl<'a> CreateCustomer<'a> { + pub fn new() -> Self { + CreateCustomer { + address: Default::default(), + balance: Default::default(), + coupon: Default::default(), + description: Default::default(), + email: Default::default(), + expand: Default::default(), + invoice_prefix: Default::default(), + invoice_settings: Default::default(), + metadata: Default::default(), + name: Default::default(), + next_invoice_sequence: Default::default(), + payment_method: Default::default(), + phone: Default::default(), + preferred_locales: Default::default(), + shipping: Default::default(), + source: Default::default(), + tax_exempt: Default::default(), + tax_id_data: Default::default(), + } + } +} + +/// The parameters for `Customer::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListCustomers<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A filter on the list based on the customer's `email` field. + /// + /// The value must be a string. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListCustomers<'a> { + pub fn new() -> Self { + ListCustomers { + created: Default::default(), + email: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Customer::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateCustomer<'a> { + /// The customer's address. + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + /// An integer amount in %s that represents the customer's current balance, which affect the customer's future invoices. + /// + /// A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// ID of Alipay account to make the customer's new default for invoice payments. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_alipay_account: Option, + + /// ID of bank account to make the customer's new default for invoice payments. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_bank_account: Option, + + /// ID of card to make the customer's new default for invoice payments. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_card: Option, + + /// If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. + /// + /// Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. + /// + /// If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option, + + /// An arbitrary string that you can attach to a customer object. + /// + /// It is displayed alongside the customer in the dashboard. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Customer's email address. + /// + /// It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. + /// This may be up to *512 characters*. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The prefix for the customer used to generate unique invoice numbers. + /// + /// Must be 3–12 uppercase letters or numbers. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_prefix: Option<&'a str>, + + /// Default invoice settings for this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The customer's full name or business name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + + /// The sequence to be used on the customer's next invoice. + /// + /// Defaults to 1. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_invoice_sequence: Option, + + /// The customer's phone number. + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option<&'a str>, + + /// Customer's preferred languages, ordered by preference. + #[serde(skip_serializing_if = "Option::is_none")] + pub preferred_locales: Option>, + + /// The customer's shipping information. + /// + /// Appears on invoices emailed to this customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + + /// The customer's tax exemption. + /// + /// One of `none`, `exempt`, or `reverse`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_exempt: Option, + + /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. + /// + /// This will always overwrite any trials that might apply via a subscribed plan. + /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. + /// The special value `now` can be provided to end the customer's trial immediately. + /// Can be at most two years from `billing_cycle_anchor`. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, +} + +impl<'a> UpdateCustomer<'a> { + pub fn new() -> Self { + UpdateCustomer { + address: Default::default(), + balance: Default::default(), + coupon: Default::default(), + default_alipay_account: Default::default(), + default_bank_account: Default::default(), + default_card: Default::default(), + default_source: Default::default(), + description: Default::default(), + email: Default::default(), + expand: Default::default(), + invoice_prefix: Default::default(), + invoice_settings: Default::default(), + metadata: Default::default(), + name: Default::default(), + next_invoice_sequence: Default::default(), + phone: Default::default(), + preferred_locales: Default::default(), + shipping: Default::default(), + source: Default::default(), + tax_exempt: Default::default(), + trial_end: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CustomerInvoiceSettings { + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_fields: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub footer: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxIdData { + #[serde(rename = "type")] + pub type_: TaxIdType, + + pub value: String, +} + +/// An enum representing the possible values of an `Customer`'s `tax_exempt` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CustomerTaxExempt { + Exempt, + None, + Reverse, +} + +impl CustomerTaxExempt { + pub fn as_str(self) -> &'static str { + match self { + CustomerTaxExempt::Exempt => "exempt", + CustomerTaxExempt::None => "none", + CustomerTaxExempt::Reverse => "reverse", + } + } +} + +impl AsRef for CustomerTaxExempt { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CustomerTaxExempt { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateCustomer`'s `tax_exempt` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CustomerTaxExemptFilter { + Exempt, + None, + Reverse, +} + +impl CustomerTaxExemptFilter { + pub fn as_str(self) -> &'static str { + match self { + CustomerTaxExemptFilter::Exempt => "exempt", + CustomerTaxExemptFilter::None => "none", + CustomerTaxExemptFilter::Reverse => "reverse", + } + } +} + +impl AsRef for CustomerTaxExemptFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CustomerTaxExemptFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `TaxIdData`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TaxIdType { + AuAbn, + BrCnpj, + BrCpf, + CaBn, + CaQst, + ChVat, + EsCif, + EuVat, + HkBr, + InGst, + JpCn, + KrBrn, + LiUid, + MxRfc, + MyItn, + MySst, + NoVat, + NzGst, + RuInn, + SgGst, + SgUen, + ThVat, + TwVat, + UsEin, + ZaVat, +} + +impl TaxIdType { + pub fn as_str(self) -> &'static str { + match self { + TaxIdType::AuAbn => "au_abn", + TaxIdType::BrCnpj => "br_cnpj", + TaxIdType::BrCpf => "br_cpf", + TaxIdType::CaBn => "ca_bn", + TaxIdType::CaQst => "ca_qst", + TaxIdType::ChVat => "ch_vat", + TaxIdType::EsCif => "es_cif", + TaxIdType::EuVat => "eu_vat", + TaxIdType::HkBr => "hk_br", + TaxIdType::InGst => "in_gst", + TaxIdType::JpCn => "jp_cn", + TaxIdType::KrBrn => "kr_brn", + TaxIdType::LiUid => "li_uid", + TaxIdType::MxRfc => "mx_rfc", + TaxIdType::MyItn => "my_itn", + TaxIdType::MySst => "my_sst", + TaxIdType::NoVat => "no_vat", + TaxIdType::NzGst => "nz_gst", + TaxIdType::RuInn => "ru_inn", + TaxIdType::SgGst => "sg_gst", + TaxIdType::SgUen => "sg_uen", + TaxIdType::ThVat => "th_vat", + TaxIdType::TwVat => "tw_vat", + TaxIdType::UsEin => "us_ein", + TaxIdType::ZaVat => "za_vat", + } + } +} + +impl AsRef for TaxIdType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TaxIdType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/customer_ext.rs b/ft-stripe/src/resources/customer_ext.rs new file mode 100644 index 0000000..27f98ed --- /dev/null +++ b/ft-stripe/src/resources/customer_ext.rs @@ -0,0 +1,83 @@ +use crate::config::{Client, Response}; +use crate::ids::{BankAccountId, CardId, CustomerId, PaymentSourceId}; +use crate::params::Deleted; +use crate::resources::{BankAccount, Customer, PaymentSource, PaymentSourceParams, Source}; +use serde::{Deserialize, Serialize}; + +impl Customer { + /// Attaches a source to a customer, does not change default Source for the Customer + /// + /// For more details see [https://stripe.com/docs/api#attach_source](https://stripe.com/docs/api#attach_source). + pub fn attach_source( + client: &Client, + customer_id: &CustomerId, + source: PaymentSourceParams, + ) -> Response { + #[derive(Serialize)] + struct AttachSource { + source: PaymentSourceParams, + } + let params = AttachSource { source }; + client.post_form(&format!("/customers/{}/sources", customer_id), params) + } + + /// Detaches a source from a customer + /// + /// For more details see [https://stripe.com/docs/api#detach_source](https://stripe.com/docs/api#detach_source). + pub fn detach_source( + client: &Client, + customer_id: &CustomerId, + source_id: &PaymentSourceId, + ) -> Response { + client.delete(&format!("/customers/{}/sources/{}", customer_id, source_id)) + } + + /// Retrieves a Card, BankAccount, or Source for a Customer + pub fn retrieve_source( + client: &Client, + customer_id: &CustomerId, + source_id: &PaymentSourceId, + ) -> Response { + client.get(&format!("/customers/{}/sources/{}", customer_id, source_id)) + } + + /// Verifies a Bank Account for a Customer. + /// + /// For more details see https://stripe.com/docs/api/customer_bank_accounts/verify. + pub fn verify_bank_account( + client: &Client, + customer_id: &CustomerId, + bank_account_id: &BankAccountId, + params: VerifyBankAccount<'_>, + ) -> Response { + client.post_form( + &format!("/customers/{}/sources/{}/verify", customer_id, bank_account_id), + params, + ) + } +} + +/// The set of parameters that can be used when verifying a Bank Account. +/// +/// For more details see https://stripe.com/docs/api/customer_bank_accounts/verify?lang=curl. +#[derive(Clone, Debug, Default, Serialize)] +pub struct VerifyBankAccount<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub amounts: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub verification_method: Option<&'a str>, +} + +impl VerifyBankAccount<'_> { + pub fn new() -> Self { + VerifyBankAccount { amounts: None, verification_method: None } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum DetachedSource { + BankAccount(Deleted), + Card(Deleted), + Source(Source), +} diff --git a/ft-stripe/src/resources/discount.rs b/ft-stripe/src/resources/discount.rs new file mode 100644 index 0000000..d9e0f2a --- /dev/null +++ b/ft-stripe/src/resources/discount.rs @@ -0,0 +1,46 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::{Expandable, Object, Timestamp}; +use crate::resources::{Coupon, Customer}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Discount". +/// +/// For more details see [https://stripe.com/docs/api/discounts/object](https://stripe.com/docs/api/discounts/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Discount { + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// The ID of the customer associated with this discount. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// If the coupon has a duration of `repeating`, the date that this discount will end. + /// + /// If the coupon has a duration of `once` or `forever`, this attribute will be null. + #[serde(skip_serializing_if = "Option::is_none")] + pub end: Option, + + /// Date that the coupon was applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub start: Option, + + /// The subscription that this coupon is applied to, if it is applied to a particular subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, +} + +impl Object for Discount { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "discount" + } +} diff --git a/ft-stripe/src/resources/dispute.rs b/ft-stripe/src/resources/dispute.rs new file mode 100644 index 0000000..8b79a11 --- /dev/null +++ b/ft-stripe/src/resources/dispute.rs @@ -0,0 +1,338 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ChargeId, DisputeId, PaymentIntentId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{BalanceTransaction, Charge, Currency, File, PaymentIntent}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Dispute". +/// +/// For more details see [https://stripe.com/docs/api/disputes/object](https://stripe.com/docs/api/disputes/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Dispute { + /// Unique identifier for the object. + pub id: DisputeId, + + /// Disputed amount. + /// + /// Usually the amount of the charge, but can differ (usually because of currency fluctuation or because only part of the order is disputed). + pub amount: i64, + + /// List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your Stripe account as a result of this dispute. + pub balance_transactions: Vec, + + /// ID of the charge that was disputed. + pub charge: Expandable, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + pub evidence: DisputeEvidence, + + pub evidence_details: DisputeEvidenceDetails, + + /// If true, it is still possible to refund the disputed payment. + /// + /// Once the payment has been fully refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute. + pub is_charge_refundable: bool, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// ID of the PaymentIntent that was disputed. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// Reason given by cardholder for dispute. + /// + /// Possible values are `bank_cannot_process`, `check_returned`, `credit_not_processed`, `customer_initiated`, `debit_not_authorized`, `duplicate`, `fraudulent`, `general`, `incorrect_account_details`, `insufficient_funds`, `product_not_received`, `product_unacceptable`, `subscription_canceled`, or `unrecognized`. + /// Read more about [dispute reasons](https://stripe.com/docs/disputes/categories). + pub reason: String, + + /// Current status of dispute. + /// + /// Possible values are `warning_needs_response`, `warning_under_review`, `warning_closed`, `needs_response`, `under_review`, `charge_refunded`, `won`, or `lost`. + pub status: DisputeStatus, +} + +impl Dispute { + /// Returns a list of your disputes. + pub fn list(client: &Client, params: ListDisputes<'_>) -> Response> { + client.get_query("/disputes", ¶ms) + } + + /// Retrieves the dispute with the given ID. + pub fn retrieve(client: &Client, id: &DisputeId, expand: &[&str]) -> Response { + client.get_query(&format!("/disputes/{}", id), &Expand { expand }) + } +} + +impl Object for Dispute { + type Id = DisputeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "dispute" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DisputeEvidence { + /// Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. + /// + /// This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. + #[serde(skip_serializing_if = "Option::is_none")] + pub access_activity_log: Option, + + /// The billing address provided by the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_address: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_policy: Option>, + + /// An explanation of how and when the customer was shown your refund policy prior to purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_policy_disclosure: Option, + + /// A justification for why the customer's subscription was not canceled. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_rebuttal: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. + /// + /// Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_communication: Option>, + + /// The email address of the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_email_address: Option, + + /// The name of the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_name: Option, + + /// The IP address that the customer used when making the purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_purchase_ip: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_signature: Option>, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. + /// + /// This document should be paired with a similar document from the disputed payment that proves the two payments are separate. + #[serde(skip_serializing_if = "Option::is_none")] + pub duplicate_charge_documentation: Option>, + + /// An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. + #[serde(skip_serializing_if = "Option::is_none")] + pub duplicate_charge_explanation: Option, + + /// The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub duplicate_charge_id: Option, + + /// A description of the product or service that was sold. + #[serde(skip_serializing_if = "Option::is_none")] + pub product_description: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option>, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_policy: Option>, + + /// Documentation demonstrating that the customer was shown your refund policy prior to purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_policy_disclosure: Option, + + /// A justification for why the customer is not entitled to a refund. + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_refusal_explanation: Option, + + /// The date on which the customer received or began receiving the purchased service, in a clear human-readable format. + #[serde(skip_serializing_if = "Option::is_none")] + pub service_date: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. + /// + /// This could include a copy of a signed contract, work order, or other form of written agreement. + #[serde(skip_serializing_if = "Option::is_none")] + pub service_documentation: Option>, + + /// The address to which a physical product was shipped. + /// + /// You should try to include as complete address information as possible. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_address: Option, + + /// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. + /// + /// If multiple carriers were used for this purchase, please separate them with commas. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_carrier: Option, + + /// The date on which a physical product began its route to the shipping address, in a clear human-readable format. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_date: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. + /// + /// This could include a copy of the shipment receipt, shipping label, etc. + /// It should show the customer's full shipping address, if possible. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_documentation: Option>, + + /// The tracking number for a physical product, obtained from the delivery service. + /// + /// If multiple tracking numbers were generated for this purchase, please separate them with commas. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_tracking_number: Option, + + /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. + #[serde(skip_serializing_if = "Option::is_none")] + pub uncategorized_file: Option>, + + /// Any additional evidence or statements. + #[serde(skip_serializing_if = "Option::is_none")] + pub uncategorized_text: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DisputeEvidenceDetails { + /// Date by which evidence must be submitted in order to successfully challenge dispute. + /// + /// Will be null if the customer's bank or credit card company doesn't allow a response for this particular dispute. + #[serde(skip_serializing_if = "Option::is_none")] + pub due_by: Option, + + /// Whether evidence has been staged for this dispute. + pub has_evidence: bool, + + /// Whether the last evidence submission was submitted past the due date. + /// + /// Defaults to `false` if no evidence submissions have occurred. + /// If `true`, then delivery of the latest evidence is *not* guaranteed. + pub past_due: bool, + + /// The number of times evidence has been submitted. + /// + /// Typically, you may only submit evidence once. + pub submission_count: u64, +} + +/// The parameters for `Dispute::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListDisputes<'a> { + /// Only return disputes associated to the charge specified by this charge ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return disputes associated to the PaymentIntent specified by this PaymentIntent ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListDisputes<'a> { + pub fn new() -> Self { + ListDisputes { + charge: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + payment_intent: Default::default(), + starting_after: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Dispute`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum DisputeStatus { + ChargeRefunded, + Lost, + NeedsResponse, + UnderReview, + WarningClosed, + WarningNeedsResponse, + WarningUnderReview, + Won, +} + +impl DisputeStatus { + pub fn as_str(self) -> &'static str { + match self { + DisputeStatus::ChargeRefunded => "charge_refunded", + DisputeStatus::Lost => "lost", + DisputeStatus::NeedsResponse => "needs_response", + DisputeStatus::UnderReview => "under_review", + DisputeStatus::WarningClosed => "warning_closed", + DisputeStatus::WarningNeedsResponse => "warning_needs_response", + DisputeStatus::WarningUnderReview => "warning_under_review", + DisputeStatus::Won => "won", + } + } +} + +impl AsRef for DisputeStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for DisputeStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/event.rs b/ft-stripe/src/resources/event.rs new file mode 100644 index 0000000..8ca0f1a --- /dev/null +++ b/ft-stripe/src/resources/event.rs @@ -0,0 +1,403 @@ +use crate::error::WebhookError; +use crate::ids::{AccountId, EventId}; +use crate::resources::*; + +use chrono::Utc; +#[cfg(feature = "webhook-events")] +use hmac::{Hmac, Mac}; +use serde::{Deserialize, Serialize}; +#[cfg(feature = "webhook-events")] +use sha2::Sha256; + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] +pub enum EventType { + #[serde(rename = "account.updated")] + AccountUpdated, + #[serde(rename = "account.application.deauthorized")] + AccountApplicationDeauthorized, + #[serde(rename = "account.external_account.created")] + AccountExternalAccountCreated, + #[serde(rename = "account.external_account.deleted")] + AccountExternalAccountDeleted, + #[serde(rename = "account.external_account.updated")] + AccountExternalAccountUpdated, + #[serde(rename = "application_fee.created")] + ApplicationFeeCreated, + #[serde(rename = "application_fee.refunded")] + ApplicationFeeRefunded, + #[serde(rename = "application_fee.refund.updated")] + ApplicationFeeRefundUpdated, + #[serde(rename = "balance.available")] + BalanceAvailable, + #[serde(rename = "charge.captured")] + ChargeCaptured, + #[serde(rename = "charge.failed")] + ChargeFailed, + #[serde(rename = "charge.pending")] + ChargePending, + #[serde(rename = "charge.refunded")] + ChargeRefunded, + #[serde(rename = "charge.succeeded")] + ChargeSucceeded, + #[serde(rename = "charge.updated")] + ChargeUpdated, + #[serde(rename = "charge.dispute.closed")] + ChargeDisputeClosed, + #[serde(rename = "charge.dispute.created")] + ChargeDisputeCreated, + #[serde(rename = "charge.dispute.funds_reinstated")] + ChargeDisputeFundsReinstated, + #[serde(rename = "charge.dispute.funds_withdrawn")] + ChargeDisputeFundsWithdrawn, + #[serde(rename = "charge.dispute.updated")] + ChargeDisputeUpdated, + #[serde(rename = "charge.refund.updated")] + ChargeRefundUpdated, + #[serde(rename = "checkout.session.completed")] + CheckoutSessionCompleted, + #[serde(rename = "coupon.created")] + CouponCreated, + #[serde(rename = "coupon.deleted")] + CouponDeleted, + #[serde(rename = "coupon.updated")] + CouponUpdated, + #[serde(rename = "customer.created")] + CustomerCreated, + #[serde(rename = "customer.deleted")] + CustomerDeleted, + #[serde(rename = "customer.updated")] + CustomerUpdated, + #[serde(rename = "customer.discount.created")] + CustomerDiscountCreated, + #[serde(rename = "customer.discount.deleted")] + CustomerDiscountDeleted, + #[serde(rename = "customer.discount.updated")] + CustomerDiscountUpdated, + #[serde(rename = "customer.source.created")] + CustomerSourceCreated, + #[serde(rename = "customer.source.deleted")] + CustomerSourceDeleted, + #[serde(rename = "customer.source.expiring")] + CustomerSourceExpiring, + #[serde(rename = "customer.source.updated")] + CustomerSourceUpdated, + #[serde(rename = "customer.subscription.created")] + CustomerSubscriptionCreated, + #[serde(rename = "customer.subscription.deleted")] + CustomerSubscriptionDeleted, + #[serde(rename = "customer.subscription.trial_will_end")] + CustomerSubscriptionTrialWillEnd, + #[serde(rename = "customer.subscription.updated")] + CustomerSubscriptionUpdated, + #[serde(rename = "file.created")] + FileCreated, + #[serde(rename = "invoice.created")] + InvoiceCreated, + #[serde(rename = "invoice.deleted")] + InvoiceDeleted, + #[serde(rename = "invoice.finalized")] + InvoiceFinalized, + #[serde(rename = "invoice.marked_uncollectible")] + InvoiceMarkedUncollectible, + #[serde(rename = "invoice.payment_action_required")] + InvoicePaymentActionRequired, + #[serde(rename = "invoice.payment_failed")] + InvoicePaymentFailed, + #[serde(rename = "invoice.payment_succeeded")] + InvoicePaymentSucceeded, + #[serde(rename = "invoice.sent")] + InvoiceSent, + #[serde(rename = "invoice.updated")] + InvoiceUpdated, + #[serde(rename = "invoice.upcoming")] + InvoiceUpcoming, + #[serde(rename = "invoice.voided")] + InvoiceVoided, + #[serde(rename = "invoiceitem.created")] + InvoiceItemCreated, + #[serde(rename = "invoiceitem.deleted")] + InvoiceItemDeleted, + #[serde(rename = "invoiceitem.updated")] + InvoiceItemUpdated, + #[serde(rename = "order.created")] + OrderCreated, + #[serde(rename = "order.payment_failed")] + OrderPaymentFailed, + #[serde(rename = "order.payment_succeeded")] + OrderPaymentSucceeded, + #[serde(rename = "order.updated")] + OrderUpdated, + #[serde(rename = "order_return.updated")] + OrderReturnUpdated, + #[serde(rename = "payment_intent.amount_capturable_updated")] + PaymentIntentAmountCapturableUpdated, + #[serde(rename = "payment_intent.created")] + PaymentIntentCreated, + #[serde(rename = "payment_intent.payment_failed")] + PaymentIntentPaymentFailed, + #[serde(rename = "payment_intent.requires_capture")] + PaymentIntentRequiresCapture, + #[serde(rename = "payment_intent.succeeded")] + PaymentIntentSucceeded, + #[serde(rename = "payment_method.automatically_updated")] + PaymentMethodAutomaticallyUpdated, + #[serde(rename = "payment_method.attached")] + PaymentMethodAttached, + #[serde(rename = "payment_method.detached")] + PaymentMethodDetached, + #[serde(rename = "payout.canceled")] + PayoutCanceled, + #[serde(rename = "payout.created")] + PayoutCreated, + #[serde(rename = "payout.failed")] + PayoutFailed, + #[serde(rename = "payout.paid")] + PayoutPaid, + #[serde(rename = "payout.updated")] + PayoutUpdated, + #[serde(rename = "plan.created")] + PlanCreated, + #[serde(rename = "plan.deleted")] + PlanDeleted, + #[serde(rename = "plan.updated")] + PlanUpdated, + #[serde(rename = "product.created")] + ProductCreated, + #[serde(rename = "product.deleted")] + ProductDeleted, + #[serde(rename = "product.updated")] + ProductUpdated, + #[serde(rename = "review.closed")] + ReviewClosed, + #[serde(rename = "review.opened")] + ReviewOpened, + #[serde(rename = "sigma.scheduled_query_run.created")] + SigmaScheduledQueryRunCreated, + #[serde(rename = "sku.created")] + SkuCreated, + #[serde(rename = "sku.deleted")] + SkuDeleted, + #[serde(rename = "sku.updated")] + SkuUpdated, + #[serde(rename = "source.canceled")] + SourceCanceled, + #[serde(rename = "source.chargeable")] + Sourcechargeable, + #[serde(rename = "source.failed")] + SourceFailed, + #[serde(rename = "source.transaction.created")] + SourceTransactionCreated, + #[serde(rename = "transfer.created")] + TransferCreated, + #[serde(rename = "transfer.reversed")] + TransferReversed, + #[serde(rename = "transfer.updated")] + TransferUpdated, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Event { + pub id: EventId, + #[serde(rename = "type")] + pub event_type: EventType, + pub data: EventData, + pub created: i64, + pub livemode: bool, + pub account: Option, + // ... +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct EventData { + pub object: EventObject, + // previous_attributes: ... +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum EventObject { + Account(Account), + ApplicationFee(ApplicationFee), + #[serde(rename = "fee_refund")] + ApplicationFeeRefund(ApplicationFeeRefund), + Balance(Balance), + BankAccount(BankAccount), + Card(Card), + Charge(Charge), + Customer(Customer), + Dispute(Dispute), + #[serde(rename = "checkout.session")] + CheckoutSession(CheckoutSession), + File(File), + Invoice(Invoice), + #[serde(rename = "invoiceitem")] + InvoiceItem(InvoiceItem), + Order(Order), + OrderReturn(OrderReturn), + PaymentIntent(PaymentIntent), + PaymentMethod(PaymentMethod), + Payout(Payout), + Plan(Plan), + Product(Product), + Refund(Refund), + Review(Review), + Sku(Sku), + Subscription(Subscription), + Transfer(Transfer), +} + +#[cfg(feature = "webhook-events")] +pub struct Webhook { + current_timestamp: i64, +} + +#[cfg(feature = "webhook-events")] +impl Webhook { + pub fn construct_event(payload: &str, sig: &str, secret: &str) -> Result { + Self { current_timestamp: Utc::now().timestamp() }.do_construct_event(payload, sig, secret) + } + + fn do_construct_event( + self, + payload: &str, + sig: &str, + secret: &str, + ) -> Result { + // Get Stripe signature from header + let signature = Signature::parse(&sig)?; + let signed_payload = format!("{}{}{}", signature.t, ".", payload); + + // Compute HMAC with the SHA256 hash function, using endpoing secret as key + // and signed_payload string as the message. + let mut mac = + Hmac::::new_from_slice(secret.as_bytes()).map_err(|_| WebhookError::BadKey)?; + mac.update(signed_payload.as_bytes()); + let sig = hex::decode(signature.v1).map_err(|_| WebhookError::BadSignature)?; + mac.verify_slice(sig.as_slice()).map_err(|_| WebhookError::BadSignature)?; + + // Get current timestamp to compare to signature timestamp + if (self.current_timestamp - signature.t).abs() > 300 { + return Err(WebhookError::BadTimestamp(signature.t)); + } + + serde_json::from_str(&payload).map_err(WebhookError::BadParse) + } +} + +#[cfg(feature = "webhook-events")] +#[derive(Debug)] +struct Signature<'r> { + t: i64, + v1: &'r str, + v0: Option<&'r str>, +} + +#[cfg(feature = "webhook-events")] +impl<'r> Signature<'r> { + fn parse(raw: &'r str) -> Result, WebhookError> { + use std::collections::HashMap; + let headers: HashMap<&str, &str> = raw + .split(',') + .map(|header| { + let mut key_and_value = header.split('='); + let key = key_and_value.next(); + let value = key_and_value.next(); + (key, value) + }) + .filter_map(|(key, value)| match (key, value) { + (Some(key), Some(value)) => Some((key, value)), + _ => None, + }) + .collect(); + let t = headers.get("t").ok_or(WebhookError::BadSignature)?; + let v1 = headers.get("v1").ok_or(WebhookError::BadSignature)?; + let v0 = headers.get("v0").map(|r| *r); + Ok(Signature { t: t.parse::().map_err(WebhookError::BadHeader)?, v1, v0 }) + } +} + +#[cfg(test)] +mod tests { + #[cfg(feature = "webhook-events")] + #[test] + fn test_signature_parse() { + use super::Signature; + + let raw_signature = + "t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd"; + let signature = Signature::parse(raw_signature).unwrap(); + assert_eq!(signature.t, 1492774577); + assert_eq!( + signature.v1, + "5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" + ); + assert_eq!(signature.v0, None); + + let raw_signature_with_test_mode = "t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39"; + let signature = Signature::parse(raw_signature_with_test_mode).unwrap(); + assert_eq!(signature.t, 1492774577); + assert_eq!( + signature.v1, + "5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" + ); + assert_eq!( + signature.v0, + Some("6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39") + ); + } + + #[cfg(feature = "webhook-events")] + #[test] + fn test_webhook_construct_event() { + let payload = r#"{ + "id": "evt_123", + "object": "event", + "account": "acct_123", + "api_version": "2017-05-25", + "created": 1533204620, + "data": { + "object": { + "id": "ii_123", + "object": "invoiceitem", + "amount": 1000, + "currency": "usd", + "customer": "cus_123", + "date": 1533204620, + "description": "Test Invoice Item", + "discountable": false, + "invoice": "in_123", + "livemode": false, + "metadata": {}, + "period": { + "start": 1533204620, + "end": 1533204620 + }, + "plan": null, + "proration": false, + "quantity": null, + "subscription": null + } + }, + "livemode": false, + "pending_webhooks": 1, + "request": { + "id": "req_123", + "idempotency_key": "idempotency-key-123" + }, + "type": "invoiceitem.created" +} +"#; + let event_timestamp = 1533204620; + let secret = "webhook_secret".to_string(); + let signature = format!("t={},v1=f0bdba6d4eacbd8ad8a3bbadd7248e633ec1477f7899c124c51b39405fa36613,v0=63f3a72374a733066c4be69ed7f8e5ac85c22c9f0a6a612ab9a025a9e4ee7eef", event_timestamp); + + let webhook = super::Webhook { current_timestamp: event_timestamp }; + + let event = webhook + .do_construct_event(payload, &signature, &secret) + .expect("Failed to construct event"); + + assert_eq!(event.event_type, super::EventType::InvoiceItemCreated); + assert_eq!(event.id.to_string(), "evt_123"); + } +} diff --git a/ft-stripe/src/resources/fee_refund.rs b/ft-stripe/src/resources/fee_refund.rs new file mode 100644 index 0000000..95588ca --- /dev/null +++ b/ft-stripe/src/resources/fee_refund.rs @@ -0,0 +1,52 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::ApplicationFeeRefundId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{ApplicationFee, BalanceTransaction, Currency}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "FeeRefund". +/// +/// For more details see [https://stripe.com/docs/api/fee_refunds/object](https://stripe.com/docs/api/fee_refunds/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ApplicationFeeRefund { + /// Unique identifier for the object. + pub id: ApplicationFeeRefundId, + + /// Amount, in %s. + pub amount: i64, + + /// Balance transaction that describes the impact on your account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// ID of the application fee that was refunded. + pub fee: Expandable, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, +} + +impl Object for ApplicationFeeRefund { + type Id = ApplicationFeeRefundId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "fee_refund" + } +} diff --git a/ft-stripe/src/resources/file.rs b/ft-stripe/src/resources/file.rs new file mode 100644 index 0000000..5557865 --- /dev/null +++ b/ft-stripe/src/resources/file.rs @@ -0,0 +1,174 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::FileId; +use crate::params::{Expand, List, Object, RangeQuery, Timestamp}; +use crate::resources::FileLink; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "File". +/// +/// For more details see [https://stripe.com/docs/api/files/object](https://stripe.com/docs/api/files/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct File { + /// Unique identifier for the object. + pub id: FileId, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// A filename for the file, suitable for saving to a filesystem. + #[serde(skip_serializing_if = "Option::is_none")] + pub filename: Option, + + /// A list of [file links](https://stripe.com/docs/api#file_links) that point at this file. + #[serde(default)] + pub links: List, + + /// The purpose of the file. + /// + /// Possible values are `additional_verification`, `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `identity_document`, `pci_document`, `sigma_scheduled_query`, or `tax_document_user_upload`. + pub purpose: FilePurpose, + + /// The size in bytes of the file object. + pub size: u64, + + /// A user friendly title for the document. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + + /// The type of the file returned (e.g., `csv`, `pdf`, `jpg`, or `png`). + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// The URL from which the file can be downloaded using your live secret API key. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl File { + /// Returns a list of the files that your account has access to. + /// + /// The files are returned sorted by creation date, with the most recently created files appearing first. + pub fn list(client: &Client, params: ListFiles<'_>) -> Response> { + client.get_query("/files", ¶ms) + } + + /// Retrieves the details of an existing file object. + /// + /// Supply the unique file ID from a file, and Stripe will return the corresponding file object. + /// To access file contents, see the [File Upload Guide](https://stripe.com/docs/file-upload#download-file-contents). + pub fn retrieve(client: &Client, id: &FileId, expand: &[&str]) -> Response { + client.get_query(&format!("/files/{}", id), &Expand { expand }) + } +} + +impl Object for File { + type Id = FileId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "file" + } +} + +/// The parameters for `File::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListFiles<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// The file purpose to filter queries by. + /// + /// If none is provided, files will not be filtered by purpose. + #[serde(skip_serializing_if = "Option::is_none")] + pub purpose: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListFiles<'a> { + pub fn new() -> Self { + ListFiles { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + purpose: Default::default(), + starting_after: Default::default(), + } + } +} + +/// An enum representing the possible values of an `ListFiles`'s `purpose` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum FilePurpose { + AdditionalVerification, + BusinessIcon, + BusinessLogo, + CustomerSignature, + DisputeEvidence, + FinanceReportRun, + IdentityDocument, + PciDocument, + SigmaScheduledQuery, + TaxDocumentUserUpload, +} + +impl FilePurpose { + pub fn as_str(self) -> &'static str { + match self { + FilePurpose::AdditionalVerification => "additional_verification", + FilePurpose::BusinessIcon => "business_icon", + FilePurpose::BusinessLogo => "business_logo", + FilePurpose::CustomerSignature => "customer_signature", + FilePurpose::DisputeEvidence => "dispute_evidence", + FilePurpose::FinanceReportRun => "finance_report_run", + FilePurpose::IdentityDocument => "identity_document", + FilePurpose::PciDocument => "pci_document", + FilePurpose::SigmaScheduledQuery => "sigma_scheduled_query", + FilePurpose::TaxDocumentUserUpload => "tax_document_user_upload", + } + } +} + +impl AsRef for FilePurpose { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for FilePurpose { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/file_link.rs b/ft-stripe/src/resources/file_link.rs new file mode 100644 index 0000000..b931ba1 --- /dev/null +++ b/ft-stripe/src/resources/file_link.rs @@ -0,0 +1,204 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{FileId, FileLinkId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{File, Scheduled}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "FileLink". +/// +/// For more details see [https://stripe.com/docs/api/file_links/object](https://stripe.com/docs/api/file_links/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct FileLink { + /// Unique identifier for the object. + pub id: FileLinkId, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Whether this link is already expired. + pub expired: bool, + + /// Time at which the link expires. + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at: Option, + + /// The file object this link points to. + pub file: Expandable, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The publicly accessible URL to download the file. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl FileLink { + /// Returns a list of file links. + pub fn list(client: &Client, params: ListFileLinks<'_>) -> Response> { + client.get_query("/file_links", ¶ms) + } + + /// Creates a new file link object. + pub fn create(client: &Client, params: CreateFileLink<'_>) -> Response { + client.post_form("/file_links", ¶ms) + } + + /// Retrieves the file link with the given ID. + pub fn retrieve(client: &Client, id: &FileLinkId, expand: &[&str]) -> Response { + client.get_query(&format!("/file_links/{}", id), &Expand { expand }) + } + + /// Updates an existing file link object. + /// + /// Expired links can no longer be updated. + pub fn update( + client: &Client, + id: &FileLinkId, + params: UpdateFileLink<'_>, + ) -> Response { + client.post_form(&format!("/file_links/{}", id), ¶ms) + } +} + +impl Object for FileLink { + type Id = FileLinkId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "file_link" + } +} + +/// The parameters for `FileLink::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateFileLink<'a> { + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A future timestamp after which the link will no longer be usable. + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at: Option, + + /// The ID of the file. + /// + /// The file's `purpose` must be one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `pci_document`, `sigma_scheduled_query`, or `tax_document_user_upload`. + pub file: FileId, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> CreateFileLink<'a> { + pub fn new(file: FileId) -> Self { + CreateFileLink { + expand: Default::default(), + expires_at: Default::default(), + file, + metadata: Default::default(), + } + } +} + +/// The parameters for `FileLink::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListFileLinks<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Filter links by their expiration status. + /// + /// By default, all links are returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub expired: Option, + + /// Only return links for the given file. + #[serde(skip_serializing_if = "Option::is_none")] + pub file: Option, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListFileLinks<'a> { + pub fn new() -> Self { + ListFileLinks { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + expired: Default::default(), + file: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `FileLink::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateFileLink<'a> { + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdateFileLink<'a> { + pub fn new() -> Self { + UpdateFileLink { + expand: Default::default(), + expires_at: Default::default(), + metadata: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/invoice.rs b/ft-stripe/src/resources/invoice.rs new file mode 100644 index 0000000..56196ce --- /dev/null +++ b/ft-stripe/src/resources/invoice.rs @@ -0,0 +1,902 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, InvoiceId, SubscriptionId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Address, Charge, Currency, CustomField, Customer, Discount, InvoiceLineItem, PaymentIntent, + PaymentMethod, PaymentSource, Shipping, Subscription, TaxRate, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Invoice". +/// +/// For more details see [https://stripe.com/docs/api/invoices/object](https://stripe.com/docs/api/invoices/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Invoice { + /// Unique identifier for the object. + #[serde(default = "InvoiceId::none")] + pub id: InvoiceId, + + /// The country of the business associated with this invoice, most often the business creating the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_country: Option, + + /// The public name of the business associated with this invoice, most often the business creating the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub account_name: Option, + + /// Final amount due at this time for this invoice. + /// + /// If the invoice's total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the `amount_due` may be 0. + /// If there is a positive `starting_balance` for the invoice (the customer owes money), the `amount_due` will also take that into account. + /// The charge that gets generated for the invoice will be for the amount specified in `amount_due`. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_due: Option, + + /// The amount, in %s, that was paid. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_paid: Option, + + /// The amount remaining, in %s, that is due. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_remaining: Option, + + /// The fee in %s that will be applied to the invoice and transferred to the application owner's Stripe account when the invoice is paid. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + + /// Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. + /// + /// Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. + /// In other words, manual payment attempts after the first attempt do not affect the retry schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub attempt_count: Option, + + /// Whether an attempt has been made to pay the invoice. + /// + /// An invoice is not attempted until 1 hour after the `invoice.created` webhook, for example, so you might not want to display that invoice as unpaid to your users. + #[serde(skip_serializing_if = "Option::is_none")] + pub attempted: Option, + + /// Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) of the invoice. + /// + /// When `false`, the invoice's state will not automatically advance without an explicit action. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_advance: Option, + + /// Indicates the reason why the invoice was created. + /// + /// `subscription_cycle` indicates an invoice created by a subscription advancing into a new period. + /// `subscription_create` indicates an invoice created due to creating a subscription. + /// `subscription_update` indicates an invoice created due to updating a subscription. + /// `subscription` is set for all old invoices to indicate either a change to a subscription or a period advancement. + /// `manual` is set for all invoices unrelated to a subscription (for example: created via the invoice editor). + /// The `upcoming` value is reserved for simulated invoices per the upcoming invoice endpoint. + /// `subscription_threshold` indicates an invoice created due to a billing threshold being reached. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_reason: Option, + + /// ID of the latest charge generated for this invoice, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option>, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. + /// When sending an invoice, Stripe will email this invoice to the customer with payment instructions. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// Custom fields displayed on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_fields: Option>, + + /// The ID of the customer who will be billed. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// The customer's address. + /// + /// Until the invoice is finalized, this field will equal `customer.address`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_address: Option
, + + /// The customer's email. + /// + /// Until the invoice is finalized, this field will equal `customer.email`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_email: Option, + + /// The customer's name. + /// + /// Until the invoice is finalized, this field will equal `customer.name`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_name: Option, + + /// The customer's phone number. + /// + /// Until the invoice is finalized, this field will equal `customer.phone`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_phone: Option, + + /// The customer's shipping information. + /// + /// Until the invoice is finalized, this field will equal `customer.shipping`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_shipping: Option, + + /// The customer's tax exempt status. + /// + /// Until the invoice is finalized, this field will equal `customer.tax_exempt`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_tax_exempt: Option, + + /// The customer's tax IDs. + /// + /// Until the invoice is finalized, this field will contain the same tax IDs as `customer.tax_ids`. + /// Once the invoice is finalized, this field will no longer be updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer_tax_ids: Option>, + + /// ID of the default payment method for the invoice. + /// + /// It must belong to the customer associated with the invoice. + /// If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option>, + + /// ID of the default payment source for the invoice. + /// + /// It must belong to the customer associated with the invoice and be in a chargeable state. + /// If not set, defaults to the subscription's default source, if any, or to the customer's default source. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option>, + + /// The tax rates applied to this invoice, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + /// Referenced as 'memo' in the Dashboard. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// Describes the current discount applied to this invoice, if there is one. + #[serde(skip_serializing_if = "Option::is_none")] + pub discount: Option, + + /// The date on which payment for this invoice is due. + /// + /// This value will be `null` for invoices where `collection_method=charge_automatically`. + #[serde(skip_serializing_if = "Option::is_none")] + pub due_date: Option, + + /// Ending customer balance after the invoice is finalized. + /// + /// Invoices are finalized approximately an hour after successful webhook delivery or when payment collection is attempted for the invoice. + /// If the invoice has not been finalized yet, this will be null. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_balance: Option, + + /// Footer displayed on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub footer: Option, + + /// The URL for the hosted invoice page, which allows customers to view and pay an invoice. + /// + /// If the invoice has not been finalized yet, this will be null. + #[serde(skip_serializing_if = "Option::is_none")] + pub hosted_invoice_url: Option, + + /// The link to download the PDF for the invoice. + /// + /// If the invoice has not been finalized yet, this will be null. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_pdf: Option, + + /// The individual line items that make up the invoice. + /// + /// `lines` is sorted as follows: invoice items in reverse chronological order, followed by the subscription, if any. + #[serde(default)] + pub lines: List, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The time at which payment will next be attempted. + /// + /// This value will be `null` for invoices where `collection_method=send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_payment_attempt: Option, + + /// A unique, identifying string that appears on emails sent to the customer for this invoice. + /// + /// This starts with the customer's unique invoice_prefix if it is specified. + #[serde(skip_serializing_if = "Option::is_none")] + pub number: Option, + + /// Whether payment was successfully collected for this invoice. + /// + /// An invoice can be paid (most commonly) with a charge or with credit from the customer's account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub paid: Option, + + /// The PaymentIntent associated with this invoice. + /// + /// The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice. + /// Note that voiding an invoice will cancel the PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// End of the usage period during which invoice items were added to this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub period_end: Option, + + /// Start of the usage period during which invoice items were added to this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub period_start: Option, + + /// Total amount of all post-payment credit notes issued for this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub post_payment_credit_notes_amount: Option, + + /// Total amount of all pre-payment credit notes issued for this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub pre_payment_credit_notes_amount: Option, + + /// This is the transaction number that appears on email receipts sent for this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_number: Option, + + /// Starting customer balance before the invoice is finalized. + /// + /// If the invoice has not been finalized yet, this will be the current customer balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_balance: Option, + + /// Extra information about an invoice for the customer's credit card statement. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. + /// + /// [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub status_transitions: Option, + + /// The subscription that this invoice was prepared for, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option>, + + /// Only set for upcoming invoices that preview prorations. + /// + /// The time used to calculate prorations. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_proration_date: Option, + + /// Total of all subscriptions, invoice items, and prorations on the invoice before any discount or tax is applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub subtotal: Option, + + /// The amount of tax on this invoice. + /// + /// This is the sum of all the tax amounts on this invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax: Option, + + /// This percentage of the subtotal has been added to the total amount of the invoice, including invoice line items and discounts. + /// + /// This field is inherited from the subscription's `tax_percent` field, but can be changed before the invoice is paid. + /// This field defaults to null. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub threshold_reason: Option, + + /// Total after discounts and taxes. + #[serde(skip_serializing_if = "Option::is_none")] + pub total: Option, + + /// The aggregate amounts calculated per tax rate for all line items. + #[serde(skip_serializing_if = "Option::is_none")] + pub total_tax_amounts: Option>, + + /// Invoices are automatically paid or sent 1 hour after webhooks are delivered, or until all webhook delivery attempts have [been exhausted](https://stripe.com/docs/billing/webhooks#understand). + /// + /// This field tracks the time when webhooks for this invoice were successfully delivered. + /// If the invoice had no webhooks to deliver, this will be set while the invoice is being created. + #[serde(skip_serializing_if = "Option::is_none")] + pub webhooks_delivered_at: Option, +} + +impl Invoice { + /// You can list all invoices, or list the invoices for a specific customer. + /// + /// The invoices are returned sorted by creation date, with the most recently created invoices appearing first. + pub fn list(client: &Client, params: ListInvoices<'_>) -> Response> { + client.get_query("/invoices", ¶ms) + } + + /// This endpoint creates a draft invoice for a given customer. + /// + /// The draft invoice created pulls in all pending invoice items on that customer, including prorations. + pub fn create(client: &Client, params: CreateInvoice<'_>) -> Response { + client.post_form("/invoices", ¶ms) + } + + /// Retrieves the invoice with the given ID. + pub fn retrieve(client: &Client, id: &InvoiceId, expand: &[&str]) -> Response { + client.get_query(&format!("/invoices/{}", id), &Expand { expand }) + } +} + +impl Object for Invoice { + type Id = InvoiceId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "invoice" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceSettingCustomField { + /// The name of the custom field. + pub name: String, + + /// The value of the custom field. + pub value: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxAmount { + /// The amount, in %s, of the tax. + pub amount: i64, + + /// Whether this tax amount is inclusive or exclusive. + pub inclusive: bool, + + /// The tax rate that was applied to get this tax amount. + pub tax_rate: Expandable, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceThresholdReason { + /// The total invoice amount threshold boundary if it triggered the threshold invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_gte: Option, + + /// Indicates which line items triggered a threshold invoice. + pub item_reasons: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItemThresholdReason { + /// The IDs of the line items that triggered the threshold invoice. + pub line_item_ids: Vec, + + /// The quantity threshold boundary that applied to the given line item. + pub usage_gte: i64, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoicesResourceInvoiceTaxId { + /// The type of the tax ID, one of `eu_vat`, `br_cnpj`, `br_cpf`, `nz_gst`, `au_abn`, `in_gst`, `no_vat`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `li_uid`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `my_sst`, `sg_gst`, or `unknown`. + #[serde(rename = "type")] + pub type_: TaxIdType, + + /// The value of the tax ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoicesStatusTransitions { + /// The time that the invoice draft was finalized. + #[serde(skip_serializing_if = "Option::is_none")] + pub finalized_at: Option, + + /// The time that the invoice was marked uncollectible. + #[serde(skip_serializing_if = "Option::is_none")] + pub marked_uncollectible_at: Option, + + /// The time that the invoice was paid. + #[serde(skip_serializing_if = "Option::is_none")] + pub paid_at: Option, + + /// The time that the invoice was voided. + #[serde(skip_serializing_if = "Option::is_none")] + pub voided_at: Option, +} + +/// The parameters for `Invoice::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateInvoice<'a> { + /// A fee in %s that will be applied to the invoice and transferred to the application owner's Stripe account. + /// + /// The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. + /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#invoices). + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + + /// Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) of the invoice. + /// + /// When `false`, the invoice's state will not automatically advance without an explicit action. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_advance: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. + /// When sending an invoice, Stripe will email this invoice to the customer with payment instructions. + /// Defaults to `charge_automatically`. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// A list of up to 4 custom fields to be displayed on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_fields: Option>, + + /// The ID of the customer who will be billed. + pub customer: CustomerId, + + /// The number of days from when the invoice is created until it is due. + /// + /// Valid only for invoices where `collection_method=send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub days_until_due: Option, + + /// ID of the default payment method for the invoice. + /// + /// It must belong to the customer associated with the invoice. + /// If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option<&'a str>, + + /// ID of the default payment source for the invoice. + /// + /// It must belong to the customer associated with the invoice and be in a chargeable state. + /// If not set, defaults to the subscription's default source, if any, or to the customer's default source. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option<&'a str>, + + /// The tax rates that will apply to any line item that does not have `tax_rates` set. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + /// Referenced as 'memo' in the Dashboard. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The date on which payment for this invoice is due. + /// + /// Valid only for invoices where `collection_method=send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub due_date: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Footer to be displayed on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub footer: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Extra information about a charge for the customer's credit card statement. + /// + /// It must contain at least one letter. + /// If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + + /// The ID of the subscription to invoice, if any. + /// + /// If not set, the created invoice will include all pending invoice items for the customer. + /// If set, the created invoice will only include pending invoice items for that subscription and pending invoice items not associated with any subscription. + /// The subscription's billing cycle and regular subscription events won't be affected. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, + + /// The percent tax rate applied to the invoice, represented as a decimal number. + /// + /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, +} + +impl<'a> CreateInvoice<'a> { + pub fn new(customer: CustomerId) -> Self { + CreateInvoice { + application_fee_amount: Default::default(), + auto_advance: Default::default(), + collection_method: Default::default(), + custom_fields: Default::default(), + customer, + days_until_due: Default::default(), + default_payment_method: Default::default(), + default_source: Default::default(), + default_tax_rates: Default::default(), + description: Default::default(), + due_date: Default::default(), + expand: Default::default(), + footer: Default::default(), + metadata: Default::default(), + statement_descriptor: Default::default(), + subscription: Default::default(), + tax_percent: Default::default(), + } + } +} + +/// The parameters for `Invoice::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListInvoices<'a> { + /// The collection method of the invoice to retrieve. + /// + /// Either `charge_automatically` or `send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return invoices for the customer specified by this customer ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub due_date: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. + /// + /// [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + /// Only return invoices for the subscription specified by this subscription ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, +} + +impl<'a> ListInvoices<'a> { + pub fn new() -> Self { + ListInvoices { + collection_method: Default::default(), + created: Default::default(), + customer: Default::default(), + due_date: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + status: Default::default(), + subscription: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Invoice`'s `collection_method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CollectionMethod { + ChargeAutomatically, + SendInvoice, +} + +impl CollectionMethod { + pub fn as_str(self) -> &'static str { + match self { + CollectionMethod::ChargeAutomatically => "charge_automatically", + CollectionMethod::SendInvoice => "send_invoice", + } + } +} + +impl AsRef for CollectionMethod { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CollectionMethod { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Invoice`'s `billing_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum InvoiceBillingReason { + AutomaticPendingInvoiceItemInvoice, + Manual, + Subscription, + SubscriptionCreate, + SubscriptionCycle, + SubscriptionThreshold, + SubscriptionUpdate, + Upcoming, +} + +impl InvoiceBillingReason { + pub fn as_str(self) -> &'static str { + match self { + InvoiceBillingReason::AutomaticPendingInvoiceItemInvoice => { + "automatic_pending_invoice_item_invoice" + } + InvoiceBillingReason::Manual => "manual", + InvoiceBillingReason::Subscription => "subscription", + InvoiceBillingReason::SubscriptionCreate => "subscription_create", + InvoiceBillingReason::SubscriptionCycle => "subscription_cycle", + InvoiceBillingReason::SubscriptionThreshold => "subscription_threshold", + InvoiceBillingReason::SubscriptionUpdate => "subscription_update", + InvoiceBillingReason::Upcoming => "upcoming", + } + } +} + +impl AsRef for InvoiceBillingReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for InvoiceBillingReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Invoice`'s `customer_tax_exempt` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum InvoiceCustomerTaxExempt { + Exempt, + None, + Reverse, +} + +impl InvoiceCustomerTaxExempt { + pub fn as_str(self) -> &'static str { + match self { + InvoiceCustomerTaxExempt::Exempt => "exempt", + InvoiceCustomerTaxExempt::None => "none", + InvoiceCustomerTaxExempt::Reverse => "reverse", + } + } +} + +impl AsRef for InvoiceCustomerTaxExempt { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for InvoiceCustomerTaxExempt { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Invoice`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum InvoiceStatus { + Deleted, + Draft, + Open, + Paid, + Uncollectible, + Void, +} + +impl InvoiceStatus { + pub fn as_str(self) -> &'static str { + match self { + InvoiceStatus::Deleted => "deleted", + InvoiceStatus::Draft => "draft", + InvoiceStatus::Open => "open", + InvoiceStatus::Paid => "paid", + InvoiceStatus::Uncollectible => "uncollectible", + InvoiceStatus::Void => "void", + } + } +} + +impl AsRef for InvoiceStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for InvoiceStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListInvoices`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum InvoiceStatusFilter { + Draft, + Open, + Paid, + Uncollectible, + Void, +} + +impl InvoiceStatusFilter { + pub fn as_str(self) -> &'static str { + match self { + InvoiceStatusFilter::Draft => "draft", + InvoiceStatusFilter::Open => "open", + InvoiceStatusFilter::Paid => "paid", + InvoiceStatusFilter::Uncollectible => "uncollectible", + InvoiceStatusFilter::Void => "void", + } + } +} + +impl AsRef for InvoiceStatusFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for InvoiceStatusFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `InvoicesResourceInvoiceTaxId`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TaxIdType { + AuAbn, + BrCnpj, + BrCpf, + CaBn, + CaQst, + ChVat, + EsCif, + EuVat, + HkBr, + InGst, + JpCn, + KrBrn, + LiUid, + MxRfc, + MyItn, + MySst, + NoVat, + NzGst, + RuInn, + SgGst, + SgUen, + ThVat, + TwVat, + Unknown, + UsEin, + ZaVat, +} + +impl TaxIdType { + pub fn as_str(self) -> &'static str { + match self { + TaxIdType::AuAbn => "au_abn", + TaxIdType::BrCnpj => "br_cnpj", + TaxIdType::BrCpf => "br_cpf", + TaxIdType::CaBn => "ca_bn", + TaxIdType::CaQst => "ca_qst", + TaxIdType::ChVat => "ch_vat", + TaxIdType::EsCif => "es_cif", + TaxIdType::EuVat => "eu_vat", + TaxIdType::HkBr => "hk_br", + TaxIdType::InGst => "in_gst", + TaxIdType::JpCn => "jp_cn", + TaxIdType::KrBrn => "kr_brn", + TaxIdType::LiUid => "li_uid", + TaxIdType::MxRfc => "mx_rfc", + TaxIdType::MyItn => "my_itn", + TaxIdType::MySst => "my_sst", + TaxIdType::NoVat => "no_vat", + TaxIdType::NzGst => "nz_gst", + TaxIdType::RuInn => "ru_inn", + TaxIdType::SgGst => "sg_gst", + TaxIdType::SgUen => "sg_uen", + TaxIdType::ThVat => "th_vat", + TaxIdType::TwVat => "tw_vat", + TaxIdType::Unknown => "unknown", + TaxIdType::UsEin => "us_ein", + TaxIdType::ZaVat => "za_vat", + } + } +} + +impl AsRef for TaxIdType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TaxIdType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/invoice_ext.rs b/ft-stripe/src/resources/invoice_ext.rs new file mode 100644 index 0000000..9ec15d2 --- /dev/null +++ b/ft-stripe/src/resources/invoice_ext.rs @@ -0,0 +1,72 @@ +use crate::config::{Client, Response}; +use crate::ids::{CouponId, CustomerId, InvoiceId, PlanId, SubscriptionId, SubscriptionItemId}; +use crate::params::{Metadata, Timestamp}; +use crate::resources::{CollectionMethod, Invoice}; +use serde::Serialize; + +#[deprecated(since = "0.12.0")] +pub type InvoiceCollectionMethod = CollectionMethod; + +impl Invoice { + /// Retrieves the details of an upcoming invoice_id + /// + /// For more details see https://stripe.com/docs/api#upcoming_invoice + pub fn upcoming(client: &Client, params: RetrieveUpcomingInvoice) -> Response { + client.get_query("/invoices/upcoming", ¶ms) + } + + /// Pays an invoice. + /// + /// For more details see https://stripe.com/docs/api#pay_invoice. + pub fn pay(client: &Client, invoice_id: &InvoiceId) -> Response { + client.post(&format!("/invoices/{}/pay", invoice_id)) + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct RetrieveUpcomingInvoice { + pub customer: CustomerId, // this is a required param + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_items: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_prorate: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_proration_date: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_tax_percent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_trial_end: Option, +} + +impl RetrieveUpcomingInvoice { + pub fn new(customer: CustomerId) -> Self { + RetrieveUpcomingInvoice { + customer, + coupon: None, + subscription: None, + subscription_items: None, + subscription_prorate: None, + subscription_proration_date: None, + subscription_tax_percent: None, + subscription_trial_end: None, + } + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct SubscriptionItemFilter { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, +} diff --git a/ft-stripe/src/resources/invoiceitem.rs b/ft-stripe/src/resources/invoiceitem.rs new file mode 100644 index 0000000..eca618d --- /dev/null +++ b/ft-stripe/src/resources/invoiceitem.rs @@ -0,0 +1,452 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, InvoiceId, InvoiceItemId, PriceId, SubscriptionId}; +use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{Currency, Customer, Invoice, Period, Plan, Price, Subscription, TaxRate}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "InvoiceItem". +/// +/// For more details see [https://stripe.com/docs/api/invoiceitems/object](https://stripe.com/docs/api/invoiceitems/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItem { + /// Unique identifier for the object. + pub id: InvoiceItemId, + + /// Amount (in the `currency` specified) of the invoice item. + /// + /// This should always be equal to `unit_amount * quantity`. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The ID of the customer who will be billed when this invoice item is billed. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// If true, discounts will apply to this invoice item. + /// + /// Always false for prorations. + #[serde(skip_serializing_if = "Option::is_none")] + pub discountable: Option, + + /// The ID of the invoice this invoice item belongs to. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub period: Option, + + /// If the invoice item is a proration, the plan of the subscription that the proration was computed for. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// The price of the invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Whether the invoice item was created automatically as a proration adjustment when the customer switched plans. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration: Option, + + /// Quantity of units for the invoice item. + /// + /// If the invoice item is a proration, the quantity of the subscription that the proration was computed for. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The subscription that this invoice item has been created for, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option>, + + /// The subscription item that this invoice item has been created for, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_item: Option, + + /// The tax rates which apply to the invoice item. + /// + /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, + + /// Unit Amount (in the `currency` specified) of the invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +impl InvoiceItem { + /// Returns a list of your invoice items. + /// + /// Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. + pub fn list(client: &Client, params: ListInvoiceItems<'_>) -> Response> { + client.get_query("/invoiceitems", ¶ms) + } + + /// Creates an item to be added to a draft invoice. + /// + /// If no invoice is specified, the item will be on the next invoice created for the customer specified. + pub fn create(client: &Client, params: CreateInvoiceItem<'_>) -> Response { + client.post_form("/invoiceitems", ¶ms) + } + + /// Retrieves the invoice item with the given ID. + pub fn retrieve(client: &Client, id: &InvoiceItemId, expand: &[&str]) -> Response { + client.get_query(&format!("/invoiceitems/{}", id), &Expand { expand }) + } + + /// Updates the amount or description of an invoice item on an upcoming invoice. + /// + /// Updating an invoice item is only possible before the invoice it’s attached to is closed. + pub fn update( + client: &Client, + id: &InvoiceItemId, + params: UpdateInvoiceItem<'_>, + ) -> Response { + client.post_form(&format!("/invoiceitems/{}", id), ¶ms) + } + + /// Deletes an invoice item, removing it from an invoice. + /// + /// Deleting invoice items is only possible when they’re not attached to invoices, or if it’s attached to a draft invoice. + pub fn delete(client: &Client, id: &InvoiceItemId) -> Response> { + client.delete(&format!("/invoiceitems/{}", id)) + } +} + +impl Object for InvoiceItem { + type Id = InvoiceItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "invoiceitem" + } +} + +/// The parameters for `InvoiceItem::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateInvoiceItem<'a> { + /// The integer amount in **%s** of the charge to be applied to the upcoming invoice. + /// + /// Passing in a negative `amount` will reduce the `amount_due` on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The ID of the customer who will be billed when this invoice item is billed. + pub customer: CustomerId, + + /// An arbitrary string which you can attach to the invoice item. + /// + /// The description is displayed in the invoice for easy tracking. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Controls whether discounts apply to this invoice item. + /// + /// Defaults to false for prorations or negative invoice items, and true for all other invoice items. + #[serde(skip_serializing_if = "Option::is_none")] + pub discountable: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The ID of an existing invoice to add this invoice item to. + /// + /// When left blank, the invoice item will be added to the next upcoming scheduled invoice. + /// This is useful when adding invoice items in response to an invoice.created webhook. + /// You can only add invoice items to draft invoices. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The period associated with this invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub period: Option, + + /// The ID of the price object. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Data used to generate a new price object inline. + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + /// Non-negative integer. + /// + /// The quantity of units for the invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The ID of a subscription to add this invoice item to. + /// + /// When left blank, the invoice item will be be added to the next upcoming scheduled invoice. + /// When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. + /// Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, + + /// The tax rates which apply to the invoice item. + /// + /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, + + /// The integer unit amount in **%s** of the charge to be applied to the upcoming invoice. + /// + /// This `unit_amount` will be multiplied by the quantity to get the full amount. + /// Passing in a negative `unit_amount` will reduce the `amount_due` on the invoice. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. + /// + /// Only one of `unit_amount` and `unit_amount_decimal` can be set. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option<&'a str>, +} + +impl<'a> CreateInvoiceItem<'a> { + pub fn new(customer: CustomerId) -> Self { + CreateInvoiceItem { + amount: Default::default(), + currency: Default::default(), + customer, + description: Default::default(), + discountable: Default::default(), + expand: Default::default(), + invoice: Default::default(), + metadata: Default::default(), + period: Default::default(), + price: Default::default(), + price_data: Default::default(), + quantity: Default::default(), + subscription: Default::default(), + tax_rates: Default::default(), + unit_amount: Default::default(), + unit_amount_decimal: Default::default(), + } + } +} + +/// The parameters for `InvoiceItem::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListInvoiceItems<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// The identifier of the customer whose invoice items to return. + /// + /// If none is provided, all invoice items will be returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Only return invoice items belonging to this invoice. + /// + /// If none is provided, all invoice items will be returned. + /// If specifying an invoice, no customer identifier is needed. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Set to `true` to only show pending invoice items, which are not yet attached to any invoices. + /// + /// Set to `false` to only show invoice items already attached to invoices. + /// If unspecified, no filter is applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListInvoiceItems<'a> { + pub fn new() -> Self { + ListInvoiceItems { + created: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + invoice: Default::default(), + limit: Default::default(), + pending: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `InvoiceItem::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateInvoiceItem<'a> { + /// The integer amount in **%s** of the charge to be applied to the upcoming invoice. + /// + /// If you want to apply a credit to the customer's account, pass a negative amount. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// An arbitrary string which you can attach to the invoice item. + /// + /// The description is displayed in the invoice for easy tracking. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Controls whether discounts apply to this invoice item. + /// + /// Defaults to false for prorations or negative invoice items, and true for all other invoice items. + /// Cannot be set to true for prorations. + #[serde(skip_serializing_if = "Option::is_none")] + pub discountable: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The period associated with this invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub period: Option, + + /// The ID of the price object. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Data used to generate a new price object inline. + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + /// Non-negative integer. + /// + /// The quantity of units for the invoice item. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The tax rates which apply to the invoice item. + /// + /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. + /// Pass an empty string to remove previously-defined tax rates. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, + + /// The integer unit amount in **%s** of the charge to be applied to the upcoming invoice. + /// + /// This unit_amount will be multiplied by the quantity to get the full amount. + /// If you want to apply a credit to the customer's account, pass a negative unit_amount. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. + /// + /// Only one of `unit_amount` and `unit_amount_decimal` can be set. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option<&'a str>, +} + +impl<'a> UpdateInvoiceItem<'a> { + pub fn new() -> Self { + UpdateInvoiceItem { + amount: Default::default(), + description: Default::default(), + discountable: Default::default(), + expand: Default::default(), + metadata: Default::default(), + period: Default::default(), + price: Default::default(), + price_data: Default::default(), + quantity: Default::default(), + tax_rates: Default::default(), + unit_amount: Default::default(), + unit_amount_decimal: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItemPriceData { + pub currency: Currency, + + pub product: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} diff --git a/ft-stripe/src/resources/issuing_authorization.rs b/ft-stripe/src/resources/issuing_authorization.rs new file mode 100644 index 0000000..b7f1290 --- /dev/null +++ b/ft-stripe/src/resources/issuing_authorization.rs @@ -0,0 +1,207 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::IssuingAuthorizationId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{ + BalanceTransaction, Currency, IssuingAuthorizationCheck, IssuingAuthorizationMethod, + IssuingAuthorizationReason, IssuingCard, IssuingCardholder, IssuingTransaction, MerchantData, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingAuthorization". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingAuthorization { + /// Unique identifier for the object. + pub id: IssuingAuthorizationId, + + /// The total amount that was authorized or rejected. + /// + /// This amount is in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub amount: i64, + + /// Whether the authorization has been approved. + pub approved: bool, + + /// How the card details were provided. + pub authorization_method: IssuingAuthorizationMethod, + + /// List of balance transactions associated with this authorization. + pub balance_transactions: Vec, + + pub card: IssuingCard, + + /// The cardholder to whom this authorization belongs. + #[serde(skip_serializing_if = "Option::is_none")] + pub cardholder: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// The total amount that was authorized or rejected. + /// + /// This amount is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub merchant_amount: i64, + + /// The currency that was presented to the cardholder for the authorization. + /// + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub merchant_currency: Currency, + + pub merchant_data: MerchantData, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The pending authorization request. + /// + /// This field will only be non-null during an `issuing_authorization.request` webhook. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_request: Option, + + /// History of every time the authorization was approved/denied (whether approved/denied by you directly or by Stripe based on your `spending_controls`). + /// + /// If the merchant changes the authorization by performing an [incremental authorization or partial capture](https://stripe.com/docs/issuing/purchases/authorizations), you can look at this field to see the previous states of the authorization. + pub request_history: Vec, + + /// The current status of the authorization in its lifecycle. + pub status: IssuingAuthorizationStatus, + + /// List of [transactions](https://stripe.com/docs/api/issuing/transactions) associated with this authorization. + pub transactions: Vec, + + pub verification_data: IssuingAuthorizationVerificationData, + + /// What, if any, digital wallet was used for this authorization. + /// + /// One of `apple_pay`, `google_pay`, or `samsung_pay`. + #[serde(skip_serializing_if = "Option::is_none")] + pub wallet: Option, +} + +impl Object for IssuingAuthorization { + type Id = IssuingAuthorizationId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.authorization" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingAuthorizationPendingRequest { + /// The additional amount Stripe will hold if the authorization is approved, in the card's [currency](https://stripe.com/docs/api#issuing_authorization_object-pending-request-currency) and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. + pub is_amount_controllable: bool, + + /// The amount the merchant is requesting to be authorized in the `merchant_currency`. + /// + /// The amount is in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub merchant_amount: i64, + + /// The local currency the merchant is requesting to authorize. + pub merchant_currency: Currency, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingAuthorizationRequest { + /// The authorization amount in your card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + /// + /// Stripe held this amount from your account to fund the authorization if the request was approved. + pub amount: i64, + + /// Whether this request was approved. + pub approved: bool, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The amount that was authorized at the time of this request. + /// + /// This amount is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub merchant_amount: i64, + + /// The currency that was collected by the merchant and presented to the cardholder for the authorization. + /// + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub merchant_currency: Currency, + + /// The reason for the approval or decline. + pub reason: IssuingAuthorizationReason, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingAuthorizationVerificationData { + /// Whether the cardholder provided an address first line and if it matched the cardholder’s `billing.address.line1`. + pub address_line1_check: IssuingAuthorizationCheck, + + /// Whether the cardholder provided a postal code and if it matched the cardholder’s `billing.address.postal_code`. + pub address_postal_code_check: IssuingAuthorizationCheck, + + /// Whether the cardholder provided a CVC and if it matched Stripe’s record. + pub cvc_check: IssuingAuthorizationCheck, + + /// Whether the cardholder provided an expiry date and if it matched Stripe’s record. + pub expiry_check: IssuingAuthorizationCheck, +} + +/// An enum representing the possible values of an `IssuingAuthorization`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingAuthorizationStatus { + Closed, + Pending, + Reversed, +} + +impl IssuingAuthorizationStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingAuthorizationStatus::Closed => "closed", + IssuingAuthorizationStatus::Pending => "pending", + IssuingAuthorizationStatus::Reversed => "reversed", + } + } +} + +impl AsRef for IssuingAuthorizationStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingAuthorizationStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_authorization_ext.rs b/ft-stripe/src/resources/issuing_authorization_ext.rs new file mode 100644 index 0000000..08067e2 --- /dev/null +++ b/ft-stripe/src/resources/issuing_authorization_ext.rs @@ -0,0 +1,69 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of the `IssuingAuthorizationVerificationData` fields. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingAuthorizationCheck { + Match, + Mismatch, + NotProvided, +} + +/// An enum representing the possible values of the `IssuingAuthorization`'s `authorization_method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingAuthorizationMethod { + KeyedIn, + Swipe, + Chip, + Contactless, + Online, +} + +/// An enum representing the possible values of the `IssuingAuthorizationRequest`'s `reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingAuthorizationReason { + AuthenticationFailed, + AuthorizationControls, + CardActive, + CardInactive, + InsufficientFunds, + AccountComplianceDisabled, + AccountInactive, + SuspectedFraud, + WebhookApproved, + WebhookDeclined, + WebhookTimeout, +} + +/// An enum representing the possible values of an `IssuingAuthorization`'s `wallet_provider` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingAuthorizationWalletProvider { + ApplePay, + GooglePay, + SamsungPay, +} + +impl IssuingAuthorizationWalletProvider { + pub fn as_str(self) -> &'static str { + match self { + IssuingAuthorizationWalletProvider::ApplePay => "apple_pay", + IssuingAuthorizationWalletProvider::GooglePay => "google_pay", + IssuingAuthorizationWalletProvider::SamsungPay => "samsung_pay", + } + } +} + +impl AsRef for IssuingAuthorizationWalletProvider { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingAuthorizationWalletProvider { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_card.rs b/ft-stripe/src/resources/issuing_card.rs new file mode 100644 index 0000000..0f26c16 --- /dev/null +++ b/ft-stripe/src/resources/issuing_card.rs @@ -0,0 +1,312 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::IssuingCardId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{ + Address, CardBrand, Currency, IssuingCardShippingStatus, IssuingCardShippingType, + IssuingCardType, IssuingCardholder, MerchantCategory, SpendingLimit, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingCard". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCard { + /// Unique identifier for the object. + pub id: IssuingCardId, + + /// The brand of the card. + pub brand: CardBrand, + + /// The reason why the card was canceled. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_reason: Option, + + pub cardholder: IssuingCardholder, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The card's CVC. + /// + /// For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). + /// Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc: Option, + + /// The expiration month of the card. + pub exp_month: i64, + + /// The expiration year of the card. + pub exp_year: i64, + + /// The last 4 digits of the card number. + pub last4: String, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The full unredacted card number. + /// + /// For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). + /// Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub number: Option, + + /// The latest card that replaces this card, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub replaced_by: Option>, + + /// The card this card replaces, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub replacement_for: Option>, + + /// The reason why the previous card needed to be replaced. + #[serde(skip_serializing_if = "Option::is_none")] + pub replacement_reason: Option, + + /// Where and how the card will be shipped. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + pub spending_controls: IssuingCardAuthorizationControls, + + /// Whether authorizations can be approved on this card. + pub status: IssuingCardStatus, + + /// The type of the card. + #[serde(rename = "type")] + pub type_: IssuingCardType, +} + +impl Object for IssuingCard { + type Id = IssuingCardId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.card" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardAuthorizationControls { + /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations permitted on this card. + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_categories: Option>, + + /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to always decline on this card. + #[serde(skip_serializing_if = "Option::is_none")] + pub blocked_categories: Option>, + + /// Limit the spending with rules based on time intervals and categories. + #[serde(skip_serializing_if = "Option::is_none")] + pub spending_limits: Option>, + + /// Currency for the amounts within spending_limits. + /// + /// Locked to the currency of the card. + #[serde(skip_serializing_if = "Option::is_none")] + pub spending_limits_currency: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardShipping { + pub address: Address, + + /// The delivery company that shipped a card. + #[serde(skip_serializing_if = "Option::is_none")] + pub carrier: Option, + + /// A unix timestamp representing a best estimate of when the card will be delivered. + #[serde(skip_serializing_if = "Option::is_none")] + pub eta: Option, + + /// Recipient name. + pub name: String, + + /// Shipment service, such as `standard` or `express`. + pub service: IssuingCardShippingService, + + /// The delivery status of the card. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + /// A tracking number for a card shipment. + #[serde(skip_serializing_if = "Option::is_none")] + pub tracking_number: Option, + + /// A link to the shipping carrier's site where you can view detailed information about a card shipment. + #[serde(skip_serializing_if = "Option::is_none")] + pub tracking_url: Option, + + /// Packaging options. + #[serde(rename = "type")] + pub type_: IssuingCardShippingType, +} + +/// An enum representing the possible values of an `IssuingCard`'s `cancellation_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardCancellationReason { + Lost, + Stolen, +} + +impl IssuingCardCancellationReason { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardCancellationReason::Lost => "lost", + IssuingCardCancellationReason::Stolen => "stolen", + } + } +} + +impl AsRef for IssuingCardCancellationReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardCancellationReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCard`'s `replacement_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardReplacementReason { + Damaged, + Expired, + Lost, + Stolen, +} + +impl IssuingCardReplacementReason { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardReplacementReason::Damaged => "damaged", + IssuingCardReplacementReason::Expired => "expired", + IssuingCardReplacementReason::Lost => "lost", + IssuingCardReplacementReason::Stolen => "stolen", + } + } +} + +impl AsRef for IssuingCardReplacementReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardReplacementReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardShipping`'s `carrier` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardShippingCarrier { + Fedex, + Usps, +} + +impl IssuingCardShippingCarrier { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardShippingCarrier::Fedex => "fedex", + IssuingCardShippingCarrier::Usps => "usps", + } + } +} + +impl AsRef for IssuingCardShippingCarrier { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardShippingCarrier { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardShipping`'s `service` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardShippingService { + Express, + Priority, + Standard, +} + +impl IssuingCardShippingService { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardShippingService::Express => "express", + IssuingCardShippingService::Priority => "priority", + IssuingCardShippingService::Standard => "standard", + } + } +} + +impl AsRef for IssuingCardShippingService { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardShippingService { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCard`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardStatus { + Active, + Canceled, + Inactive, +} + +impl IssuingCardStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardStatus::Active => "active", + IssuingCardStatus::Canceled => "canceled", + IssuingCardStatus::Inactive => "inactive", + } + } +} + +impl AsRef for IssuingCardStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_card_ext.rs b/ft-stripe/src/resources/issuing_card_ext.rs new file mode 100644 index 0000000..06a3a7f --- /dev/null +++ b/ft-stripe/src/resources/issuing_card_ext.rs @@ -0,0 +1,125 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `IssuingCardPin`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardPinStatus { + Active, + Blocked, +} + +impl IssuingCardPinStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardPinStatus::Active => "active", + IssuingCardPinStatus::Blocked => "blocked", + } + } +} + +impl AsRef for IssuingCardPinStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardPinStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardShipping`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardShippingStatus { + Canceled, + Delivered, + Failure, + Pending, + Returned, + Shipped, +} + +impl IssuingCardShippingStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardShippingStatus::Canceled => "canceled", + IssuingCardShippingStatus::Delivered => "delivered", + IssuingCardShippingStatus::Failure => "failure", + IssuingCardShippingStatus::Pending => "pending", + IssuingCardShippingStatus::Returned => "returned", + IssuingCardShippingStatus::Shipped => "shipped", + } + } +} + +impl AsRef for IssuingCardShippingStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardShippingStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardShipping`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardShippingType { + Bulk, + Individual, +} + +impl IssuingCardShippingType { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardShippingType::Bulk => "bulk", + IssuingCardShippingType::Individual => "individual", + } + } +} + +impl AsRef for IssuingCardShippingType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardShippingType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCard`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardType { + Physical, + Virtual, +} + +impl IssuingCardType { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardType::Physical => "physical", + IssuingCardType::Virtual => "virtual", + } + } +} + +impl AsRef for IssuingCardType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_cardholder.rs b/ft-stripe/src/resources/issuing_cardholder.rs new file mode 100644 index 0000000..9399541 --- /dev/null +++ b/ft-stripe/src/resources/issuing_cardholder.rs @@ -0,0 +1,307 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::IssuingCardholderId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{Address, Currency, File, MerchantCategory, SpendingLimit}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingCardholder". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholder { + /// Unique identifier for the object. + pub id: IssuingCardholderId, + + pub billing: IssuingCardholderAddress, + + /// Additional information about a `company` cardholder. + #[serde(skip_serializing_if = "Option::is_none")] + pub company: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// The cardholder's email address. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// Additional information about an `individual` cardholder. + #[serde(skip_serializing_if = "Option::is_none")] + pub individual: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The cardholder's name. + /// + /// This will be printed on cards issued to them. + pub name: String, + + /// The cardholder's phone number. + #[serde(skip_serializing_if = "Option::is_none")] + pub phone_number: Option, + + pub requirements: IssuingCardholderRequirements, + + /// Spending rules that give you some control over how this cardholder's cards can be used. + /// + /// Refer to our [authorizations](https://stripe.com/docs/issuing/purchases/authorizations) documentation for more details. + #[serde(skip_serializing_if = "Option::is_none")] + pub spending_controls: Option, + + /// Specifies whether to permit authorizations on this cardholder's cards. + pub status: IssuingCardholderStatus, + + /// One of `individual` or `company`. + #[serde(rename = "type")] + pub type_: IssuingCardholderType, +} + +impl Object for IssuingCardholder { + type Id = IssuingCardholderId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.cardholder" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderAddress { + pub address: Address, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderAuthorizationControls { + /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations permitted on this cardholder's cards. + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_categories: Option>, + + /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to always decline on this cardholder's cards. + #[serde(skip_serializing_if = "Option::is_none")] + pub blocked_categories: Option>, + + /// Limit the spending with rules based on time intervals and categories. + #[serde(skip_serializing_if = "Option::is_none")] + pub spending_limits: Option>, + + /// Currency for the amounts within spending_limits. + #[serde(skip_serializing_if = "Option::is_none")] + pub spending_limits_currency: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderCompany { + /// Whether the company's business ID number was provided. + pub tax_id_provided: bool, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderIndividual { + /// The date of birth of this cardholder. + #[serde(skip_serializing_if = "Option::is_none")] + pub dob: Option, + + /// The first name of this cardholder. + pub first_name: String, + + /// The last name of this cardholder. + pub last_name: String, + + /// Government-issued ID document for this cardholder. + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderIndividualDob { + /// The day of birth, between 1 and 31. + #[serde(skip_serializing_if = "Option::is_none")] + pub day: Option, + + /// The month of birth, between 1 and 12. + #[serde(skip_serializing_if = "Option::is_none")] + pub month: Option, + + /// The four-digit year of birth. + #[serde(skip_serializing_if = "Option::is_none")] + pub year: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderRequirements { + /// If `disabled_reason` is present, all cards will decline authorizations with `cardholder_verification_required` reason. + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled_reason: Option, + + /// Array of fields that need to be collected in order to verify and re-enable the cardholder. + #[serde(skip_serializing_if = "Option::is_none")] + pub past_due: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderVerification { + /// An identifying document, either a passport or local ID card. + #[serde(skip_serializing_if = "Option::is_none")] + pub document: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholderIdDocument { + /// The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + #[serde(skip_serializing_if = "Option::is_none")] + pub back: Option>, + + /// The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + #[serde(skip_serializing_if = "Option::is_none")] + pub front: Option>, +} + +/// An enum representing the possible values of an `IssuingCardholderRequirements`'s `disabled_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardholderRequirementsDisabledReason { + Listed, + #[serde(rename = "rejected.listed")] + RejectedListed, + UnderReview, +} + +impl IssuingCardholderRequirementsDisabledReason { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardholderRequirementsDisabledReason::Listed => "listed", + IssuingCardholderRequirementsDisabledReason::RejectedListed => "rejected.listed", + IssuingCardholderRequirementsDisabledReason::UnderReview => "under_review", + } + } +} + +impl AsRef for IssuingCardholderRequirementsDisabledReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardholderRequirementsDisabledReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardholderRequirements`'s `past_due` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardholderRequirementsPastDue { + #[serde(rename = "company.tax_id")] + CompanyTaxId, + #[serde(rename = "individual.dob.day")] + IndividualDobDay, + #[serde(rename = "individual.dob.month")] + IndividualDobMonth, + #[serde(rename = "individual.dob.year")] + IndividualDobYear, + #[serde(rename = "individual.first_name")] + IndividualFirstName, + #[serde(rename = "individual.last_name")] + IndividualLastName, + #[serde(rename = "individual.verification.document")] + IndividualVerificationDocument, +} + +impl IssuingCardholderRequirementsPastDue { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardholderRequirementsPastDue::CompanyTaxId => "company.tax_id", + IssuingCardholderRequirementsPastDue::IndividualDobDay => "individual.dob.day", + IssuingCardholderRequirementsPastDue::IndividualDobMonth => "individual.dob.month", + IssuingCardholderRequirementsPastDue::IndividualDobYear => "individual.dob.year", + IssuingCardholderRequirementsPastDue::IndividualFirstName => "individual.first_name", + IssuingCardholderRequirementsPastDue::IndividualLastName => "individual.last_name", + IssuingCardholderRequirementsPastDue::IndividualVerificationDocument => { + "individual.verification.document" + } + } + } +} + +impl AsRef for IssuingCardholderRequirementsPastDue { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardholderRequirementsPastDue { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardholder`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardholderStatus { + Active, + Blocked, + Inactive, +} + +impl IssuingCardholderStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardholderStatus::Active => "active", + IssuingCardholderStatus::Blocked => "blocked", + IssuingCardholderStatus::Inactive => "inactive", + } + } +} + +impl AsRef for IssuingCardholderStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardholderStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingCardholder`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingCardholderType { + Company, + Individual, +} + +impl IssuingCardholderType { + pub fn as_str(self) -> &'static str { + match self { + IssuingCardholderType::Company => "company", + IssuingCardholderType::Individual => "individual", + } + } +} + +impl AsRef for IssuingCardholderType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingCardholderType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_dispute.rs b/ft-stripe/src/resources/issuing_dispute.rs new file mode 100644 index 0000000..7b5ef02 --- /dev/null +++ b/ft-stripe/src/resources/issuing_dispute.rs @@ -0,0 +1,27 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::IssuingDisputeId; +use crate::params::Object; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingDispute". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingDispute { + /// Unique identifier for the object. + pub id: IssuingDisputeId, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, +} + +impl Object for IssuingDispute { + type Id = IssuingDisputeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.dispute" + } +} diff --git a/ft-stripe/src/resources/issuing_dispute_ext.rs b/ft-stripe/src/resources/issuing_dispute_ext.rs new file mode 100644 index 0000000..170fbc9 --- /dev/null +++ b/ft-stripe/src/resources/issuing_dispute_ext.rs @@ -0,0 +1,63 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `IssuingDispute`'s `reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingDisputeReason { + Fraudulent, + Other, +} + +impl IssuingDisputeReason { + pub fn as_str(self) -> &'static str { + match self { + IssuingDisputeReason::Fraudulent => "fraudulent", + IssuingDisputeReason::Other => "other", + } + } +} + +impl AsRef for IssuingDisputeReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingDisputeReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `IssuingDispute`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingDisputeStatus { + Lost, + UnderReview, + Unsubmitted, + Won, +} + +impl IssuingDisputeStatus { + pub fn as_str(self) -> &'static str { + match self { + IssuingDisputeStatus::Lost => "lost", + IssuingDisputeStatus::UnderReview => "under_review", + IssuingDisputeStatus::Unsubmitted => "unsubmitted", + IssuingDisputeStatus::Won => "won", + } + } +} + +impl AsRef for IssuingDisputeStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingDisputeStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/issuing_merchant_data.rs b/ft-stripe/src/resources/issuing_merchant_data.rs new file mode 100644 index 0000000..d6765e9 --- /dev/null +++ b/ft-stripe/src/resources/issuing_merchant_data.rs @@ -0,0 +1,325 @@ +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingAuthorizationMerchantData". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MerchantData { + /// Identifier assigned to the seller by the card brand. + pub network_id: String, + + /// A categorization of the seller's type of business. + /// + /// See the [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. + pub category: MerchantCategory, + + /// Name of the seller. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// City where the seller is located. + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option, + + /// State where the seller is located. + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, + + /// Country where the seller is located. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Postal code where the seller is located. + #[serde(skip_serializing_if = "Option::is_none")] + pub postal_code: Option, +} + +/// An enum representing the industry of a merchant. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum MerchantCategory { + AcRefrigerationRepair, + AccountingBookkeepingServices, + AdvertisingServices, + AgriculturalCooperative, + AirlinesAirCarriers, + AirportsFlyingFields, + AmbulanceServices, + AmusementParksCarnivals, + AntiqueReproductions, + AntiqueShops, + Aquariums, + ArchitecturalSurveyingServices, + ArtDealersAndGalleries, + ArtistsSupplyAndCraftShops, + AutoAndHomeSupplyStores, + AutoBodyRepairShops, + AutoPaintShops, + AutoServiceShops, + AutomatedCashDisburse, + AutomatedFuelDispensers, + AutomobileAssociations, + AutomotivePartsAndAccessoriesStores, + AutomotiveTireStores, + BailAndBondPayments, + Bakeries, + BandsOrchestras, + BarberAndBeautyShops, + BettingCasinoGambling, + BicycleShops, + BilliardPoolEstablishments, + BoatDealers, + BoatRentalsAndLeases, + BookStores, + BooksPeriodicalsAndNewspapers, + BowlingAlleys, + BusLines, + BusinessSecretarialSchools, + BuyingShoppingServices, + CableSatelliteAndOtherPayTelevisionAndRadio, + CameraAndPhotographicSupplyStores, + CandyNutAndConfectioneryStores, + CarAndTruckDealersNewUsed, + CarAndTruckDealersUsedOnly, + CarRentalAgencies, + CarWashes, + CarpentryServices, + CarpetUpholsteryCleaning, + Caterers, + CharitableAndSocialServiceOrganizationsFundraising, + ChemicalsAndAlliedProducts, + ChidrensAndInfantsWearStores, + ChildCareServices, + ChiropodistsPodiatrists, + Chiropractors, + CigarStoresAndStands, + CivicSocialFraternalAssociations, + CleaningAndMaintenance, + ClothingRental, + CollegesUniversities, + CommercialEquipment, + CommercialFootwear, + CommercialPhotographyArtAndGraphics, + CommuterTransportAndFerries, + ComputerNetworkServices, + ComputerProgramming, + ComputerRepair, + ComputerSoftwareStores, + ComputersPeripheralsAndSoftware, + ConcreteWorkServices, + ConstructionMaterials, + ConsultingPublicRelations, + CorrespondenceSchools, + CosmeticStores, + CounselingServices, + CountryClubs, + CourierServices, + CourtCosts, + CreditReportingAgencies, + CruiseLines, + DairyProductsStores, + DanceHallStudiosSchools, + DatingEscortServices, + DentistsOrthodontists, + DepartmentStores, + DetectiveAgencies, + DirectMarketingCatalogMerchant, + DirectMarketingCombinationCatalogAndRetailMerchant, + DirectMarketingInboundTelemarketing, + DirectMarketingInsuranceServices, + DirectMarketingOther, + DirectMarketingOutboundTelemarketing, + DirectMarketingSubscription, + DirectMarketingTravel, + DiscountStores, + Doctors, + DoorToDoorSales, + DraperyWindowCoveringAndUpholsteryStores, + DrinkingPlaces, + DrugStoresAndPharmacies, + DrugsDrugProprietariesAndDruggistSundries, + DryCleaners, + DurableGoods, + DutyFreeStores, + EatingPlacesRestaurants, + EducationalServices, + ElectricRazorStores, + ElectricalPartsAndEquipment, + ElectricalServices, + ElectronicsRepairShops, + ElectronicsStores, + ElementarySecondarySchools, + EmploymentTempAgencies, + EquipmentRental, + ExterminatingServices, + FamilyClothingStores, + FastFoodRestaurants, + FinancialInstitutions, + FinesGovernmentAdministrativeEntities, + FireplaceFireplaceScreensAndAccessoriesStores, + FloorCoveringStores, + Florists, + FloristsSuppliesNurseryStockAndFlowers, + FreezerAndLockerMeatProvisioners, + FuelDealersNonAutomotive, + FuneralServicesCrematories, + FurnitureHomeFurnishingsAndEquipmentStoresExceptAppliances, + FurnitureRepairRefinishing, + FurriersAndFurShops, + GeneralServices, + GiftCardNoveltyAndSouvenirShops, + GlassPaintAndWallpaperStores, + GlasswareCrystalStores, + GolfCoursesPublic, + GovernmentServices, + GroceryStoresSupermarkets, + HardwareEquipmentAndSupplies, + HardwareStores, + HealthAndBeautySpas, + HearingAidsSalesAndSupplies, + #[serde(rename = "heating_plumbing_a_c")] + HeatingPlumbingAC, + HobbyToyAndGameShops, + HomeSupplyWarehouseStores, + Hospitals, + HotelsMotelsAndResorts, + HouseholdApplianceStores, + IndustrialSupplies, + InformationRetrievalServices, + InsuranceDefault, + InsuranceUnderwritingPremiums, + IntraCompanyPurchases, + JewelryStoresWatchesClocksAndSilverwareStores, + LandscapingServices, + Laundries, + LaundryCleaningServices, + LegalServicesAttorneys, + LuggageAndLeatherGoodsStores, + LumberBuildingMaterialsStores, + ManualCashDisburse, + MarinasServiceAndSupplies, + MasonryStoneworkAndPlaster, + MassageParlors, + MedicalAndDentalLabs, + MedicalDentalOphthalmicAndHospitalEquipmentAndSupplies, + MedicalServices, + MembershipOrganizations, + MensAndBoysClothingAndAccessoriesStores, + MensWomensClothingStores, + MetalServiceCenters, + Miscellaneous, + MiscellaneousApparelAndAccessoryShops, + MiscellaneousAutoDealers, + MiscellaneousBusinessServices, + MiscellaneousFoodStores, + MiscellaneousGeneralMerchandise, + MiscellaneousGeneralServices, + MiscellaneousHomeFurnishingSpecialtyStores, + MiscellaneousPublishingAndPrinting, + MiscellaneousRecreationServices, + MiscellaneousRepairShops, + MiscellaneousSpecialtyRetail, + MobileHomeDealers, + MotionPictureTheaters, + MotorFreightCarriersAndTrucking, + MotorHomesDealers, + MotorVehicleSuppliesAndNewParts, + MotorcycleShopsAndDealers, + MotorcycleShopsDealers, + MusicStoresMusicalInstrumentsPianosAndSheetMusic, + NewsDealersAndNewsstands, + NonFiMoneyOrders, + NonFiStoredValueCardPurchaseLoad, + NondurableGoods, + NurseriesLawnAndGardenSupplyStores, + NursingPersonalCare, + OfficeAndCommercialFurniture, + OpticiansEyeglasses, + OptometristsOphthalmologist, + OrthopedicGoodsProstheticDevices, + Osteopaths, + PackageStoresBeerWineAndLiquor, + PaintsVarnishesAndSupplies, + ParkingLotsGarages, + PassengerRailways, + PawnShops, + PetShopsPetFoodAndSupplies, + PetroleumAndPetroleumProducts, + PhotoDeveloping, + PhotographicPhotocopyMicrofilmEquipmentAndSupplies, + PhotographicStudios, + PictureVideoProduction, + PieceGoodsNotionsAndOtherDryGoods, + PlumbingHeatingEquipmentAndSupplies, + PoliticalOrganizations, + PostalServicesGovernmentOnly, + PreciousStonesAndMetalsWatchesAndJewelry, + ProfessionalServices, + PublicWarehousingAndStorage, + QuickCopyReproAndBlueprint, + Railroads, + RealEstateAgentsAndManagersRentals, + RecordStores, + RecreationalVehicleRentals, + ReligiousGoodsStores, + ReligiousOrganizations, + RoofingSidingSheetMetal, + SecretarialSupportServices, + SecurityBrokersDealers, + ServiceStations, + SewingNeedleworkFabricAndPieceGoodsStores, + ShoeRepairHatCleaning, + ShoeStores, + SmallApplianceRepair, + SnowmobileDealers, + SpecialTradeServices, + SpecialtyCleaning, + SportingGoodsStores, + SportingRecreationCamps, + SportsAndRidingApparelStores, + SportsClubsFields, + StampAndCoinStores, + StationaryOfficeSuppliesPrintingAndWritingPaper, + StationeryStoresOfficeAndSchoolSupplyStores, + SwimmingPoolsSales, + TUiTravelGermany, + TailorsAlterations, + TaxPaymentsGovernmentAgencies, + TaxPreparationServices, + TaxicabsLimousines, + TelecommunicationEquipmentAndTelephoneSales, + TelecommunicationServices, + TelegraphServices, + TentAndAwningShops, + TestingLaboratories, + TheatricalTicketAgencies, + Timeshares, + TireRetreadingAndRepair, + TollsBridgeFees, + TouristAttractionsAndExhibits, + TowingServices, + TrailerParksCampgrounds, + TransportationServices, + TravelAgenciesTourOperators, + TruckStopIteration, + TruckUtilityTrailerRentals, + TypesettingPlateMakingAndRelatedServices, + TypewriterStores, + #[serde(rename = "u_s_federal_government_agencies_or_departments")] + USFederalGovernmentAgenciesOrDepartments, + UniformsCommercialClothing, + UsedMerchandiseAndSecondhandStores, + Utilities, + VarietyStores, + VeterinaryServices, + VideoAmusementGameSupplies, + VideoGameArcades, + VideoTapeRentalStores, + VocationalTradeSchools, + WatchJewelryRepair, + WeldingRepair, + WholesaleClubs, + WigAndToupeeStores, + WiresMoneyOrders, + WomensAccessoryAndSpecialtyShops, + WomensReadyToWearStores, + WreckingAndSalvageYards, +} diff --git a/ft-stripe/src/resources/issuing_transaction.rs b/ft-stripe/src/resources/issuing_transaction.rs new file mode 100644 index 0000000..1d0cbd0 --- /dev/null +++ b/ft-stripe/src/resources/issuing_transaction.rs @@ -0,0 +1,210 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::IssuingTransactionId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{ + BalanceTransaction, Currency, IssuingAuthorization, IssuingCard, IssuingCardholder, + IssuingTransactionType, MerchantData, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "IssuingTransaction". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransaction { + /// Unique identifier for the object. + pub id: IssuingTransactionId, + + /// The transaction amount, which will be reflected in your balance. + /// + /// This amount is in your currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + pub amount: i64, + + /// The `Authorization` object that led to this transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization: Option>, + + /// ID of the [balance transaction](https://stripe.com/docs/api/balance_transactions) associated with this transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// The card used to make this transaction. + pub card: Expandable, + + /// The cardholder to whom this transaction belongs. + #[serde(skip_serializing_if = "Option::is_none")] + pub cardholder: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// The amount that the merchant will receive, denominated in `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). + /// + /// It will be different from `amount` if the merchant is taking payment in a different currency. + pub merchant_amount: i64, + + /// The currency with which the merchant is taking payment. + pub merchant_currency: Currency, + + pub merchant_data: MerchantData, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// Additional purchase information that is optionally provided by the merchant. + #[serde(skip_serializing_if = "Option::is_none")] + pub purchase_details: Option, + + /// The nature of the transaction. + #[serde(rename = "type")] + pub type_: IssuingTransactionType, +} + +impl Object for IssuingTransaction { + type Id = IssuingTransactionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.transaction" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionPurchaseDetails { + /// Information about the flight that was purchased with this transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub flight: Option, + + /// Information about fuel that was purchased with this transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub fuel: Option, + + /// Information about lodging that was purchased with this transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub lodging: Option, + + /// The line items in the purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt: Option>, + + /// A merchant-specific order number. + #[serde(skip_serializing_if = "Option::is_none")] + pub reference: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionFlightData { + /// The time that the flight departed. + #[serde(skip_serializing_if = "Option::is_none")] + pub departure_at: Option, + + /// The name of the passenger. + #[serde(skip_serializing_if = "Option::is_none")] + pub passenger_name: Option, + + /// Whether the ticket is refundable. + #[serde(skip_serializing_if = "Option::is_none")] + pub refundable: Option, + + /// The legs of the trip. + #[serde(skip_serializing_if = "Option::is_none")] + pub segments: Option>, + + /// The travel agency that issued the ticket. + #[serde(skip_serializing_if = "Option::is_none")] + pub travel_agency: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionFlightDataLeg { + /// The flight's destination airport code. + #[serde(skip_serializing_if = "Option::is_none")] + pub arrival_airport_code: Option, + + /// The airline carrier code. + #[serde(skip_serializing_if = "Option::is_none")] + pub carrier: Option, + + /// The airport code that the flight departed from. + #[serde(skip_serializing_if = "Option::is_none")] + pub departure_airport_code: Option, + + /// The flight number. + #[serde(skip_serializing_if = "Option::is_none")] + pub flight_number: Option, + + /// The flight's service class. + #[serde(skip_serializing_if = "Option::is_none")] + pub service_class: Option, + + /// Whether a stopover is allowed on this flight. + #[serde(skip_serializing_if = "Option::is_none")] + pub stopover_allowed: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionFuelData { + /// The type of fuel that was purchased. + /// + /// One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. + #[serde(rename = "type")] + pub type_: String, + + /// The units for `volume`. + /// + /// One of `us_gallon` or `liter`. + pub unit: String, + + /// The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. + pub unit_cost_decimal: String, + + /// The volume of the fuel that was pumped, represented as a decimal string with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub volume_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionLodgingData { + /// The time of checking into the lodging. + #[serde(skip_serializing_if = "Option::is_none")] + pub check_in_at: Option, + + /// The number of nights stayed at the lodging. + #[serde(skip_serializing_if = "Option::is_none")] + pub nights: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransactionReceiptData { + /// The description of the item. + /// + /// The maximum length of this field is 26 characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The quantity of the item. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The total for this line item in cents. + #[serde(skip_serializing_if = "Option::is_none")] + pub total: Option, + + /// The unit cost of the item in cents. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_cost: Option, +} diff --git a/ft-stripe/src/resources/issuing_transaction_ext.rs b/ft-stripe/src/resources/issuing_transaction_ext.rs new file mode 100644 index 0000000..aa64fcb --- /dev/null +++ b/ft-stripe/src/resources/issuing_transaction_ext.rs @@ -0,0 +1,38 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `IssuingTransaction`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum IssuingTransactionType { + Capture, + CashWithdrawal, + Dispute, + DisputeLoss, + Refund, + RefundReversal, +} + +impl IssuingTransactionType { + pub fn as_str(self) -> &'static str { + match self { + IssuingTransactionType::Capture => "capture", + IssuingTransactionType::CashWithdrawal => "cash_withdrawal", + IssuingTransactionType::Dispute => "dispute", + IssuingTransactionType::DisputeLoss => "dispute_loss", + IssuingTransactionType::Refund => "refund", + IssuingTransactionType::RefundReversal => "refund_reversal", + } + } +} + +impl AsRef for IssuingTransactionType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for IssuingTransactionType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/item.rs b/ft-stripe/src/resources/item.rs new file mode 100644 index 0000000..f6bf253 --- /dev/null +++ b/ft-stripe/src/resources/item.rs @@ -0,0 +1,62 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::CheckoutSessionItemId; +use crate::params::Object; +use crate::resources::{Currency, Price, TaxRate}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "PaymentPagesCheckoutSessionLineItem". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CheckoutSessionItem { + /// Unique identifier for the object. + pub id: CheckoutSessionItemId, + + /// Total before any discounts or taxes is applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_subtotal: Option, + + /// Total after discounts and taxes. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_total: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + /// Defaults to product name. + pub description: String, + + pub price: Price, + + /// The quantity of products being purchased. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The taxes applied to the line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub taxes: Option>, +} + +impl Object for CheckoutSessionItem { + type Id = CheckoutSessionItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "item" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentPagesCheckoutSessionLineItemResourceLineItemTax { + /// Amount of tax for this line item. + pub amount: i64, + + pub rate: TaxRate, +} diff --git a/ft-stripe/src/resources/line_item.rs b/ft-stripe/src/resources/line_item.rs new file mode 100644 index 0000000..8ea34fc --- /dev/null +++ b/ft-stripe/src/resources/line_item.rs @@ -0,0 +1,138 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::InvoiceLineItemId; +use crate::params::{Expandable, Metadata, Object}; +use crate::resources::{Currency, Period, Plan, Price, TaxRate}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "InvoiceLineItem". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceLineItem { + /// Unique identifier for the object. + pub id: InvoiceLineItemId, + + /// The amount, in %s. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// If true, discounts will apply to this line item. + /// + /// Always false for prorations. + pub discountable: bool, + + /// The ID of the [invoice item](https://stripe.com/docs/api/invoiceitems) associated with this line item if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_item: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Note that for line items with `type=subscription` this will reflect the metadata of the subscription that caused the line item to be created. + pub metadata: Metadata, + + pub period: Option, + + /// The plan of the subscription, if the line item is a subscription or a proration. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// The price of the line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Whether this is a proration. + pub proration: bool, + + /// The quantity of the subscription, if the line item is a subscription or a proration. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The subscription that the invoice item pertains to, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, + + /// The subscription item that generated this invoice item. + /// + /// Left empty if the line item is not an explicit result of a subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_item: Option, + + /// The amount of tax calculated per tax rate for this line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_amounts: Option>, + + /// The tax rates which apply to the line item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, + + /// A string identifying the type of the source of this line item, either an `invoiceitem` or a `subscription`. + #[serde(rename = "type")] + pub type_: InvoiceLineItemType, +} + +impl Object for InvoiceLineItem { + type Id = InvoiceLineItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "line_item" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxAmount { + /// The amount, in %s, of the tax. + pub amount: i64, + + /// Whether this tax amount is inclusive or exclusive. + pub inclusive: bool, + + /// The tax rate that was applied to get this tax amount. + pub tax_rate: Expandable, +} + +/// An enum representing the possible values of an `InvoiceLineItem`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum InvoiceLineItemType { + #[serde(rename = "invoiceitem")] + InvoiceItem, + Subscription, +} + +impl InvoiceLineItemType { + pub fn as_str(self) -> &'static str { + match self { + InvoiceLineItemType::InvoiceItem => "invoiceitem", + InvoiceLineItemType::Subscription => "subscription", + } + } +} + +impl AsRef for InvoiceLineItemType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for InvoiceLineItemType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/line_item_ext.rs b/ft-stripe/src/resources/line_item_ext.rs new file mode 100644 index 0000000..1af7d7a --- /dev/null +++ b/ft-stripe/src/resources/line_item_ext.rs @@ -0,0 +1,45 @@ +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, InvoiceId}; +use crate::resources::{Currency, InvoiceLineItem}; +use serde::{Deserialize, Serialize}; + +impl InvoiceLineItem { + /// Creates an invoice line item. + /// + /// For more details see https://stripe.com/docs/api#invoice_line_item_object + pub fn create(client: &Client, params: CreateInvoiceLineItem<'_>) -> Response { + client.post_form("/invoiceitems", ¶ms) + } +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct CreateInvoiceLineItem<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub discountable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, +} + +impl CreateInvoiceLineItem<'_> { + pub fn new() -> Self { + CreateInvoiceLineItem { + amount: None, + currency: None, + customer: None, + description: None, + discountable: None, + invoice: None, + subscription: None, + } + } +} diff --git a/ft-stripe/src/resources/mandate.rs b/ft-stripe/src/resources/mandate.rs new file mode 100644 index 0000000..8d350ef --- /dev/null +++ b/ft-stripe/src/resources/mandate.rs @@ -0,0 +1,233 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::MandateId; +use crate::params::{Expand, Expandable, Object, Timestamp}; +use crate::resources::{Currency, PaymentMethod}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Mandate". +/// +/// For more details see [https://stripe.com/docs/api/mandates/object](https://stripe.com/docs/api/mandates/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Mandate { + /// Unique identifier for the object. + pub id: MandateId, + + pub customer_acceptance: CustomerAcceptance, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + #[serde(skip_serializing_if = "Option::is_none")] + pub multi_use: Option, + + /// ID of the payment method associated with this mandate. + pub payment_method: Expandable, + + pub payment_method_details: MandatePaymentMethodDetails, + + #[serde(skip_serializing_if = "Option::is_none")] + pub single_use: Option, + + /// The status of the mandate, which indicates whether it can be used to initiate a payment. + pub status: MandateStatus, + + /// The type of the mandate. + #[serde(rename = "type")] + pub type_: MandateType, +} + +impl Mandate { + /// Retrieves a Mandate object. + pub fn retrieve(client: &Client, id: &MandateId, expand: &[&str]) -> Response { + client.get_query(&format!("/mandates/{}", id), &Expand { expand }) + } +} + +impl Object for Mandate { + type Id = MandateId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "mandate" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CustomerAcceptance { + /// The time at which the customer accepted the Mandate. + #[serde(skip_serializing_if = "Option::is_none")] + pub accepted_at: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub offline: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub online: Option, + + /// The type of customer acceptance information included with the Mandate. + /// + /// One of `online` or `offline`. + #[serde(rename = "type")] + pub type_: CustomerAcceptanceType, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MandateMultiUse {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MandatePaymentMethodDetails { + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sepa_debit: Option, + + /// The type of the payment method associated with this mandate. + /// + /// An additional hash is included on `payment_method_details` with a name matching this value. + /// It contains mandate information specific to the payment method. + #[serde(rename = "type")] + pub type_: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CardMandatePaymentMethodDetails {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MandateAuBecsDebit { + /// The URL of the mandate. + /// + /// This URL generally contains sensitive information about the customer and should be shared with them exclusively. + pub url: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MandateSepaDebit { + /// The unique reference of the mandate. + pub reference: String, + + /// The URL of the mandate. + /// + /// This URL generally contains sensitive information about the customer and should be shared with them exclusively. + pub url: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct MandateSingleUse { + /// On a single use mandate, the amount of the payment. + pub amount: i64, + + /// On a single use mandate, the currency of the payment. + pub currency: Currency, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OfflineAcceptance {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OnlineAcceptance { + /// The IP address from which the Mandate was accepted by the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub ip_address: Option, + + /// The user agent of the browser from which the Mandate was accepted by the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, +} + +/// An enum representing the possible values of an `CustomerAcceptance`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CustomerAcceptanceType { + Offline, + Online, +} + +impl CustomerAcceptanceType { + pub fn as_str(self) -> &'static str { + match self { + CustomerAcceptanceType::Offline => "offline", + CustomerAcceptanceType::Online => "online", + } + } +} + +impl AsRef for CustomerAcceptanceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CustomerAcceptanceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Mandate`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum MandateStatus { + Active, + Inactive, + Pending, +} + +impl MandateStatus { + pub fn as_str(self) -> &'static str { + match self { + MandateStatus::Active => "active", + MandateStatus::Inactive => "inactive", + MandateStatus::Pending => "pending", + } + } +} + +impl AsRef for MandateStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for MandateStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Mandate`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum MandateType { + MultiUse, + SingleUse, +} + +impl MandateType { + pub fn as_str(self) -> &'static str { + match self { + MandateType::MultiUse => "multi_use", + MandateType::SingleUse => "single_use", + } + } +} + +impl AsRef for MandateType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for MandateType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/order.rs b/ft-stripe/src/resources/order.rs new file mode 100644 index 0000000..3642eaf --- /dev/null +++ b/ft-stripe/src/resources/order.rs @@ -0,0 +1,522 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CouponId, CustomerId, OrderId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Charge, Currency, Customer, OrderItem, OrderReturn, OrderStatusFilter, Shipping, ShippingParams, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Order". +/// +/// For more details see [https://stripe.com/docs/api/orders/object](https://stripe.com/docs/api/orders/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Order { + /// Unique identifier for the object. + pub id: OrderId, + + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. + pub amount: i64, + + /// The total amount that was returned to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_returned: Option, + + /// ID of the Connect Application that created the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option, + + /// A fee in cents that will be applied to the order and transferred to the application owner’s Stripe account. + /// + /// The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. + /// For more information, see the application fees documentation. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee: Option, + + /// The ID of the payment used to pay for the order. + /// + /// Present if the order status is `paid`, `fulfilled`, or `refunded`. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The customer used for the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// The email address of the customer placing the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// External coupon code to load for this order. + #[serde(skip_serializing_if = "Option::is_none")] + pub external_coupon_code: Option, + + /// List of items constituting the order. + /// + /// An order can have up to 25 items. + pub items: Vec, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// A list of returns that have taken place for this order. + #[serde(default)] + pub returns: List, + + /// The shipping method that is currently selected for this order, if any. + /// + /// If present, it is equal to one of the `id`s of shipping methods in the `shipping_methods` array. + /// At order creation time, if there are multiple shipping methods, Stripe will automatically selected the first method. + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_shipping_method: Option, + + /// The shipping address for the order. + /// + /// Present if the order is for goods to be shipped. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// A list of supported shipping methods for this order. + /// + /// The desired shipping method can be specified either by updating the order, or when paying it. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_methods: Option>, + + /// Current order status. + /// + /// One of `created`, `paid`, `canceled`, `fulfilled`, or `returned`. + /// More details in the [Orders Guide](https://stripe.com/docs/orders/guide#understanding-order-statuses). + pub status: OrderStatus, + + /// The timestamps at which the order status was updated. + #[serde(skip_serializing_if = "Option::is_none")] + pub status_transitions: Option, + + /// Time at which the object was last updated. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub updated: Option, + + /// The user's order ID if it is different from the Stripe order ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub upstream_id: Option, +} + +impl Order { + /// Returns a list of your orders. + /// + /// The orders are returned sorted by creation date, with the most recently created orders appearing first. + pub fn list(client: &Client, params: ListOrders<'_>) -> Response> { + client.get_query("/orders", ¶ms) + } + + /// Creates a new order object. + pub fn create(client: &Client, params: CreateOrder<'_>) -> Response { + client.post_form("/orders", ¶ms) + } + + /// Retrieves the details of an existing order. + /// + /// Supply the unique order ID from either an order creation request or the order list, and Stripe will return the corresponding order information. + pub fn retrieve(client: &Client, id: &OrderId, expand: &[&str]) -> Response { + client.get_query(&format!("/orders/{}", id), &Expand { expand }) + } + + /// Updates the specific order by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. + pub fn update(client: &Client, id: &OrderId, params: UpdateOrder<'_>) -> Response { + client.post_form(&format!("/orders/{}", id), ¶ms) + } +} + +impl Object for Order { + type Id = OrderId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "order" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ShippingMethod { + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the line item. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The estimated delivery date for the given shipping method. + /// + /// Can be either a specific date or a range. + #[serde(skip_serializing_if = "Option::is_none")] + pub delivery_estimate: Option, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + pub description: String, + + /// Unique identifier for the object. + pub id: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct DeliveryEstimate { + /// If `type` is `"exact"`, `date` will be the expected delivery date in the format YYYY-MM-DD. + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + /// If `type` is `"range"`, `earliest` will be be the earliest delivery date in the format YYYY-MM-DD. + #[serde(skip_serializing_if = "Option::is_none")] + pub earliest: Option, + + /// If `type` is `"range"`, `latest` will be the latest delivery date in the format YYYY-MM-DD. + #[serde(skip_serializing_if = "Option::is_none")] + pub latest: Option, + + /// The type of estimate. + /// + /// Must be either `"range"` or `"exact"`. + #[serde(rename = "type")] + pub type_: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct StatusTransitions { + /// The time that the order was canceled. + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled: Option, + + /// The time that the order was fulfilled. + #[serde(skip_serializing_if = "Option::is_none")] + pub fulfiled: Option, + + /// The time that the order was paid. + #[serde(skip_serializing_if = "Option::is_none")] + pub paid: Option, + + /// The time that the order was returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub returned: Option, +} + +/// The parameters for `Order::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateOrder<'a> { + /// A coupon code that represents a discount to be applied to this order. + /// + /// Must be one-time duration and in same currency as the order. + /// An order can have multiple coupons. + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The ID of an existing customer to use for this order. + /// + /// If provided, the customer email and shipping address will be used to create the order. + /// Subsequently, the customer will also be charged to pay the order. + /// If `email` or `shipping` are also provided, they will override the values retrieved from the customer object. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// The email address of the customer placing the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// List of items constituting the order. + /// + /// An order can have up to 25 items. + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Shipping address for the order. + /// + /// Required if any of the SKUs are for products that have `shippable` set to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, +} + +impl<'a> CreateOrder<'a> { + pub fn new(currency: Currency) -> Self { + CreateOrder { + coupon: Default::default(), + currency, + customer: Default::default(), + email: Default::default(), + expand: Default::default(), + items: Default::default(), + metadata: Default::default(), + shipping: Default::default(), + } + } +} + +/// The parameters for `Order::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListOrders<'a> { + /// Date this order was created. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return orders for the given customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Only return orders with the given IDs. + #[serde(skip_serializing_if = "Option::is_none")] + pub ids: Option>, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return orders that have the given status. + /// + /// One of `created`, `paid`, `fulfilled`, or `refunded`. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + /// Filter orders based on when they were paid, fulfilled, canceled, or returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub status_transitions: Option, + + /// Only return orders with the given upstream order IDs. + #[serde(skip_serializing_if = "Option::is_none")] + pub upstream_ids: Option>, +} + +impl<'a> ListOrders<'a> { + pub fn new() -> Self { + ListOrders { + created: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + ids: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + status: Default::default(), + status_transitions: Default::default(), + upstream_ids: Default::default(), + } + } +} + +/// The parameters for `Order::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateOrder<'a> { + /// A coupon code that represents a discount to be applied to this order. + /// + /// Must be one-time duration and in same currency as the order. + /// An order can have multiple coupons. + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The shipping method to select for fulfilling this order. + /// + /// If specified, must be one of the `id`s of a shipping method in the `shipping_methods` array. + /// If specified, will overwrite the existing selected shipping method, updating `items` as necessary. + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_shipping_method: Option<&'a str>, + + /// Tracking information once the order has been fulfilled. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// Current order status. + /// + /// One of `created`, `paid`, `canceled`, `fulfilled`, or `returned`. + /// More detail in the [Orders Guide](https://stripe.com/docs/orders/guide#understanding-order-statuses). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl<'a> UpdateOrder<'a> { + pub fn new() -> Self { + UpdateOrder { + coupon: Default::default(), + expand: Default::default(), + metadata: Default::default(), + selected_shipping_method: Default::default(), + shipping: Default::default(), + status: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ListOrdersStatusTransitions { + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fulfilled: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub paid: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub returned: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OrderItemParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +/// An enum representing the possible values of an `OrderItemParams`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum OrderItemParamsType { + Discount, + Shipping, + Sku, + Tax, +} + +impl OrderItemParamsType { + pub fn as_str(self) -> &'static str { + match self { + OrderItemParamsType::Discount => "discount", + OrderItemParamsType::Shipping => "shipping", + OrderItemParamsType::Sku => "sku", + OrderItemParamsType::Tax => "tax", + } + } +} + +impl AsRef for OrderItemParamsType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for OrderItemParamsType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `UpdateOrder`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum OrderStatus { + Canceled, + Created, + Fulfilled, + Paid, + Returned, +} + +impl OrderStatus { + pub fn as_str(self) -> &'static str { + match self { + OrderStatus::Canceled => "canceled", + OrderStatus::Created => "created", + OrderStatus::Fulfilled => "fulfilled", + OrderStatus::Paid => "paid", + OrderStatus::Returned => "returned", + } + } +} + +impl AsRef for OrderStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for OrderStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/order_ext.rs b/ft-stripe/src/resources/order_ext.rs new file mode 100644 index 0000000..f189621 --- /dev/null +++ b/ft-stripe/src/resources/order_ext.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `ListOrders`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum OrderStatusFilter { + Created, + Fulfilled, + Paid, + Refunded, +} + +impl OrderStatusFilter { + pub fn as_str(self) -> &'static str { + match self { + OrderStatusFilter::Created => "created", + OrderStatusFilter::Fulfilled => "fulfilled", + OrderStatusFilter::Paid => "paid", + OrderStatusFilter::Refunded => "refunded", + } + } +} + +impl AsRef for OrderStatusFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for OrderStatusFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/order_item.rs b/ft-stripe/src/resources/order_item.rs new file mode 100644 index 0000000..d65a4ee --- /dev/null +++ b/ft-stripe/src/resources/order_item.rs @@ -0,0 +1,50 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::{Expandable, Object}; +use crate::resources::{Currency, Sku}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "OrderItem". +/// +/// For more details see [https://stripe.com/docs/api/order_items/object](https://stripe.com/docs/api/order_items/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OrderItem { + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the line item. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Description of the line item, meant to be displayable to the user (e.g., `"Express shipping"`). + pub description: String, + + /// The ID of the associated object for this line item. + /// + /// Expandable if not null (e.g., expandable to a SKU). + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option>, + + /// A positive integer representing the number of instances of `parent` that are included in this order item. + /// + /// Applicable/present only if `type` is `sku`. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The type of line item. + /// + /// One of `sku`, `tax`, `shipping`, or `discount`. + #[serde(rename = "type")] + pub type_: String, +} + +impl Object for OrderItem { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "order_item" + } +} diff --git a/ft-stripe/src/resources/order_return.rs b/ft-stripe/src/resources/order_return.rs new file mode 100644 index 0000000..e3a266d --- /dev/null +++ b/ft-stripe/src/resources/order_return.rs @@ -0,0 +1,120 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{OrderId, OrderReturnId}; +use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; +use crate::resources::{Currency, Order, OrderItem, Refund}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "OrderReturn". +/// +/// For more details see [https://stripe.com/docs/api/order_returns/object](https://stripe.com/docs/api/order_returns/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OrderReturn { + /// Unique identifier for the object. + pub id: OrderReturnId, + + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the returned line item. + pub amount: i64, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The items included in this order return. + pub items: Vec, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// The order that this return includes items from. + #[serde(skip_serializing_if = "Option::is_none")] + pub order: Option>, + + /// The ID of the refund issued for this return. + #[serde(skip_serializing_if = "Option::is_none")] + pub refund: Option>, +} + +impl OrderReturn { + /// Returns a list of your order returns. + /// + /// The returns are returned sorted by creation date, with the most recently created return appearing first. + pub fn list(client: &Client, params: ListOrderReturns<'_>) -> Response> { + client.get_query("/order_returns", ¶ms) + } + + /// Retrieves the details of an existing order return. + /// + /// Supply the unique order ID from either an order return creation request or the order return list, and Stripe will return the corresponding order information. + pub fn retrieve(client: &Client, id: &OrderReturnId, expand: &[&str]) -> Response { + client.get_query(&format!("/order_returns/{}", id), &Expand { expand }) + } +} + +impl Object for OrderReturn { + type Id = OrderReturnId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "order_return" + } +} + +/// The parameters for `OrderReturn::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListOrderReturns<'a> { + /// Date this return was created. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// The order to retrieve returns for. + #[serde(skip_serializing_if = "Option::is_none")] + pub order: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListOrderReturns<'a> { + pub fn new() -> Self { + ListOrderReturns { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + order: Default::default(), + starting_after: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/payment_intent.rs b/ft-stripe/src/resources/payment_intent.rs new file mode 100644 index 0000000..eccb2bb --- /dev/null +++ b/ft-stripe/src/resources/payment_intent.rs @@ -0,0 +1,601 @@ +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, PaymentIntentId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Account, Application, Charge, Currency, Customer, Invoice, PaymentIntentOffSession, + PaymentMethod, PaymentSource, Review, Shipping, TransferDataParams, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "PaymentIntent". +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/object](https://stripe.com/docs/api/payment_intents/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentIntent { + /// Unique identifier for the object. + pub id: PaymentIntentId, + + /// Amount intended to be collected by this PaymentIntent. + pub amount: i64, + + /// Amount that can be captured from this PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_capturable: Option, + + /// Amount that was collected by this PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_received: Option, + + /// ID of the Connect application that created the PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option>, + + /// The amount of the application fee (if any) for the resulting payment. + /// + /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + + /// Populated when `status` is `canceled`, this is the time at which the PaymentIntent was canceled. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled_at: Option, + + /// Reason for cancellation of this PaymentIntent, either user-provided (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or generated by Stripe internally (`failed_invoice`, `void_invoice`, or `automatic`). + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_reason: Option, + + /// Capture method of this PaymentIntent, one of `automatic` or `manual`. + pub capture_method: PaymentIntentCaptureMethod, + + /// Charges that were created by this PaymentIntent, if any. + #[serde(default)] + pub charges: List, + + /// The client secret of this PaymentIntent. + /// + /// Used for client-side retrieval using a publishable key. + /// Please refer to our [automatic confirmation quickstart guide](https://stripe.com/docs/payments/payment-intents/quickstart#automatic-confirmation-flow) to learn about how `client_secret` should be handled. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + + /// Confirmation method of this PaymentIntent, one of `manual` or `automatic`. + pub confirmation_method: PaymentIntentConfirmationMethod, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// ID of the Customer this PaymentIntent is for if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// ID of the invoice that created this PaymentIntent, if it exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice: Option>, + + /// The payment error encountered in the previous PaymentIntent confirmation. + #[serde(skip_serializing_if = "Option::is_none")] + pub last_payment_error: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// For more information, see the [documentation](https://stripe.com/docs/payments/payment-intents/creating-payment-intents#storing-information-in-metadata). + #[serde(default)] + pub metadata: Metadata, + + /// If present, this property tells you what actions you need to take in order for your customer to fulfill a payment using the provided source. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_action: Option, + + /// The account (if any) for which the funds of the PaymentIntent are intended. + /// + /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option>, + + /// ID of the payment method used in this PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option>, + + /// The list of payment method types (e.g. + /// + /// card) that this PaymentIntent is allowed to use. + pub payment_method_types: Vec, + + /// Email address that the receipt for the resulting payment will be sent to. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option, + + /// ID of the review associated with this PaymentIntent, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub review: Option>, + + /// Shipping information for this PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + + /// ID of the source used in this PaymentIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option>, + + /// Used in payment flows that collect payment details and charge later when the customer is not available to complete additional required steps for the payment. + /// + /// Setting this parameter indicates that this payment attempt is happening while the customer is not in your checkout flow. + /// Use `recurring` for payments made on a recurring basis (for example, subscriptions) and `one_off` for all other off-session payments. + pub off_session: Option, + + /// Extra information about a PaymentIntent. + /// + /// This will appear on your customer's statement when this PaymentIntent succeeds in creating a charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// Status of this PaymentIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, `canceled`, or `succeeded`. + /// + /// Read more about each PaymentIntent [status](https://stripe.com/docs/payments/payment-intents/status). + pub status: PaymentIntentStatus, + + /// The data with which to automatically create a Transfer when the payment is finalized. + /// + /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_data: Option, + + /// A string that identifies the resulting payment as part of a group. + /// + /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option, +} + +impl PaymentIntent { + /// Creates a new payment_intent. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create). + pub fn create(client: &Client, params: CreatePaymentIntent<'_>) -> Response { + client.post_form("/payment_intents", params) + } + + /// Retrieves the details of a payment_intent. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/retrieve](https://stripe.com/docs/api/payment_intents/retrieve). + pub fn retrieve(client: &Client, payment_intent_id: &str) -> Response { + client.get(&format!("/payment_intents/{}", payment_intent_id)) + } + + /// Updates a payment_intent's properties. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update). + pub fn update( + client: &Client, + payment_intent_id: &str, + params: PaymentIntentUpdateParams<'_>, + ) -> Response { + client.post_form(&format!("/payment_intents/{}", payment_intent_id), params) + } + + /// Confirm that customer intends to pay with current or provided source. Upon confirmation, the PaymentIntent will attempt to initiate a payment. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm). + pub fn confirm( + client: &Client, + payment_intent_id: &str, + params: PaymentIntentConfirmParams<'_>, + ) -> Response { + client.post_form(&format!("/payment_intents/{}/confirm", payment_intent_id), params) + } + + /// Capture the funds of an existing uncaptured PaymentIntent where required_action="requires_capture". + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture). + pub fn capture( + client: &Client, + payment_intent_id: &str, + params: CapturePaymentIntent, + ) -> Response { + client.post_form(&format!("/payment_intents/{}/capture", payment_intent_id), params) + } + + /// A PaymentIntent object can be canceled when it is in one of these statuses: requires_source, requires_capture, requires_confirmation, requires_source_action. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel). + pub fn cancel( + client: &Client, + payment_intent_id: &str, + params: CancelPaymentIntent, + ) -> Response { + client.post_form(&format!("/payment_intents/{}/cancel", payment_intent_id), params) + } + + /// List all payment_intents. + /// + /// For more details see [https://stripe.com/docs/api/payment_intents/list](https://stripe.com/docs/api/payment_intents/list). + pub fn list(client: &Client, params: ListPaymentIntents) -> Response> { + client.get_query("/payment_intents", ¶ms) + } +} + +impl Object for PaymentIntent { + type Id = PaymentIntentId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "payment_intent" + } +} + +/// The resource representing a Stripe PaymentError object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentError { + #[serde(rename = "type")] + pub payment_error_type: PaymentErrorType, + pub charge: Option, + pub code: Option, + pub decline_code: Option, + pub doc_url: Option, + pub message: Option, + pub param: Option, + pub source: Option>, +} + +/// The resource representing a Stripe PaymentErrorType object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type). +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] +pub enum PaymentErrorType { + #[serde(rename = "api_error")] + Api, + #[serde(rename = "api_connection_error")] + Connection, + #[serde(rename = "authentication_error")] + Authentication, + #[serde(rename = "card_error")] + Card, + #[serde(rename = "idempotency_error")] + Idempotency, + #[serde(rename = "invalid_request_error")] + InvalidRequest, + #[serde(rename = "rate_limit_error")] + RateLimit, + + /// A variant not yet supported by the library. + /// It is an error to send `Other` as part of a request. + #[serde(other, skip_serializing)] + Other, +} + +// TODO: This might be moved to `PaymentSourceType` if we determine +// that all of the variants are _always_ the same. +// +// In that case this can be replaced with a deprecated type alias. +/// Represents the way a `PaymentIntent` needs to be fulfilled. +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentMethodType { + /// This `PaymentIntent` needs to be fulfilled through credit card payment. + Card, + /// This `PaymentIntent` needs to be fulfilled through an + /// [iDeal](https://stripe.com/docs/payments/ideal) payment. + Ideal, + /// This `PaymentIntent` needs to be fulfilled through a + /// [Sepa Direct Debit](https://stripe.com/docs/payments/sepa-debit) payment. + SepaDebit, +} + +/// The resource representing a Stripe CaptureMethod object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method). +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CaptureMethod { + Automatic, + Manual, + + /// A variant not yet supported by the library. + /// It is an error to send `Other` as part of a request. + #[serde(other, skip_serializing)] + Other, +} +/// The resource representing a Stripe ConfirmationMethod object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method). +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ConfirmationMethod { + Secret, + Publishable, + + /// A variant not yet supported by the library. + /// It is an error to send `Other` as part of a request. + #[serde(other, skip_serializing)] + Other, +} + +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentNextActionType { + RedirectToUrl, + UseStripeSdk, + + /// A variant not yet supported by the library. + /// It is an error to send `Other` as part of a request. + #[serde(other, skip_serializing)] + Other, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentIntentNextAction { + /// Type of the next action to perform, one of `redirect_to_url` or `use_stripe_sdk`. + #[serde(rename = "type")] + pub type_: PaymentIntentNextActionType, + + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_to_url: Option, + + /// When confirming a PaymentIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. + /// + /// The shape of the contents is subject to change and is only intended to be used by Stripe.js. + #[serde(skip_serializing_if = "Option::is_none")] + pub use_stripe_sdk: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentIntentNextActionRedirectToUrl { + /// If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. + #[serde(skip_serializing_if = "Option::is_none")] + pub return_url: Option, + + /// The URL you must redirect your customer to in order to authenticate the payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferData { + /// The account (if any) the payment will be attributed to for tax + /// reporting, and where funds from the payment will be transferred to upon + /// payment success. + pub destination: Expandable, +} + +/// The set of parameters that can be used when creating a payment_intent object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create) +#[derive(Clone, Debug, Default, Serialize)] +pub struct CreatePaymentIntent<'a> { + /// The list of payment types (e.g. card) that this PaymentIntent is allowed to use. + pub payment_method_types: Vec, + pub amount: u64, + pub currency: Currency, + pub payment_method: Option<&'a str>, + pub confirmation_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub capture_method: Option, + + /// Attempt to confirm this PaymentIntent on source attachment. + #[serde(skip_serializing_if = "Option::is_none")] + pub confirm: Option, // TODO: Is this the correct type? + + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub return_url: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub save_source_to_customer: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_data: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> CreatePaymentIntent<'a> { + pub fn new(amount: u64, currency: Currency) -> Self { + CreatePaymentIntent { + payment_method_types: Default::default(), + amount, + currency, + payment_method: Default::default(), + confirmation_method: Default::default(), + application_fee_amount: Default::default(), + capture_method: Default::default(), + confirm: Default::default(), + customer: Default::default(), + description: Default::default(), + metadata: Default::default(), + on_behalf_of: Default::default(), + receipt_email: Default::default(), + return_url: Default::default(), + save_source_to_customer: Default::default(), + shipping: Default::default(), + source: Default::default(), + statement_descriptor: Default::default(), + transfer_data: Default::default(), + transfer_group: Default::default(), + } + } +} + +/// The set of parameters that can be used when updating a payment_intent object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update) +#[derive(Clone, Debug, Default, Serialize)] +pub struct PaymentIntentUpdateParams<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub save_source_to_customer: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +/// The set of parameters that can be used when confirming a payment_intent object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm) +#[derive(Clone, Debug, Default, Serialize)] +pub struct PaymentIntentConfirmParams<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_email: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub return_url: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub save_source_to_customer: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option<&'a str>, +} + +/// The set of parameters that can be used when capturing a payment_intent object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture) +#[derive(Clone, Debug, Default, Serialize)] +pub struct CapturePaymentIntent { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_to_capture: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_amount: Option, +} + +/// The set of parameters that can be used when canceling a payment_intent object. +/// +/// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel) +#[derive(Clone, Debug, Default, Serialize)] +pub struct CancelPaymentIntent { + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_reason: Option, +} + +/// The parameters for `PaymentIntent::list`. +#[derive(Clone, Debug, Serialize)] +pub struct ListPaymentIntents<'a> { + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return PaymentIntents for the customer specified by this customer ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option<&'a PaymentIntentId>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option<&'a PaymentIntentId>, +} + +/// An enum representing the possible values of an `PaymentIntent`'s `cancellation_reason` field. +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentCancellationReason { + Abandoned, + Automatic, + Duplicate, + FailedInvoice, + Fraudulent, + RequestedByCustomer, + VoidInvoice, +} + +/// An enum representing the possible values of an `PaymentIntent`'s `capture_method` field. +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentCaptureMethod { + Automatic, + Manual, +} + +/// An enum representing the possible values of an `PaymentIntent`'s `confirmation_method` field. +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentConfirmationMethod { + Automatic, + Manual, +} + +/// An enum representing the possible values of an `PaymentIntent`'s `status` field. +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentIntentStatus { + Canceled, + Processing, + RequiresAction, + RequiresCapture, + RequiresConfirmation, + RequiresPaymentMethod, + RequiresSource, + Succeeded, +} diff --git a/ft-stripe/src/resources/payment_method.rs b/ft-stripe/src/resources/payment_method.rs new file mode 100644 index 0000000..96833d8 --- /dev/null +++ b/ft-stripe/src/resources/payment_method.rs @@ -0,0 +1,948 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, PaymentMethodId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, Timestamp}; +use crate::resources::{Address, BillingDetails, Customer, PaymentMethodDetails}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "PaymentMethod". +/// +/// For more details see [https://stripe.com/docs/api/payment_methods/object](https://stripe.com/docs/api/payment_methods/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethod { + /// Unique identifier for the object. + pub id: PaymentMethodId, + + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit: Option, + + pub billing_details: BillingDetails, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card_present: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// The ID of the Customer to which this PaymentMethod is saved. + /// + /// This will not be set when the PaymentMethod has not been saved to a Customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fpx: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ideal: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sepa_debit: Option, + + /// The type of the PaymentMethod. + /// + /// An additional hash is included on the PaymentMethod with a name matching this value. + /// It contains additional information specific to the PaymentMethod type. + #[serde(rename = "type")] + pub type_: PaymentMethodType, +} + +impl PaymentMethod { + /// Returns a list of PaymentMethods for a given Customer. + pub fn list(client: &Client, params: ListPaymentMethods<'_>) -> Response> { + client.get_query("/payment_methods", ¶ms) + } + + /// Creates a PaymentMethod object. + /// + /// Read the [Stripe.js reference](https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. + pub fn create(client: &Client, params: CreatePaymentMethod<'_>) -> Response { + client.post_form("/payment_methods", ¶ms) + } + + /// Retrieves a PaymentMethod object. + pub fn retrieve( + client: &Client, + id: &PaymentMethodId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/payment_methods/{}", id), &Expand { expand }) + } + + /// Updates a PaymentMethod object. + /// + /// A PaymentMethod must be attached a customer to be updated. + pub fn update( + client: &Client, + id: &PaymentMethodId, + params: UpdatePaymentMethod<'_>, + ) -> Response { + client.post_form(&format!("/payment_methods/{}", id), ¶ms) + } +} + +impl Object for PaymentMethod { + type Id = PaymentMethodId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "payment_method" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodAuBecsDebit { + /// Six-digit number identifying bank and branch associated with this bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub bsb_number: Option, + + /// Uniquely identifies this particular bank account. + /// + /// You can use this attribute to check whether two bank accounts are the same. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// Last four digits of the bank account number. + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CardDetails { + /// Card brand. + /// + /// Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, `unionpay`, `visa`, or `unknown`. + pub brand: String, + + /// Checks on Card address and CVC if provided. + #[serde(skip_serializing_if = "Option::is_none")] + pub checks: Option, + + /// Two-letter ISO code representing the country of the card. + /// + /// You could use this attribute to get a sense of the international breakdown of cards you've collected. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Two-digit number representing the card's expiration month. + pub exp_month: i64, + + /// Four-digit number representing the card's expiration year. + pub exp_year: i64, + + /// Uniquely identifies this particular card number. + /// + /// You can use this attribute to check whether two customers who’ve signed up with you are using the same card number,for example. + /// For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// Card funding type. + /// + /// Can be `credit`, `debit`, `prepaid`, or `unknown`. + pub funding: String, + + /// Details of the original PaymentMethod that created this object. + #[serde(skip_serializing_if = "Option::is_none")] + pub generated_from: Option, + + /// The last four digits of the card. + pub last4: String, + + /// Contains details on how this Card maybe be used for 3D Secure authentication. + #[serde(skip_serializing_if = "Option::is_none")] + pub three_d_secure_usage: Option, + + /// If this Card is part of a card wallet, this contains the details of the card wallet. + #[serde(skip_serializing_if = "Option::is_none")] + pub wallet: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodCardChecks { + /// If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line1_check: Option, + + /// If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub address_postal_code_check: Option, + + /// If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc_check: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodCardGeneratedCard { + /// The charge that created this object. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option, + + /// Transaction-specific details of the payment method used in the payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_details: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CardPresent {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletDetails { + #[serde(skip_serializing_if = "Option::is_none")] + pub amex_express_checkout: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub apple_pay: Option, + + /// (For tokenized numbers only.) The last four digits of the device account number. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub google_pay: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub masterpass: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub samsung_pay: Option, + + /// The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, or `visa_checkout`. + /// + /// An additional hash is included on the Wallet subhash with a name matching this value. + /// It contains additional information specific to the card wallet type. + #[serde(rename = "type")] + pub type_: WalletDetailsType, + + #[serde(skip_serializing_if = "Option::is_none")] + pub visa_checkout: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletAmexExpressCheckout {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletApplePay {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletGooglePay {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletMasterpass { + /// Owner's verified billing address. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_address: Option
, + + /// Owner's verified email. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// Owner's verified full name. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// Owner's verified shipping address. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_address: Option
, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletSamsungPay {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WalletVisaCheckout { + /// Owner's verified billing address. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_address: Option
, + + /// Owner's verified email. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// Owner's verified full name. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// Owner's verified shipping address. + /// + /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_address: Option
, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodFpx { + /// The customer's bank, if provided. + /// + /// Can be one of `affin_bank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, or `pb_enterprise`. + pub bank: PaymentMethodFpxBank, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodIdeal { + /// The customer's bank, if provided. + /// + /// Can be one of `abn_amro`, `asn_bank`, `bunq`, `handelsbanken`, `ing`, `knab`, `moneyou`, `rabobank`, `regiobank`, `sns_bank`, `triodos_bank`, or `van_lanschot`. + #[serde(skip_serializing_if = "Option::is_none")] + pub bank: Option, + + /// The Bank Identifier Code of the customer's bank, if the bank was provided. + #[serde(skip_serializing_if = "Option::is_none")] + pub bic: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodSepaDebit { + /// Bank code of bank associated with the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_code: Option, + + /// Branch code of bank associated with the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub branch_code: Option, + + /// Two-letter ISO code representing the country the bank account is located in. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Uniquely identifies this particular bank account. + /// + /// You can use this attribute to check whether two bank accounts are the same. + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + /// Last four characters of the IBAN. + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ThreeDSecureUsage { + /// Whether 3D Secure is supported on this card. + pub supported: bool, +} + +/// The parameters for `PaymentMethod::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreatePaymentMethod<'a> { + /// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit: Option, + + /// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_details: Option, + + /// The `Customer` to whom the original PaymentMethod is attached. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. + #[serde(skip_serializing_if = "Option::is_none")] + pub fpx: Option, + + /// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. + #[serde(skip_serializing_if = "Option::is_none")] + pub ideal: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The PaymentMethod to share. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub sepa_debit: Option, + + /// The type of the PaymentMethod. + /// + /// An additional hash is included on the PaymentMethod with a name matching this value. + /// It contains additional information specific to the PaymentMethod type. + /// Required unless `payment_method` is specified (see the [Cloning PaymentMethods](https://stripe.com/docs/payments/payment-methods/connect#cloning-payment-methods) guide). + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +impl<'a> CreatePaymentMethod<'a> { + pub fn new() -> Self { + CreatePaymentMethod { + au_becs_debit: Default::default(), + billing_details: Default::default(), + customer: Default::default(), + expand: Default::default(), + fpx: Default::default(), + ideal: Default::default(), + metadata: Default::default(), + payment_method: Default::default(), + sepa_debit: Default::default(), + type_: Default::default(), + } + } +} + +/// The parameters for `PaymentMethod::list`. +#[derive(Clone, Debug, Serialize)] +pub struct ListPaymentMethods<'a> { + /// The ID of the customer whose PaymentMethods will be retrieved. + pub customer: CustomerId, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// A required filter on the list, based on the object `type` field. + #[serde(rename = "type")] + pub type_: PaymentMethodTypeFilter, +} + +impl<'a> ListPaymentMethods<'a> { + pub fn new(customer: CustomerId, type_: PaymentMethodTypeFilter) -> Self { + ListPaymentMethods { + customer, + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + type_, + } + } +} + +/// The parameters for `PaymentMethod::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdatePaymentMethod<'a> { + /// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit: Option, + + /// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_details: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. + #[serde(skip_serializing_if = "Option::is_none")] + pub sepa_debit: Option, +} + +impl<'a> UpdatePaymentMethod<'a> { + pub fn new() -> Self { + UpdatePaymentMethod { + au_becs_debit: Default::default(), + billing_details: Default::default(), + expand: Default::default(), + metadata: Default::default(), + sepa_debit: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePaymentMethodAuBecsDebit { + pub account_number: String, + + pub bsb_number: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePaymentMethodFpx { + pub bank: CreatePaymentMethodFpxBank, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePaymentMethodIdeal { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePaymentMethodSepaDebit { + pub iban: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdatePaymentMethodAuBecsDebit {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdatePaymentMethodSepaDebit {} + +/// An enum representing the possible values of an `CreatePaymentMethodFpx`'s `bank` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePaymentMethodFpxBank { + AffinBank, + AllianceBank, + Ambank, + BankIslam, + BankMuamalat, + BankRakyat, + Bsn, + Cimb, + DeutscheBank, + HongLeongBank, + Hsbc, + Kfh, + Maybank2e, + Maybank2u, + Ocbc, + PbEnterprise, + PublicBank, + Rhb, + StandardChartered, + Uob, +} + +impl CreatePaymentMethodFpxBank { + pub fn as_str(self) -> &'static str { + match self { + CreatePaymentMethodFpxBank::AffinBank => "affin_bank", + CreatePaymentMethodFpxBank::AllianceBank => "alliance_bank", + CreatePaymentMethodFpxBank::Ambank => "ambank", + CreatePaymentMethodFpxBank::BankIslam => "bank_islam", + CreatePaymentMethodFpxBank::BankMuamalat => "bank_muamalat", + CreatePaymentMethodFpxBank::BankRakyat => "bank_rakyat", + CreatePaymentMethodFpxBank::Bsn => "bsn", + CreatePaymentMethodFpxBank::Cimb => "cimb", + CreatePaymentMethodFpxBank::DeutscheBank => "deutsche_bank", + CreatePaymentMethodFpxBank::HongLeongBank => "hong_leong_bank", + CreatePaymentMethodFpxBank::Hsbc => "hsbc", + CreatePaymentMethodFpxBank::Kfh => "kfh", + CreatePaymentMethodFpxBank::Maybank2e => "maybank2e", + CreatePaymentMethodFpxBank::Maybank2u => "maybank2u", + CreatePaymentMethodFpxBank::Ocbc => "ocbc", + CreatePaymentMethodFpxBank::PbEnterprise => "pb_enterprise", + CreatePaymentMethodFpxBank::PublicBank => "public_bank", + CreatePaymentMethodFpxBank::Rhb => "rhb", + CreatePaymentMethodFpxBank::StandardChartered => "standard_chartered", + CreatePaymentMethodFpxBank::Uob => "uob", + } + } +} + +impl AsRef for CreatePaymentMethodFpxBank { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePaymentMethodFpxBank { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreatePaymentMethodIdeal`'s `bank` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePaymentMethodIdealBank { + AbnAmro, + AsnBank, + Bunq, + Handelsbanken, + Ing, + Knab, + Moneyou, + Rabobank, + Regiobank, + SnsBank, + TriodosBank, + VanLanschot, +} + +impl CreatePaymentMethodIdealBank { + pub fn as_str(self) -> &'static str { + match self { + CreatePaymentMethodIdealBank::AbnAmro => "abn_amro", + CreatePaymentMethodIdealBank::AsnBank => "asn_bank", + CreatePaymentMethodIdealBank::Bunq => "bunq", + CreatePaymentMethodIdealBank::Handelsbanken => "handelsbanken", + CreatePaymentMethodIdealBank::Ing => "ing", + CreatePaymentMethodIdealBank::Knab => "knab", + CreatePaymentMethodIdealBank::Moneyou => "moneyou", + CreatePaymentMethodIdealBank::Rabobank => "rabobank", + CreatePaymentMethodIdealBank::Regiobank => "regiobank", + CreatePaymentMethodIdealBank::SnsBank => "sns_bank", + CreatePaymentMethodIdealBank::TriodosBank => "triodos_bank", + CreatePaymentMethodIdealBank::VanLanschot => "van_lanschot", + } + } +} + +impl AsRef for CreatePaymentMethodIdealBank { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePaymentMethodIdealBank { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `PaymentMethodFpx`'s `bank` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodFpxBank { + AffinBank, + AllianceBank, + Ambank, + BankIslam, + BankMuamalat, + BankRakyat, + Bsn, + Cimb, + DeutscheBank, + HongLeongBank, + Hsbc, + Kfh, + Maybank2e, + Maybank2u, + Ocbc, + PbEnterprise, + PublicBank, + Rhb, + StandardChartered, + Uob, +} + +impl PaymentMethodFpxBank { + pub fn as_str(self) -> &'static str { + match self { + PaymentMethodFpxBank::AffinBank => "affin_bank", + PaymentMethodFpxBank::AllianceBank => "alliance_bank", + PaymentMethodFpxBank::Ambank => "ambank", + PaymentMethodFpxBank::BankIslam => "bank_islam", + PaymentMethodFpxBank::BankMuamalat => "bank_muamalat", + PaymentMethodFpxBank::BankRakyat => "bank_rakyat", + PaymentMethodFpxBank::Bsn => "bsn", + PaymentMethodFpxBank::Cimb => "cimb", + PaymentMethodFpxBank::DeutscheBank => "deutsche_bank", + PaymentMethodFpxBank::HongLeongBank => "hong_leong_bank", + PaymentMethodFpxBank::Hsbc => "hsbc", + PaymentMethodFpxBank::Kfh => "kfh", + PaymentMethodFpxBank::Maybank2e => "maybank2e", + PaymentMethodFpxBank::Maybank2u => "maybank2u", + PaymentMethodFpxBank::Ocbc => "ocbc", + PaymentMethodFpxBank::PbEnterprise => "pb_enterprise", + PaymentMethodFpxBank::PublicBank => "public_bank", + PaymentMethodFpxBank::Rhb => "rhb", + PaymentMethodFpxBank::StandardChartered => "standard_chartered", + PaymentMethodFpxBank::Uob => "uob", + } + } +} + +impl AsRef for PaymentMethodFpxBank { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PaymentMethodFpxBank { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `PaymentMethodIdeal`'s `bank` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodIdealBank { + AbnAmro, + AsnBank, + Bunq, + Handelsbanken, + Ing, + Knab, + Moneyou, + Rabobank, + Regiobank, + SnsBank, + TriodosBank, + VanLanschot, +} + +impl PaymentMethodIdealBank { + pub fn as_str(self) -> &'static str { + match self { + PaymentMethodIdealBank::AbnAmro => "abn_amro", + PaymentMethodIdealBank::AsnBank => "asn_bank", + PaymentMethodIdealBank::Bunq => "bunq", + PaymentMethodIdealBank::Handelsbanken => "handelsbanken", + PaymentMethodIdealBank::Ing => "ing", + PaymentMethodIdealBank::Knab => "knab", + PaymentMethodIdealBank::Moneyou => "moneyou", + PaymentMethodIdealBank::Rabobank => "rabobank", + PaymentMethodIdealBank::Regiobank => "regiobank", + PaymentMethodIdealBank::SnsBank => "sns_bank", + PaymentMethodIdealBank::TriodosBank => "triodos_bank", + PaymentMethodIdealBank::VanLanschot => "van_lanschot", + } + } +} + +impl AsRef for PaymentMethodIdealBank { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PaymentMethodIdealBank { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `PaymentMethodIdeal`'s `bic` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodIdealBic { + #[serde(rename = "ABNANL2A")] + Abnanl2a, + #[serde(rename = "ASNBNL21")] + Asnbnl21, + #[serde(rename = "BUNQNL2A")] + Bunqnl2a, + #[serde(rename = "FVLBNL22")] + Fvlbnl22, + #[serde(rename = "HANDNL2A")] + Handnl2a, + #[serde(rename = "INGBNL2A")] + Ingbnl2a, + #[serde(rename = "KNABNL2H")] + Knabnl2h, + #[serde(rename = "MOYONL21")] + Moyonl21, + #[serde(rename = "RABONL2U")] + Rabonl2u, + #[serde(rename = "RBRBNL21")] + Rbrbnl21, + #[serde(rename = "SNSBNL2A")] + Snsbnl2a, + #[serde(rename = "TRIONL2U")] + Trionl2u, +} + +impl PaymentMethodIdealBic { + pub fn as_str(self) -> &'static str { + match self { + PaymentMethodIdealBic::Abnanl2a => "ABNANL2A", + PaymentMethodIdealBic::Asnbnl21 => "ASNBNL21", + PaymentMethodIdealBic::Bunqnl2a => "BUNQNL2A", + PaymentMethodIdealBic::Fvlbnl22 => "FVLBNL22", + PaymentMethodIdealBic::Handnl2a => "HANDNL2A", + PaymentMethodIdealBic::Ingbnl2a => "INGBNL2A", + PaymentMethodIdealBic::Knabnl2h => "KNABNL2H", + PaymentMethodIdealBic::Moyonl21 => "MOYONL21", + PaymentMethodIdealBic::Rabonl2u => "RABONL2U", + PaymentMethodIdealBic::Rbrbnl21 => "RBRBNL21", + PaymentMethodIdealBic::Snsbnl2a => "SNSBNL2A", + PaymentMethodIdealBic::Trionl2u => "TRIONL2U", + } + } +} + +impl AsRef for PaymentMethodIdealBic { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PaymentMethodIdealBic { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `PaymentMethod`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodType { + AuBecsDebit, + Card, + Fpx, + Ideal, + SepaDebit, +} + +impl PaymentMethodType { + pub fn as_str(self) -> &'static str { + match self { + PaymentMethodType::AuBecsDebit => "au_becs_debit", + PaymentMethodType::Card => "card", + PaymentMethodType::Fpx => "fpx", + PaymentMethodType::Ideal => "ideal", + PaymentMethodType::SepaDebit => "sepa_debit", + } + } +} + +impl AsRef for PaymentMethodType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PaymentMethodType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListPaymentMethods`'s `type_` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodTypeFilter { + AuBecsDebit, + Card, + CardPresent, + Fpx, + Ideal, + SepaDebit, +} + +impl PaymentMethodTypeFilter { + pub fn as_str(self) -> &'static str { + match self { + PaymentMethodTypeFilter::AuBecsDebit => "au_becs_debit", + PaymentMethodTypeFilter::Card => "card", + PaymentMethodTypeFilter::CardPresent => "card_present", + PaymentMethodTypeFilter::Fpx => "fpx", + PaymentMethodTypeFilter::Ideal => "ideal", + PaymentMethodTypeFilter::SepaDebit => "sepa_debit", + } + } +} + +impl AsRef for PaymentMethodTypeFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PaymentMethodTypeFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `WalletDetails`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum WalletDetailsType { + AmexExpressCheckout, + ApplePay, + GooglePay, + Masterpass, + SamsungPay, + VisaCheckout, +} + +impl WalletDetailsType { + pub fn as_str(self) -> &'static str { + match self { + WalletDetailsType::AmexExpressCheckout => "amex_express_checkout", + WalletDetailsType::ApplePay => "apple_pay", + WalletDetailsType::GooglePay => "google_pay", + WalletDetailsType::Masterpass => "masterpass", + WalletDetailsType::SamsungPay => "samsung_pay", + WalletDetailsType::VisaCheckout => "visa_checkout", + } + } +} + +impl AsRef for WalletDetailsType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for WalletDetailsType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/payment_method_ext.rs b/ft-stripe/src/resources/payment_method_ext.rs new file mode 100644 index 0000000..21f9aa0 --- /dev/null +++ b/ft-stripe/src/resources/payment_method_ext.rs @@ -0,0 +1,32 @@ +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, PaymentMethodId}; +use crate::resources::PaymentMethod; +use serde::{Deserialize, Serialize}; + +/// The parameters for `PaymentMethod::attach` +/// +/// For more details see [https://stripe.com/docs/api/payment_methods/attach](https://stripe.com/docs/api/payment_methods/attach). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AttachPaymentMethod { + pub customer: CustomerId, +} + +impl PaymentMethod { + /// Attach a payment method to a customer + /// + /// For more details see [https://stripe.com/docs/api/payment_methods/attach](https://stripe.com/docs/api/payment_methods/attach). + pub fn attach( + client: &Client, + payment_method_id: &PaymentMethodId, + params: AttachPaymentMethod, + ) -> Response { + client.post_form(&format!("/payment_methods/{}/attach", payment_method_id), params) + } + + /// Detach a payment method from its customer + /// + /// For more details see [https://stripe.com/docs/api/payment_methods/detach](https://stripe.com/docs/api/payment_methods/detach). + pub fn detach(client: &Client, payment_method_id: &PaymentMethodId) -> Response { + client.post(&format!("/payment_methods/{}/detach", payment_method_id)) + } +} diff --git a/ft-stripe/src/resources/payment_source.rs b/ft-stripe/src/resources/payment_source.rs new file mode 100644 index 0000000..122c479 --- /dev/null +++ b/ft-stripe/src/resources/payment_source.rs @@ -0,0 +1,114 @@ +use crate::ids::{PaymentSourceId, SourceId, TokenId}; +use crate::params::Object; +use crate::resources::{Account, AlipayAccount, BankAccount, Card, Currency, Source}; +use serde::ser::SerializeStruct; +use serde::{Deserialize, Serialize}; + +/// A PaymentSourceParams represents all of the supported ways that can +/// be used to creating a new customer with a payment method or creating +/// a payment method directly for a customer via `Customer::attach_source`. +/// +/// Not to be confused with `SourceParams` which is used by `Source::create` +/// to create a source that is not necessarily attached to a customer. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PaymentSourceParams { + /// Creates a payment method (e.g. card or bank account) from tokenized data, + /// using a token typically received from Stripe Elements. + Token(TokenId), + + /// Attach an existing source to an existing customer or + /// create a new customer from an existing source. + Source(SourceId), +} + +/// A PaymentSource represents a payment method _associated with a customer or charge_. +/// This value is usually returned as a subresource on another request. +/// +/// Not to be confused with `Source` which represents a "generic" payment method +/// returned by the `Source::get` (which could still be a credit card, etc) +/// but is not necessarily attached to either a customer or charge. + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum PaymentSource { + Card(Card), + Source(Source), + Account(Account), + BankAccount(BankAccount), + AlipayAccount(AlipayAccount), +} + +impl Object for PaymentSource { + type Id = PaymentSourceId; + fn id(&self) -> Self::Id { + match self { + PaymentSource::Card(x) => PaymentSourceId::Card(x.id()), + PaymentSource::Source(x) => PaymentSourceId::Source(x.id()), + PaymentSource::Account(x) => PaymentSourceId::Account(x.id()), + PaymentSource::BankAccount(x) => PaymentSourceId::BankAccount(x.id()), + PaymentSource::AlipayAccount(x) => PaymentSourceId::AlipayAccount(x.id()), + } + } + fn object(&self) -> &'static str { + match self { + PaymentSource::Card(x) => x.object(), + PaymentSource::Source(x) => x.object(), + PaymentSource::Account(x) => x.object(), + PaymentSource::BankAccount(x) => x.object(), + PaymentSource::AlipayAccount(x) => x.object(), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +pub struct BankAccountParams<'a> { + pub country: &'a str, + pub currency: Currency, + pub account_holder_name: Option<&'a str>, + pub account_holder_type: Option<&'a str>, + pub routing_number: Option<&'a str>, + pub account_number: &'a str, +} + +impl<'a> serde::ser::Serialize for BankAccountParams<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + let mut s = serializer.serialize_struct("BankAccountParams", 6)?; + s.serialize_field("object", "bank_account")?; + s.serialize_field("country", &self.country)?; + s.serialize_field("currency", &self.currency)?; + s.serialize_field("account_holder_name", &self.account_holder_name)?; + s.serialize_field("routing_number", &self.routing_number)?; + s.serialize_field("account_number", &self.account_number)?; + s.end() + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +pub struct CardParams<'a> { + pub exp_month: &'a str, // eg. "12" + pub exp_year: &'a str, // eg. "17" or 2017" + + pub number: &'a str, // card number + pub name: Option<&'a str>, // cardholder's full name + pub cvc: Option<&'a str>, // card security code +} + +impl<'a> serde::ser::Serialize for CardParams<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + let mut s = serializer.serialize_struct("CardParams", 6)?; + s.serialize_field("object", "card")?; + s.serialize_field("exp_month", &self.exp_month)?; + s.serialize_field("exp_year", &self.exp_year)?; + s.serialize_field("number", &self.number)?; + s.serialize_field("name", &self.name)?; + s.serialize_field("cvc", &self.cvc)?; + s.end() + } +} diff --git a/ft-stripe/src/resources/payout.rs b/ft-stripe/src/resources/payout.rs new file mode 100644 index 0000000..fb6389d --- /dev/null +++ b/ft-stripe/src/resources/payout.rs @@ -0,0 +1,382 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::PayoutId; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{BalanceTransaction, BankAccount, Card, Currency}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Payout". +/// +/// For more details see [https://stripe.com/docs/api/payouts/object](https://stripe.com/docs/api/payouts/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Payout { + /// Unique identifier for the object. + pub id: PayoutId, + + /// Amount (in %s) to be transferred to your bank account or debit card. + pub amount: i64, + + /// Date the payout is expected to arrive in the bank. + /// + /// This factors in delays like weekends or bank holidays. + pub arrival_date: Timestamp, + + /// Returns `true` if the payout was created by an [automated payout schedule](https://stripe.com/docs/payouts#payout-schedule), and `false` if it was [requested manually](https://stripe.com/docs/payouts#manual-payouts). + pub automatic: bool, + + /// ID of the balance transaction that describes the impact of this payout on your account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// ID of the bank account or card the payout was sent to. + #[serde(skip_serializing_if = "Option::is_none")] + pub destination: Option>, + + /// If the payout failed or was canceled, this will be the ID of the balance transaction that reversed the initial balance transaction, and puts the funds from the failed payout back in your balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_balance_transaction: Option>, + + /// Error code explaining reason for payout failure if available. + /// + /// See [Types of payout failures](https://stripe.com/docs/api#payout_failures) for a list of failure codes. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_code: Option, + + /// Message to user further explaining reason for payout failure if available. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_message: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// The method used to send this payout, which can be `standard` or `instant`. + /// + /// `instant` is only supported for payouts to debit cards. + /// (See [Instant payouts for marketplaces](https://stripe.com/blog/instant-payouts-for-marketplaces) for more information.). + pub method: String, + + /// The source balance this payout came from. + /// + /// One of `card`, `fpx`, or `bank_account`. + pub source_type: String, + + /// Extra information about a payout to be displayed on the user's bank statement. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// Current status of the payout: `paid`, `pending`, `in_transit`, `canceled` or `failed`. + /// + /// A payout is `pending` until it is submitted to the bank, when it becomes `in_transit`. + /// The status then changes to `paid` if the transaction goes through, or to `failed` or `canceled` (within 5 business days). + /// Some failed payouts may initially show as `paid` but then change to `failed`. + pub status: String, + + /// Can be `bank_account` or `card`. + #[serde(rename = "type")] + pub type_: PayoutType, +} + +impl Payout { + /// Returns a list of existing payouts sent to third-party bank accounts or that Stripe has sent you. + /// + /// The payouts are returned in sorted order, with the most recently created payouts appearing first. + // pub fn list(client: &Client, params: ListPayouts<'_>) -> Response> { + // client.get_query("/payouts", ¶ms) + // } + + /// To send funds to your own bank account, you create a new payout object. + /// + /// Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the payout amount, or you’ll receive an “Insufficient Funds” error. If your API key is in test mode, money won’t actually be sent, though everything else will occur as if in live mode. If you are creating a manual payout on a Stripe account that uses multiple payment source types, you’ll need to specify the source type balance that the payout should draw from. + /// The [balance object](https://stripe.com/docs/api#balance_object) details available and pending amounts by source type. + pub fn create(client: &Client, params: CreatePayout<'_>) -> Response { + client.post_form("/payouts", ¶ms) + } + + /// Retrieves the details of an existing payout. + /// + /// Supply the unique payout ID from either a payout creation request or the payout list, and Stripe will return the corresponding payout information. + pub fn retrieve(client: &Client, id: &PayoutId, expand: &[&str]) -> Response { + client.get_query(&format!("/payouts/{}", id), &Expand { expand }) + } + + /// Updates the specified payout by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. + /// This request accepts only the metadata as arguments. + pub fn update(client: &Client, id: &PayoutId, params: UpdatePayout<'_>) -> Response { + client.post_form(&format!("/payouts/{}", id), ¶ms) + } +} + +impl Object for Payout { + type Id = PayoutId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "payout" + } +} + +/// The parameters for `Payout::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreatePayout<'a> { + /// A positive integer in cents representing how much to payout. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The method used to send this payout, which can be `standard` or `instant`. + /// + /// `instant` is only supported for payouts to debit cards. + /// (See [Instant payouts for marketplaces for more information](https://stripe.com/blog/instant-payouts-for-marketplaces).). + #[serde(skip_serializing_if = "Option::is_none")] + pub method: Option, + + /// The balance type of your Stripe balance to draw this payout from. + /// + /// Balances for different payment sources are kept separately. + /// You can find the amounts with the balances API. + /// One of `bank_account`, `card`, or `fpx`. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_type: Option, + + /// A string to be displayed on the recipient's bank or card statement. + /// + /// This may be at most 22 characters. + /// Attempting to use a `statement_descriptor` longer than 22 characters will return an error. + /// Note: Most banks will truncate this information and/or display it inconsistently. + /// Some may not display it at all. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, +} + +impl<'a> CreatePayout<'a> { + pub fn new(amount: i64, currency: Currency) -> Self { + CreatePayout { + amount, + currency, + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + method: Default::default(), + source_type: Default::default(), + statement_descriptor: Default::default(), + } + } +} + +/// The parameters for `Payout::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListPayouts<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub arrival_date: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return payouts that have the given status: `pending`, `paid`, `failed`, or `canceled`. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option<&'a str>, +} + +impl<'a> ListPayouts<'a> { + pub fn new() -> Self { + ListPayouts { + arrival_date: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + status: Default::default(), + } + } +} + +/// The parameters for `Payout::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdatePayout<'a> { + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdatePayout<'a> { + pub fn new() -> Self { + UpdatePayout { expand: Default::default(), metadata: Default::default() } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "object", rename_all = "snake_case")] +pub enum PayoutDestination { + BankAccount(BankAccount), + Card(Card), +} + +/// An enum representing the possible values of an `CreatePayout`'s `method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PayoutMethod { + Instant, + Standard, +} + +impl PayoutMethod { + pub fn as_str(self) -> &'static str { + match self { + PayoutMethod::Instant => "instant", + PayoutMethod::Standard => "standard", + } + } +} + +impl AsRef for PayoutMethod { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PayoutMethod { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreatePayout`'s `source_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PayoutSourceType { + BankAccount, + Card, + Fpx, +} + +impl PayoutSourceType { + pub fn as_str(self) -> &'static str { + match self { + PayoutSourceType::BankAccount => "bank_account", + PayoutSourceType::Card => "card", + PayoutSourceType::Fpx => "fpx", + } + } +} + +impl AsRef for PayoutSourceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PayoutSourceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Payout`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PayoutType { + BankAccount, + Card, +} + +impl PayoutType { + pub fn as_str(self) -> &'static str { + match self { + PayoutType::BankAccount => "bank_account", + PayoutType::Card => "card", + } + } +} + +impl AsRef for PayoutType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PayoutType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/payout_ext.rs b/ft-stripe/src/resources/payout_ext.rs new file mode 100644 index 0000000..026659f --- /dev/null +++ b/ft-stripe/src/resources/payout_ext.rs @@ -0,0 +1,29 @@ +use crate::config::{Client, Response}; +use crate::ids::{PayoutDestinationId, PayoutId}; +use crate::params::Object; +use crate::resources::{Payout, PayoutDestination}; + +impl Payout { + /// Cancels the payout. + /// + /// For more details see [https://stripe.com/docs/api/payouts/cancel](https://stripe.com/docs/api/payouts/cancel). + pub fn cancel(client: &Client, id: &PayoutId) -> Response { + client.post(&format!("/payouts/{}/cancel", id)) + } +} + +impl Object for PayoutDestination { + type Id = PayoutDestinationId; + fn id(&self) -> Self::Id { + match self { + PayoutDestination::BankAccount(x) => PayoutDestinationId::BankAccount(x.id()), + PayoutDestination::Card(x) => PayoutDestinationId::Card(x.id()), + } + } + fn object(&self) -> &'static str { + match self { + PayoutDestination::BankAccount(x) => x.object(), + PayoutDestination::Card(x) => x.object(), + } + } +} diff --git a/ft-stripe/src/resources/person.rs b/ft-stripe/src/resources/person.rs new file mode 100644 index 0000000..eaf6a86 --- /dev/null +++ b/ft-stripe/src/resources/person.rs @@ -0,0 +1,397 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::PersonId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{Address, Dob, File}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Person". +/// +/// For more details see [https://stripe.com/docs/api/persons/object](https://stripe.com/docs/api/persons/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Person { + /// Unique identifier for the object. + pub id: PersonId, + + #[serde(skip_serializing_if = "Option::is_none")] + pub account: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kana: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kanji: Option
, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dob: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub gender: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id_number_provided: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub maiden_name: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub relationship: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub requirements: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ssn_last_4_provided: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +impl Object for Person { + type Id = PersonId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "person" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonVerification { + /// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_document: Option, + + /// A user-displayable string describing the verification state for the person. + /// + /// For example, this may say "Provided identity information could not be verified". + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option, + + /// One of `document_address_mismatch`, `document_dob_mismatch`, `document_duplicate_type`, `document_id_number_mismatch`, `document_name_mismatch`, `document_nationality_mismatch`, `failed_keyed_identity`, or `failed_other`. + /// + /// A machine-readable code specifying the verification state for the person. + #[serde(skip_serializing_if = "Option::is_none")] + pub details_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub document: Option, + + /// The state of verification for the person. + /// + /// Possible values are `unverified`, `pending`, or `verified`. + pub status: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonVerificationDocument { + /// The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + #[serde(skip_serializing_if = "Option::is_none")] + pub back: Option>, + + /// A user-displayable string describing the verification state of this document. + /// + /// For example, if a document is uploaded and the picture is too fuzzy, this may say "Identity document is too unclear to read". + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option, + + /// One of `document_corrupt`, `document_country_not_supported`, `document_expired`, `document_failed_copy`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_failed_greyscale`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_missing_back`, `document_missing_front`, `document_not_readable`, `document_not_uploaded`, `document_photo_mismatch`, `document_too_large`, or `document_type_not_supported`. + /// + /// A machine-readable code specifying the verification state for this document. + #[serde(skip_serializing_if = "Option::is_none")] + pub details_code: Option, + + /// The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. + #[serde(skip_serializing_if = "Option::is_none")] + pub front: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonRelationship { + /// Whether the person is a director of the account's legal entity. + /// + /// Currently only required for accounts in the EU. + /// Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. + #[serde(skip_serializing_if = "Option::is_none")] + pub director: Option, + + /// Whether the person has significant responsibility to control, manage, or direct the organization. + #[serde(skip_serializing_if = "Option::is_none")] + pub executive: Option, + + /// Whether the person is an owner of the account’s legal entity. + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + + /// The percent owned by the person of the account's legal entity. + #[serde(skip_serializing_if = "Option::is_none")] + pub percent_ownership: Option, + + /// Whether the person is authorized as the primary representative of the account. + /// + /// This is the person nominated by the business to provide information about themselves, and general information about the account. + /// There can only be one representative at any given time. + /// At the time the account is created, this person should be set to the person responsible for opening the account. + #[serde(skip_serializing_if = "Option::is_none")] + pub representative: Option, + + /// The person's title (e.g., CEO, Support Engineer). + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonRequirements { + /// Fields that need to be collected to keep the person's account enabled. + /// + /// If not collected by the account's `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. + pub currently_due: Vec, + + /// The fields that need to be collected again because validation or verification failed for some reason. + pub errors: Vec, + + /// Fields that need to be collected assuming all volume thresholds are reached. + /// + /// As fields are needed, they are moved to `currently_due` and the account's `current_deadline` is set. + pub eventually_due: Vec, + + /// Fields that weren't collected by the account's `current_deadline`. + /// + /// These fields need to be collected to enable payouts for the person's account. + pub past_due: Vec, + + /// Fields that may become required depending on the results of verification or review. + /// + /// An empty array unless an asynchronous verification is pending. + /// If verification fails, the fields in this array become required and move to `currently_due` or `past_due`. + pub pending_verification: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AccountRequirementsError { + /// The code for the type of error. + pub code: AccountRequirementsErrorCode, + + /// An informative message that indicates the error type and provides additional details about the error. + pub reason: String, + + /// The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. + pub requirement: String, +} + +/// An enum representing the possible values of an `AccountRequirementsError`'s `code` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum AccountRequirementsErrorCode { + InvalidAddressCityStatePostalCode, + InvalidStreetAddress, + InvalidValueOther, + VerificationDocumentAddressMismatch, + VerificationDocumentAddressMissing, + VerificationDocumentCorrupt, + VerificationDocumentCountryNotSupported, + VerificationDocumentDobMismatch, + VerificationDocumentDuplicateType, + VerificationDocumentExpired, + VerificationDocumentFailedCopy, + VerificationDocumentFailedGreyscale, + VerificationDocumentFailedOther, + VerificationDocumentFailedTestMode, + VerificationDocumentFraudulent, + VerificationDocumentIdNumberMismatch, + VerificationDocumentIdNumberMissing, + VerificationDocumentIncomplete, + VerificationDocumentInvalid, + VerificationDocumentManipulated, + VerificationDocumentMissingBack, + VerificationDocumentMissingFront, + VerificationDocumentNameMismatch, + VerificationDocumentNameMissing, + VerificationDocumentNationalityMismatch, + VerificationDocumentNotReadable, + VerificationDocumentNotUploaded, + VerificationDocumentPhotoMismatch, + VerificationDocumentTooLarge, + VerificationDocumentTypeNotSupported, + VerificationFailedAddressMatch, + VerificationFailedBusinessIecNumber, + VerificationFailedDocumentMatch, + VerificationFailedIdNumberMatch, + VerificationFailedKeyedIdentity, + VerificationFailedKeyedMatch, + VerificationFailedNameMatch, + VerificationFailedOther, +} + +impl AccountRequirementsErrorCode { + pub fn as_str(self) -> &'static str { + match self { + AccountRequirementsErrorCode::InvalidAddressCityStatePostalCode => { + "invalid_address_city_state_postal_code" + } + AccountRequirementsErrorCode::InvalidStreetAddress => "invalid_street_address", + AccountRequirementsErrorCode::InvalidValueOther => "invalid_value_other", + AccountRequirementsErrorCode::VerificationDocumentAddressMismatch => { + "verification_document_address_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentAddressMissing => { + "verification_document_address_missing" + } + AccountRequirementsErrorCode::VerificationDocumentCorrupt => { + "verification_document_corrupt" + } + AccountRequirementsErrorCode::VerificationDocumentCountryNotSupported => { + "verification_document_country_not_supported" + } + AccountRequirementsErrorCode::VerificationDocumentDobMismatch => { + "verification_document_dob_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentDuplicateType => { + "verification_document_duplicate_type" + } + AccountRequirementsErrorCode::VerificationDocumentExpired => { + "verification_document_expired" + } + AccountRequirementsErrorCode::VerificationDocumentFailedCopy => { + "verification_document_failed_copy" + } + AccountRequirementsErrorCode::VerificationDocumentFailedGreyscale => { + "verification_document_failed_greyscale" + } + AccountRequirementsErrorCode::VerificationDocumentFailedOther => { + "verification_document_failed_other" + } + AccountRequirementsErrorCode::VerificationDocumentFailedTestMode => { + "verification_document_failed_test_mode" + } + AccountRequirementsErrorCode::VerificationDocumentFraudulent => { + "verification_document_fraudulent" + } + AccountRequirementsErrorCode::VerificationDocumentIdNumberMismatch => { + "verification_document_id_number_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentIdNumberMissing => { + "verification_document_id_number_missing" + } + AccountRequirementsErrorCode::VerificationDocumentIncomplete => { + "verification_document_incomplete" + } + AccountRequirementsErrorCode::VerificationDocumentInvalid => { + "verification_document_invalid" + } + AccountRequirementsErrorCode::VerificationDocumentManipulated => { + "verification_document_manipulated" + } + AccountRequirementsErrorCode::VerificationDocumentMissingBack => { + "verification_document_missing_back" + } + AccountRequirementsErrorCode::VerificationDocumentMissingFront => { + "verification_document_missing_front" + } + AccountRequirementsErrorCode::VerificationDocumentNameMismatch => { + "verification_document_name_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentNameMissing => { + "verification_document_name_missing" + } + AccountRequirementsErrorCode::VerificationDocumentNationalityMismatch => { + "verification_document_nationality_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentNotReadable => { + "verification_document_not_readable" + } + AccountRequirementsErrorCode::VerificationDocumentNotUploaded => { + "verification_document_not_uploaded" + } + AccountRequirementsErrorCode::VerificationDocumentPhotoMismatch => { + "verification_document_photo_mismatch" + } + AccountRequirementsErrorCode::VerificationDocumentTooLarge => { + "verification_document_too_large" + } + AccountRequirementsErrorCode::VerificationDocumentTypeNotSupported => { + "verification_document_type_not_supported" + } + AccountRequirementsErrorCode::VerificationFailedAddressMatch => { + "verification_failed_address_match" + } + AccountRequirementsErrorCode::VerificationFailedBusinessIecNumber => { + "verification_failed_business_iec_number" + } + AccountRequirementsErrorCode::VerificationFailedDocumentMatch => { + "verification_failed_document_match" + } + AccountRequirementsErrorCode::VerificationFailedIdNumberMatch => { + "verification_failed_id_number_match" + } + AccountRequirementsErrorCode::VerificationFailedKeyedIdentity => { + "verification_failed_keyed_identity" + } + AccountRequirementsErrorCode::VerificationFailedKeyedMatch => { + "verification_failed_keyed_match" + } + AccountRequirementsErrorCode::VerificationFailedNameMatch => { + "verification_failed_name_match" + } + AccountRequirementsErrorCode::VerificationFailedOther => "verification_failed_other", + } + } +} + +impl AsRef for AccountRequirementsErrorCode { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for AccountRequirementsErrorCode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/placeholders.rs b/ft-stripe/src/resources/placeholders.rs new file mode 100644 index 0000000..dd12957 --- /dev/null +++ b/ft-stripe/src/resources/placeholders.rs @@ -0,0 +1,598 @@ +use crate::ids::*; +use crate::params::Object; +use serde::{Deserialize, Serialize}; + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Account { + pub id: AccountId, +} + +#[cfg(not(feature = "connect"))] +impl Object for Account { + type Id = AccountId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "account" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Application { + pub id: (), +} + +#[cfg(not(feature = "connect"))] +impl Object for Application { + type Id = (); + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "application" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ApplicationFee { + pub id: ApplicationFeeId, +} + +#[cfg(not(feature = "connect"))] +impl Object for ApplicationFee { + type Id = ApplicationFeeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "application_fee" + } +} + +#[cfg(not(feature = "checkout"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CheckoutSession { + pub id: CheckoutSessionId, +} + +#[cfg(not(feature = "checkout"))] +impl Object for CheckoutSession { + type Id = CheckoutSessionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "checkout_session" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ConnectCollectionTransfer { + pub id: (), +} + +#[cfg(not(feature = "connect"))] +impl Object for ConnectCollectionTransfer { + type Id = (); + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "connect_collection_transfer" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Coupon { + pub id: CouponId, +} + +#[cfg(not(feature = "billing"))] +impl Object for Coupon { + type Id = CouponId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "coupon" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Discount { + pub id: (), +} + +#[cfg(not(feature = "billing"))] +impl Object for Discount { + type Id = (); + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "discount" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ApplicationFeeRefund { + pub id: ApplicationFeeRefundId, +} + +#[cfg(not(feature = "connect"))] +impl Object for ApplicationFeeRefund { + type Id = ApplicationFeeRefundId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "fee_refund" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Invoice { + pub id: InvoiceId, +} + +#[cfg(not(feature = "billing"))] +impl Object for Invoice { + type Id = InvoiceId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "invoice" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItem { + pub id: InvoiceItemId, +} + +#[cfg(not(feature = "billing"))] +impl Object for InvoiceItem { + type Id = InvoiceItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "invoiceitem" + } +} + +#[cfg(not(feature = "issuing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingAuthorization { + pub id: IssuingAuthorizationId, +} + +#[cfg(not(feature = "issuing"))] +impl Object for IssuingAuthorization { + type Id = IssuingAuthorizationId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.authorization" + } +} + +#[cfg(not(feature = "issuing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCard { + pub id: IssuingCardId, +} + +#[cfg(not(feature = "issuing"))] +impl Object for IssuingCard { + type Id = IssuingCardId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.card" + } +} + +#[cfg(not(feature = "issuing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingCardholder { + pub id: IssuingCardholderId, +} + +#[cfg(not(feature = "issuing"))] +impl Object for IssuingCardholder { + type Id = IssuingCardholderId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.cardholder" + } +} + +#[cfg(not(feature = "issuing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingDispute { + pub id: IssuingDisputeId, +} + +#[cfg(not(feature = "issuing"))] +impl Object for IssuingDispute { + type Id = IssuingDisputeId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.dispute" + } +} + +#[cfg(not(feature = "issuing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct IssuingTransaction { + pub id: IssuingTransactionId, +} + +#[cfg(not(feature = "issuing"))] +impl Object for IssuingTransaction { + type Id = IssuingTransactionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "issuing.transaction" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceLineItem { + pub id: InvoiceLineItemId, +} + +#[cfg(not(feature = "billing"))] +impl Object for InvoiceLineItem { + type Id = InvoiceLineItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "line_item" + } +} + +#[cfg(not(feature = "orders"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Order { + pub id: OrderId, +} + +#[cfg(not(feature = "orders"))] +impl Object for Order { + type Id = OrderId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "order" + } +} + +#[cfg(not(feature = "orders"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OrderItem { + pub id: (), +} + +#[cfg(not(feature = "orders"))] +impl Object for OrderItem { + type Id = (); + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "order_item" + } +} + +#[cfg(not(feature = "orders"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OrderReturn { + pub id: OrderReturnId, +} + +#[cfg(not(feature = "orders"))] +impl Object for OrderReturn { + type Id = OrderReturnId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "order_return" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Person { + pub id: PersonId, +} + +#[cfg(not(feature = "connect"))] +impl Object for Person { + type Id = PersonId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "person" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Plan { + pub id: PlanId, +} + +#[cfg(not(feature = "billing"))] +impl Object for Plan { + type Id = PlanId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "plan" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Recipient { + pub id: RecipientId, +} + +#[cfg(not(feature = "connect"))] +impl Object for Recipient { + type Id = RecipientId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "recipient" + } +} + +#[cfg(not(feature = "fraud"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Review { + pub id: ReviewId, +} + +#[cfg(not(feature = "fraud"))] +impl Object for Review { + type Id = ReviewId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "review" + } +} + +#[cfg(not(feature = "sigma"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ScheduledQueryRun { + pub id: ScheduledQueryRunId, +} + +#[cfg(not(feature = "sigma"))] +impl Object for ScheduledQueryRun { + type Id = ScheduledQueryRunId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "scheduled_query_run" + } +} + +#[cfg(not(feature = "orders"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Sku { + pub id: SkuId, +} + +#[cfg(not(feature = "orders"))] +impl Object for Sku { + type Id = SkuId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "sku" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Subscription { + pub id: SubscriptionId, +} + +#[cfg(not(feature = "billing"))] +impl Object for Subscription { + type Id = SubscriptionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItem { + pub id: SubscriptionItemId, +} + +#[cfg(not(feature = "billing"))] +impl Object for SubscriptionItem { + type Id = SubscriptionItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription_item" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionSchedule { + pub id: SubscriptionScheduleId, +} + +#[cfg(not(feature = "billing"))] +impl Object for SubscriptionSchedule { + type Id = SubscriptionScheduleId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription_schedule" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleRevision { + pub id: (), +} + +#[cfg(not(feature = "billing"))] +impl Object for SubscriptionScheduleRevision { + type Id = (); + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription_schedule_revision" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxId { + pub id: TaxIdId, +} + +#[cfg(not(feature = "billing"))] +impl Object for TaxId { + type Id = TaxIdId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "tax_id" + } +} + +#[cfg(not(feature = "billing"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxRate { + pub id: TaxRateId, +} + +#[cfg(not(feature = "billing"))] +impl Object for TaxRate { + type Id = TaxRateId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "tax_rate" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Topup { + pub id: TopupId, +} + +#[cfg(not(feature = "connect"))] +impl Object for Topup { + type Id = TopupId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "topup" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Transfer { + pub id: TransferId, +} + +#[cfg(not(feature = "connect"))] +impl Object for Transfer { + type Id = TransferId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "transfer" + } +} + +#[cfg(not(feature = "connect"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferReversal { + pub id: TransferReversalId, +} + +#[cfg(not(feature = "connect"))] +impl Object for TransferReversal { + type Id = TransferReversalId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "transfer_reversal" + } +} + +#[cfg(not(feature = "webhook-endpoints"))] +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WebhookEndpoint { + pub id: WebhookEndpointId, +} + +#[cfg(not(feature = "webhook-endpoints"))] +impl Object for WebhookEndpoint { + type Id = WebhookEndpointId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "webhook_endpoint" + } +} diff --git a/ft-stripe/src/resources/plan.rs b/ft-stripe/src/resources/plan.rs new file mode 100644 index 0000000..6aecefd --- /dev/null +++ b/ft-stripe/src/resources/plan.rs @@ -0,0 +1,674 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::PlanId; +use crate::params::{ + Deleted, Expand, Expandable, IdOrCreate, List, Metadata, Object, RangeQuery, Timestamp, +}; +use crate::resources::{CreateProduct, Currency, Product, UpTo}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Plan". +/// +/// For more details see [https://stripe.com/docs/api/plans/object](https://stripe.com/docs/api/plans/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Plan { + /// Unique identifier for the object. + pub id: PlanId, + + /// Whether the plan can be used for new purchases. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Specifies a usage aggregation strategy for plans of `usage_type=metered`. + /// + /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. + /// Defaults to `sum`. + #[serde(skip_serializing_if = "Option::is_none")] + pub aggregate_usage: Option, + + /// The unit amount in %s to be charged, represented as a whole integer if possible. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// The unit amount in %s to be charged, represented as a decimal string with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_decimal: Option, + + /// Describes how to compute the price per period. + /// + /// Either `per_unit` or `tiered`. + /// `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`). + /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_scheme: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// The frequency at which a subscription is billed. + /// + /// One of `day`, `week`, `month` or `year`. + #[serde(skip_serializing_if = "Option::is_none")] + pub interval: Option, + + /// The number of intervals (specified in the `interval` attribute) between subscription billings. + /// + /// For example, `interval=month` and `interval_count=3` bills every 3 months. + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// A brief description of the plan, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option, + + /// The product whose pricing this plan determines. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>, + + /// Each element represents a pricing tier. + /// + /// This parameter requires `billing_scheme` to be set to `tiered`. + /// See also the documentation for `billing_scheme`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers: Option>, + + /// Defines if the tiering price should be `graduated` or `volume` based. + /// + /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + /// In `graduated` tiering, pricing can change as the quantity grows. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers_mode: Option, + + /// Apply a transformation to the reported usage or set quantity before computing the amount billed. + /// + /// Cannot be combined with `tiers`. + #[serde(skip_serializing_if = "Option::is_none")] + pub transform_usage: Option, + + /// 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). + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, + + /// Configures how the quantity per period should be determined. + /// + /// Can be either `metered` or `licensed`. + /// `licensed` automatically bills the `quantity` set when adding it to a subscription. + /// `metered` aggregates the total usage based on usage records. + /// Defaults to `licensed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub usage_type: Option, +} + +impl Plan { + /// Returns a list of your plans. + pub fn list(client: &Client, params: ListPlans<'_>) -> Response> { + client.get_query("/plans", ¶ms) + } + + /// You can create plans using the API, or in the Stripe [Dashboard](https://dashboard.stripe.com/subscriptions/products). + pub fn create(client: &Client, params: CreatePlan<'_>) -> Response { + client.post_form("/plans", ¶ms) + } + + /// Retrieves the plan with the given ID. + pub fn retrieve(client: &Client, id: &PlanId, expand: &[&str]) -> Response { + client.get_query(&format!("/plans/{}", id), &Expand { expand }) + } + + /// Updates the specified plan by setting the values of the parameters passed. + /// + /// Any parameters not provided are left unchanged. + /// By design, you cannot change a plan’s ID, amount, currency, or billing cycle. + pub fn update(client: &Client, id: &PlanId, params: UpdatePlan<'_>) -> Response { + client.post_form(&format!("/plans/{}", id), ¶ms) + } + + /// Deleting plans means new subscribers can’t be added. + /// + /// Existing subscribers aren’t affected. + pub fn delete(client: &Client, id: &PlanId) -> Response> { + client.delete(&format!("/plans/{}", id)) + } +} + +impl Object for Plan { + type Id = PlanId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "plan" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PlanTier { + /// Price for the entire tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount: Option, + + /// Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount_decimal: Option, + + /// Per unit price for units relevant to the tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, + + /// Up to and including to this quantity will be contained in the tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub up_to: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransformUsage { + /// Divide usage by this number. + pub divide_by: i64, + + /// After division, either round the result `up` or `down`. + pub round: TransformUsageRound, +} + +/// The parameters for `Plan::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreatePlan<'a> { + /// Whether the plan is currently available for new subscriptions. + /// + /// Defaults to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Specifies a usage aggregation strategy for plans of `usage_type=metered`. + /// + /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. + /// Defaults to `sum`. + #[serde(skip_serializing_if = "Option::is_none")] + pub aggregate_usage: Option, + + /// A positive integer in %s (or 0 for a free plan) representing how much to charge on a recurring basis. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Same as `amount`, but accepts a decimal value with at most 12 decimal places. + /// + /// Only one of `amount` and `amount_decimal` can be set. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_decimal: Option<&'a str>, + + /// Describes how to compute the price per period. + /// + /// Either `per_unit` or `tiered`. + /// `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`). + /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_scheme: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// An identifier randomly generated by Stripe. + /// + /// Used to identify this plan when subscribing a customer. + /// You can optionally override this ID, but the ID must be unique across all plans in your Stripe account. + /// You can, however, use the same plan ID in both live and test modes. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option<&'a str>, + + /// Specifies billing frequency. + /// + /// Either `day`, `week`, `month` or `year`. + pub interval: PlanInterval, + + /// The number of intervals between subscription billings. + /// + /// For example, `interval=month` and `interval_count=3` bills every 3 months. + /// Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// A brief description of the plan, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option<&'a str>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// Each element represents a pricing tier. + /// + /// This parameter requires `billing_scheme` to be set to `tiered`. + /// See also the documentation for `billing_scheme`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers: Option>, + + /// Defines if the tiering price should be `graduated` or `volume` based. + /// + /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers_mode: Option, + + /// Apply a transformation to the reported usage or set quantity before computing the billed price. + /// + /// Cannot be combined with `tiers`. + #[serde(skip_serializing_if = "Option::is_none")] + pub transform_usage: Option, + + /// 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). + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, + + /// Configures how the quantity per period should be determined. + /// + /// Can be either `metered` or `licensed`. + /// `licensed` automatically bills the `quantity` set when adding it to a subscription. + /// `metered` aggregates the total usage based on usage records. + /// Defaults to `licensed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub usage_type: Option, +} + +impl<'a> CreatePlan<'a> { + pub fn new(currency: Currency, interval: PlanInterval) -> Self { + CreatePlan { + active: Default::default(), + aggregate_usage: Default::default(), + amount: Default::default(), + amount_decimal: Default::default(), + billing_scheme: Default::default(), + currency, + expand: Default::default(), + id: Default::default(), + interval, + interval_count: Default::default(), + metadata: Default::default(), + nickname: Default::default(), + product: Default::default(), + tiers: Default::default(), + tiers_mode: Default::default(), + transform_usage: Default::default(), + trial_period_days: Default::default(), + usage_type: Default::default(), + } + } +} + +/// The parameters for `Plan::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListPlans<'a> { + /// Only return plans that are active or inactive (e.g., pass `false` to list all inactive plans). + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return plans for the given product. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListPlans<'a> { + pub fn new() -> Self { + ListPlans { + active: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + product: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Plan::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdatePlan<'a> { + /// Whether the plan is currently available for new subscriptions. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// A brief description of the plan, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option<&'a str>, + + /// The product the plan belongs to. + /// + /// Note that after updating, statement descriptors and line items of the plan in active subscriptions will be affected. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// 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). + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, +} + +impl<'a> UpdatePlan<'a> { + pub fn new() -> Self { + UpdatePlan { + active: Default::default(), + expand: Default::default(), + metadata: Default::default(), + nickname: Default::default(), + product: Default::default(), + trial_period_days: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePlanTiers { + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount_decimal: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, + + pub up_to: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePlanTransformUsage { + pub divide_by: i64, + + pub round: CreatePlanTransformUsageRound, +} + +/// An enum representing the possible values of an `CreatePlanTransformUsage`'s `round` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePlanTransformUsageRound { + Down, + Up, +} + +impl CreatePlanTransformUsageRound { + pub fn as_str(self) -> &'static str { + match self { + CreatePlanTransformUsageRound::Down => "down", + CreatePlanTransformUsageRound::Up => "up", + } + } +} + +impl AsRef for CreatePlanTransformUsageRound { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePlanTransformUsageRound { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Plan`'s `aggregate_usage` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanAggregateUsage { + LastDuringPeriod, + LastEver, + Max, + Sum, +} + +impl PlanAggregateUsage { + pub fn as_str(self) -> &'static str { + match self { + PlanAggregateUsage::LastDuringPeriod => "last_during_period", + PlanAggregateUsage::LastEver => "last_ever", + PlanAggregateUsage::Max => "max", + PlanAggregateUsage::Sum => "sum", + } + } +} + +impl AsRef for PlanAggregateUsage { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanAggregateUsage { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Plan`'s `billing_scheme` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanBillingScheme { + PerUnit, + Tiered, +} + +impl PlanBillingScheme { + pub fn as_str(self) -> &'static str { + match self { + PlanBillingScheme::PerUnit => "per_unit", + PlanBillingScheme::Tiered => "tiered", + } + } +} + +impl AsRef for PlanBillingScheme { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanBillingScheme { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Plan`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanInterval { + Day, + Month, + Week, + Year, +} + +impl PlanInterval { + pub fn as_str(self) -> &'static str { + match self { + PlanInterval::Day => "day", + PlanInterval::Month => "month", + PlanInterval::Week => "week", + PlanInterval::Year => "year", + } + } +} + +impl AsRef for PlanInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Plan`'s `tiers_mode` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanTiersMode { + Graduated, + Volume, +} + +impl PlanTiersMode { + pub fn as_str(self) -> &'static str { + match self { + PlanTiersMode::Graduated => "graduated", + PlanTiersMode::Volume => "volume", + } + } +} + +impl AsRef for PlanTiersMode { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanTiersMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Plan`'s `usage_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanUsageType { + Licensed, + Metered, +} + +impl PlanUsageType { + pub fn as_str(self) -> &'static str { + match self { + PlanUsageType::Licensed => "licensed", + PlanUsageType::Metered => "metered", + } + } +} + +impl AsRef for PlanUsageType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanUsageType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `TransformUsage`'s `round` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TransformUsageRound { + Down, + Up, +} + +impl TransformUsageRound { + pub fn as_str(self) -> &'static str { + match self { + TransformUsageRound::Down => "down", + TransformUsageRound::Up => "up", + } + } +} + +impl AsRef for TransformUsageRound { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TransformUsageRound { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/platform_tax_fee.rs b/ft-stripe/src/resources/platform_tax_fee.rs new file mode 100644 index 0000000..d3d3f57 --- /dev/null +++ b/ft-stripe/src/resources/platform_tax_fee.rs @@ -0,0 +1,28 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::Object; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "PlatformTax". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PlatformTaxFee { + /// The Connected account that incurred this charge. + pub account: String, + + /// The payment object that caused this tax to be inflicted. + pub source_transaction: String, + + /// The type of tax (VAT). + #[serde(rename = "type")] + pub type_: String, +} + +impl Object for PlatformTaxFee { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "platform_tax_fee" + } +} diff --git a/ft-stripe/src/resources/price.rs b/ft-stripe/src/resources/price.rs new file mode 100644 index 0000000..4723e11 --- /dev/null +++ b/ft-stripe/src/resources/price.rs @@ -0,0 +1,920 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::PriceId; +use crate::params::{ + Expand, Expandable, IdOrCreate, List, Metadata, Object, RangeQuery, Timestamp, +}; +use crate::resources::{CreateProduct, Currency, Product, UpTo}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Price". +/// +/// For more details see [https://stripe.com/docs/api/prices/object](https://stripe.com/docs/api/prices/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Price { + /// Unique identifier for the object. + pub id: PriceId, + + /// Whether the price can be used for new purchases. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Describes how to compute the price per period. + /// + /// Either `per_unit` or `tiered`. + /// `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). + /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_scheme: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// A lookup key used to retrieve prices dynamically from a static string. + #[serde(skip_serializing_if = "Option::is_none")] + pub lookup_key: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// A brief description of the plan, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option, + + /// The ID of the product this price is associated with. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>, + + /// The recurring components of a price such as `interval` and `usage_type`. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, + + /// Each element represents a pricing tier. + /// + /// This parameter requires `billing_scheme` to be set to `tiered`. + /// See also the documentation for `billing_scheme`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers: Option>, + + /// Defines if the tiering price should be `graduated` or `volume` based. + /// + /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + /// In `graduated` tiering, pricing can change as the quantity grows. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers_mode: Option, + + /// Apply a transformation to the reported usage or set quantity before computing the amount billed. + /// + /// Cannot be combined with `tiers`. + #[serde(skip_serializing_if = "Option::is_none")] + pub transform_quantity: Option, + + /// One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// The unit amount in %s to be charged, represented as a whole integer if possible. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// The unit amount in %s to be charged, represented as a decimal string with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +impl Price { + /// Returns a list of your prices. + pub fn list(client: &Client, params: ListPrices<'_>) -> Response> { + client.get_query("/prices", ¶ms) + } + + /// Creates a new price for an existing product. + /// + /// The price can be recurring or one-time. + pub fn create(client: &Client, params: CreatePrice<'_>) -> Response { + client.post_form("/prices", ¶ms) + } + + /// Retrieves the price with the given ID. + pub fn retrieve(client: &Client, id: &PriceId, expand: &[&str]) -> Response { + client.get_query(&format!("/prices/{}", id), &Expand { expand }) + } + + /// Updates the specified price by setting the values of the parameters passed. + /// + /// Any parameters not provided are left unchanged. + pub fn update(client: &Client, id: &PriceId, params: UpdatePrice<'_>) -> Response { + client.post_form(&format!("/prices/{}", id), ¶ms) + } +} + +impl Object for Price { + type Id = PriceId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "price" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PriceTier { + /// Price for the entire tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount: Option, + + /// Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount_decimal: Option, + + /// Per unit price for units relevant to the tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, + + /// Up to and including to this quantity will be contained in the tier. + #[serde(skip_serializing_if = "Option::is_none")] + pub up_to: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Recurring { + /// Specifies a usage aggregation strategy for prices of `usage_type=metered`. + /// + /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. + /// Defaults to `sum`. + #[serde(skip_serializing_if = "Option::is_none")] + pub aggregate_usage: Option, + + /// The frequency at which a subscription is billed. + /// + /// One of `day`, `week`, `month` or `year`. + pub interval: RecurringInterval, + + /// The number of intervals (specified in the `interval` attribute) between subscription billings. + /// + /// For example, `interval=month` and `interval_count=3` bills every 3 months. + pub interval_count: u64, + + /// Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, + + /// Configures how the quantity per period should be determined. + /// + /// Can be either `metered` or `licensed`. + /// `licensed` automatically bills the `quantity` set when adding it to a subscription. + /// `metered` aggregates the total usage based on usage records. + /// Defaults to `licensed`. + pub usage_type: RecurringUsageType, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransformQuantity { + /// Divide usage by this number. + pub divide_by: i64, + + /// After division, either round the result `up` or `down`. + pub round: TransformQuantityRound, +} + +/// The parameters for `Price::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreatePrice<'a> { + /// Whether the price is currently active. + /// + /// Defaults to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Describes how to compute the price per period. + /// + /// Either `per_unit` or `tiered`. + /// `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). + /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_scheme: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A lookup key used to retrieve prices dynamically from a static string. + #[serde(skip_serializing_if = "Option::is_none")] + pub lookup_key: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// A brief description of the price, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option<&'a str>, + + /// The ID of the product that this price will belong to. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// These fields can be used to create a new product that this price will belong to. + #[serde(skip_serializing_if = "Option::is_none")] + pub product_data: Option, + + /// The recurring components of a price such as `interval` and `usage_type`. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, + + /// Each element represents a pricing tier. + /// + /// This parameter requires `billing_scheme` to be set to `tiered`. + /// See also the documentation for `billing_scheme`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers: Option>, + + /// Defines if the tiering price should be `graduated` or `volume` based. + /// + /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. + #[serde(skip_serializing_if = "Option::is_none")] + pub tiers_mode: Option, + + /// If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_lookup_key: Option, + + /// Apply a transformation to the reported usage or set quantity before computing the billed price. + /// + /// Cannot be combined with `tiers`. + #[serde(skip_serializing_if = "Option::is_none")] + pub transform_quantity: Option, + + /// A positive integer in %s (or 0 for a free price) representing how much to charge. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. + /// + /// Only one of `unit_amount` and `unit_amount_decimal` can be set. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option<&'a str>, +} + +impl<'a> CreatePrice<'a> { + pub fn new(currency: Currency) -> Self { + CreatePrice { + active: Default::default(), + billing_scheme: Default::default(), + currency, + expand: Default::default(), + lookup_key: Default::default(), + metadata: Default::default(), + nickname: Default::default(), + product: Default::default(), + product_data: Default::default(), + recurring: Default::default(), + tiers: Default::default(), + tiers_mode: Default::default(), + transfer_lookup_key: Default::default(), + transform_quantity: Default::default(), + unit_amount: Default::default(), + unit_amount_decimal: Default::default(), + } + } +} + +/// The parameters for `Price::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListPrices<'a> { + /// Only return prices that are active or inactive (e.g., pass `false` to list all inactive prices). + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return prices for the given currency. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return the price with these lookup_keys, if any exist. + #[serde(skip_serializing_if = "Option::is_none")] + pub lookup_keys: Option>, + + /// Only return prices for the given product. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// Only return prices with these recurring fields. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return prices of type `recurring` or `one_time`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +impl<'a> ListPrices<'a> { + pub fn new() -> Self { + ListPrices { + active: Default::default(), + created: Default::default(), + currency: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + lookup_keys: Default::default(), + product: Default::default(), + recurring: Default::default(), + starting_after: Default::default(), + type_: Default::default(), + } + } +} + +/// The parameters for `Price::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdatePrice<'a> { + /// Whether the price is currently active. + /// + /// Defaults to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A lookup key used to retrieve prices dynamically from a static string. + #[serde(skip_serializing_if = "Option::is_none")] + pub lookup_key: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// A brief description of the price, hidden from customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option<&'a str>, + + /// The recurring components of a price such as `interval` and `usage_type`. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, + + /// If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_lookup_key: Option, +} + +impl<'a> UpdatePrice<'a> { + pub fn new() -> Self { + UpdatePrice { + active: Default::default(), + expand: Default::default(), + lookup_key: Default::default(), + metadata: Default::default(), + nickname: Default::default(), + recurring: Default::default(), + transfer_lookup_key: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePriceProductData { + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + + #[serde(default)] + pub metadata: Metadata, + + pub name: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_label: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePriceRecurring { + #[serde(skip_serializing_if = "Option::is_none")] + pub aggregate_usage: Option, + + pub interval: CreatePriceRecurringInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub usage_type: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePriceTiers { + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub flat_amount_decimal: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, + + pub up_to: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreatePriceTransformQuantity { + pub divide_by: i64, + + pub round: CreatePriceTransformQuantityRound, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ListPricesRecurring { + #[serde(skip_serializing_if = "Option::is_none")] + pub interval: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub usage_type: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdatePriceRecurring { + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, +} + +/// An enum representing the possible values of an `CreatePriceRecurring`'s `aggregate_usage` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePriceRecurringAggregateUsage { + LastDuringPeriod, + LastEver, + Max, + Sum, +} + +impl CreatePriceRecurringAggregateUsage { + pub fn as_str(self) -> &'static str { + match self { + CreatePriceRecurringAggregateUsage::LastDuringPeriod => "last_during_period", + CreatePriceRecurringAggregateUsage::LastEver => "last_ever", + CreatePriceRecurringAggregateUsage::Max => "max", + CreatePriceRecurringAggregateUsage::Sum => "sum", + } + } +} + +impl AsRef for CreatePriceRecurringAggregateUsage { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePriceRecurringAggregateUsage { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreatePriceRecurring`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePriceRecurringInterval { + Day, + Month, + Week, + Year, +} + +impl CreatePriceRecurringInterval { + pub fn as_str(self) -> &'static str { + match self { + CreatePriceRecurringInterval::Day => "day", + CreatePriceRecurringInterval::Month => "month", + CreatePriceRecurringInterval::Week => "week", + CreatePriceRecurringInterval::Year => "year", + } + } +} + +impl AsRef for CreatePriceRecurringInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePriceRecurringInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreatePriceRecurring`'s `usage_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePriceRecurringUsageType { + Licensed, + Metered, +} + +impl CreatePriceRecurringUsageType { + pub fn as_str(self) -> &'static str { + match self { + CreatePriceRecurringUsageType::Licensed => "licensed", + CreatePriceRecurringUsageType::Metered => "metered", + } + } +} + +impl AsRef for CreatePriceRecurringUsageType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePriceRecurringUsageType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreatePriceTransformQuantity`'s `round` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreatePriceTransformQuantityRound { + Down, + Up, +} + +impl CreatePriceTransformQuantityRound { + pub fn as_str(self) -> &'static str { + match self { + CreatePriceTransformQuantityRound::Down => "down", + CreatePriceTransformQuantityRound::Up => "up", + } + } +} + +impl AsRef for CreatePriceTransformQuantityRound { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreatePriceTransformQuantityRound { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListPricesRecurring`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ListPricesRecurringInterval { + Day, + Month, + Week, + Year, +} + +impl ListPricesRecurringInterval { + pub fn as_str(self) -> &'static str { + match self { + ListPricesRecurringInterval::Day => "day", + ListPricesRecurringInterval::Month => "month", + ListPricesRecurringInterval::Week => "week", + ListPricesRecurringInterval::Year => "year", + } + } +} + +impl AsRef for ListPricesRecurringInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ListPricesRecurringInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListPricesRecurring`'s `usage_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ListPricesRecurringUsageType { + Licensed, + Metered, +} + +impl ListPricesRecurringUsageType { + pub fn as_str(self) -> &'static str { + match self { + ListPricesRecurringUsageType::Licensed => "licensed", + ListPricesRecurringUsageType::Metered => "metered", + } + } +} + +impl AsRef for ListPricesRecurringUsageType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ListPricesRecurringUsageType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Price`'s `billing_scheme` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PriceBillingScheme { + PerUnit, + Tiered, +} + +impl PriceBillingScheme { + pub fn as_str(self) -> &'static str { + match self { + PriceBillingScheme::PerUnit => "per_unit", + PriceBillingScheme::Tiered => "tiered", + } + } +} + +impl AsRef for PriceBillingScheme { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PriceBillingScheme { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Price`'s `tiers_mode` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PriceTiersMode { + Graduated, + Volume, +} + +impl PriceTiersMode { + pub fn as_str(self) -> &'static str { + match self { + PriceTiersMode::Graduated => "graduated", + PriceTiersMode::Volume => "volume", + } + } +} + +impl AsRef for PriceTiersMode { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PriceTiersMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Price`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PriceType { + OneTime, + Recurring, +} + +impl PriceType { + pub fn as_str(self) -> &'static str { + match self { + PriceType::OneTime => "one_time", + PriceType::Recurring => "recurring", + } + } +} + +impl AsRef for PriceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PriceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Recurring`'s `aggregate_usage` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RecurringAggregateUsage { + LastDuringPeriod, + LastEver, + Max, + Sum, +} + +impl RecurringAggregateUsage { + pub fn as_str(self) -> &'static str { + match self { + RecurringAggregateUsage::LastDuringPeriod => "last_during_period", + RecurringAggregateUsage::LastEver => "last_ever", + RecurringAggregateUsage::Max => "max", + RecurringAggregateUsage::Sum => "sum", + } + } +} + +impl AsRef for RecurringAggregateUsage { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RecurringAggregateUsage { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Recurring`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RecurringInterval { + Day, + Month, + Week, + Year, +} + +impl RecurringInterval { + pub fn as_str(self) -> &'static str { + match self { + RecurringInterval::Day => "day", + RecurringInterval::Month => "month", + RecurringInterval::Week => "week", + RecurringInterval::Year => "year", + } + } +} + +impl AsRef for RecurringInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RecurringInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Recurring`'s `usage_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RecurringUsageType { + Licensed, + Metered, +} + +impl RecurringUsageType { + pub fn as_str(self) -> &'static str { + match self { + RecurringUsageType::Licensed => "licensed", + RecurringUsageType::Metered => "metered", + } + } +} + +impl AsRef for RecurringUsageType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RecurringUsageType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `TransformQuantity`'s `round` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TransformQuantityRound { + Down, + Up, +} + +impl TransformQuantityRound { + pub fn as_str(self) -> &'static str { + match self { + TransformQuantityRound::Down => "down", + TransformQuantityRound::Up => "up", + } + } +} + +impl AsRef for TransformQuantityRound { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TransformQuantityRound { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/product.rs b/ft-stripe/src/resources/product.rs new file mode 100644 index 0000000..274e962 --- /dev/null +++ b/ft-stripe/src/resources/product.rs @@ -0,0 +1,500 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::ProductId; +use crate::params::{Deleted, Expand, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::PackageDimensions; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Product". +/// +/// For more details see [https://stripe.com/docs/api/products/object](https://stripe.com/docs/api/products/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Product { + /// Unique identifier for the object. + pub id: ProductId, + + /// Whether the product is currently available for purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A list of up to 5 attributes that each SKU can provide values for (e.g., `["color", "size"]`). + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + + /// A short one-line description of the product, meant to be displayable to the customer. + /// + /// Only applicable to products of `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub caption: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// An array of connect application identifiers that cannot purchase this product. + /// + /// Only applicable to products of `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub deactivate_on: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// The product's description, meant to be displayable to the customer. + /// + /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub images: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The product's name, meant to be displayable to the customer. + /// + /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// The dimensions of this product for shipping purposes. + /// + /// A SKU associated with this product can override this value by having its own `package_dimensions`. + /// Only applicable to products of `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// Whether this product is a shipped good. + /// + /// Only applicable to products of `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub shippable: Option, + + /// Extra information about a product which will appear on your customer's credit card statement. + /// + /// In the case that multiple products are billed at once, the first statement descriptor will be used. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// The type of the product. + /// + /// The product is either of type `good`, which is eligible for use with Orders and SKUs, or `service`, which is eligible for use with Subscriptions and Plans. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. + /// + /// When set, this will be included in associated invoice line item descriptions. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_label: Option, + + /// Time at which the object was last updated. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub updated: Option, + + /// A URL of a publicly-accessible webpage for this product. + /// + /// Only applicable to products of `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl Product { + /// Returns a list of your products. + /// + /// The products are returned sorted by creation date, with the most recently created products appearing first. + pub fn list(client: &Client, params: ListProducts<'_>) -> Response> { + client.get_query("/products", ¶ms) + } + + /// Creates a new product object. + pub fn create(client: &Client, params: CreateProduct<'_>) -> Response { + client.post_form("/products", ¶ms) + } + + /// Retrieves the details of an existing product. + /// + /// Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information. + pub fn retrieve(client: &Client, id: &ProductId, expand: &[&str]) -> Response { + client.get_query(&format!("/products/{}", id), &Expand { expand }) + } + + /// Updates the specific product by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. + pub fn update(client: &Client, id: &ProductId, params: UpdateProduct<'_>) -> Response { + client.post_form(&format!("/products/{}", id), ¶ms) + } + + /// Delete a product. + /// + /// Deleting a product with type=`good` is only possible if it has no SKUs associated with it. + /// Deleting a product with type=`service` is only possible if it has no plans associated with it. + pub fn delete(client: &Client, id: &ProductId) -> Response> { + client.delete(&format!("/products/{}", id)) + } +} + +impl Object for Product { + type Id = ProductId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "product" + } +} + +/// The parameters for `Product::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateProduct<'a> { + /// Whether the product is currently available for purchase. + /// + /// Defaults to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A list of up to 5 alphanumeric attributes. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + + /// A short one-line description of the product, meant to be displayable to the customer. + /// + /// May only be set if type=`good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub caption: Option<&'a str>, + + /// An array of Connect application names or identifiers that should not be able to order the SKUs for this product. + /// + /// May only be set if type=`good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub deactivate_on: Option>, + + /// The product's description, meant to be displayable to the customer. + /// + /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// An identifier will be randomly generated by Stripe. + /// + /// You can optionally override this ID, but the ID must be unique across all products in your Stripe account. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option<&'a str>, + + /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub images: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The product's name, meant to be displayable to the customer. + /// + /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. + pub name: &'a str, + + /// The dimensions of this product for shipping purposes. + /// + /// A SKU associated with this product can override this value by having its own `package_dimensions`. + /// May only be set if type=`good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// Whether this product is shipped (i.e., physical goods). + /// + /// Defaults to `true`. + /// May only be set if type=`good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub shippable: Option, + + /// An arbitrary string to be displayed on your customer's credit card or bank statement. + /// + /// While most banks display this information consistently, some may display it incorrectly or not at all. This may be up to 22 characters. + /// The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. + /// Non-ASCII characters are automatically stripped. It must contain at least one letter. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + + /// The type of the product. + /// + /// Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. + /// Set this parameter to `good` to use this product with Orders and SKUs. + /// On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. + /// + /// When set, this will be included in associated invoice line item descriptions. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_label: Option<&'a str>, + + /// A URL of a publicly-accessible webpage for this product. + /// + /// May only be set if type=`good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option<&'a str>, +} + +impl<'a> CreateProduct<'a> { + pub fn new(name: &'a str) -> Self { + CreateProduct { + active: Default::default(), + attributes: Default::default(), + caption: Default::default(), + deactivate_on: Default::default(), + description: Default::default(), + expand: Default::default(), + id: Default::default(), + images: Default::default(), + metadata: Default::default(), + name, + package_dimensions: Default::default(), + shippable: Default::default(), + statement_descriptor: Default::default(), + type_: Default::default(), + unit_label: Default::default(), + url: Default::default(), + } + } +} + +/// The parameters for `Product::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListProducts<'a> { + /// Only return products that are active or inactive (e.g., pass `false` to list all inactive products). + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Only return products that were created during the given date interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Only return products with the given IDs. + #[serde(skip_serializing_if = "Option::is_none")] + pub ids: Option>, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return products that can be shipped (i.e., physical, not digital products). + #[serde(skip_serializing_if = "Option::is_none")] + pub shippable: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return products of this type. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// Only return products with the given url. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option<&'a str>, +} + +impl<'a> ListProducts<'a> { + pub fn new() -> Self { + ListProducts { + active: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + ids: Default::default(), + limit: Default::default(), + shippable: Default::default(), + starting_after: Default::default(), + type_: Default::default(), + url: Default::default(), + } + } +} + +/// The parameters for `Product::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateProduct<'a> { + /// Whether the product is available for purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A list of up to 5 alphanumeric attributes that each SKU can provide values for (e.g., `["color", "size"]`). + /// + /// If a value for `attributes` is specified, the list specified will replace the existing attributes list on this product. + /// Any attributes not present after the update will be deleted from the SKUs for this product. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + + /// A short one-line description of the product, meant to be displayable to the customer. + /// + /// May only be set if `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub caption: Option<&'a str>, + + /// An array of Connect application names or identifiers that should not be able to order the SKUs for this product. + /// + /// May only be set if `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub deactivate_on: Option>, + + /// The product's description, meant to be displayable to the customer. + /// + /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub images: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The product's name, meant to be displayable to the customer. + /// + /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + + /// The dimensions of this product for shipping purposes. + /// + /// A SKU associated with this product can override this value by having its own `package_dimensions`. + /// May only be set if `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// Whether this product is shipped (i.e., physical goods). + /// + /// Defaults to `true`. + /// May only be set if `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub shippable: Option, + + /// An arbitrary string to be displayed on your customer's credit card or bank statement. + /// + /// While most banks display this information consistently, some may display it incorrectly or not at all. This may be up to 22 characters. + /// The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. + /// Non-ASCII characters are automatically stripped. It must contain at least one letter. + /// May only be set if `type=service`. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + + /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. + /// + /// When set, this will be included in associated invoice line item descriptions. + /// May only be set if `type=service`. + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_label: Option<&'a str>, + + /// A URL of a publicly-accessible webpage for this product. + /// + /// May only be set if `type=good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option<&'a str>, +} + +impl<'a> UpdateProduct<'a> { + pub fn new() -> Self { + UpdateProduct { + active: Default::default(), + attributes: Default::default(), + caption: Default::default(), + deactivate_on: Default::default(), + description: Default::default(), + expand: Default::default(), + images: Default::default(), + metadata: Default::default(), + name: Default::default(), + package_dimensions: Default::default(), + shippable: Default::default(), + statement_descriptor: Default::default(), + unit_label: Default::default(), + url: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Product`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ProductType { + Good, + Service, +} + +impl ProductType { + pub fn as_str(self) -> &'static str { + match self { + ProductType::Good => "good", + ProductType::Service => "service", + } + } +} + +impl AsRef for ProductType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ProductType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/recipient.rs b/ft-stripe/src/resources/recipient.rs new file mode 100644 index 0000000..564d335 --- /dev/null +++ b/ft-stripe/src/resources/recipient.rs @@ -0,0 +1,325 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::RecipientId; +use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{Account, BankAccount, Card}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "TransferRecipient". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Recipient { + /// Unique identifier for the object. + pub id: RecipientId, + + /// Hash describing the current account on the recipient, if there is one. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_account: Option, + + #[serde(default)] + pub cards: List, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// The default card to use for creating transfers to this recipient. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_card: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The ID of the [Custom account](https://stripe.com/docs/connect/custom-accounts) this recipient was migrated to. + /// + /// If set, the recipient can no longer be updated, nor can transfers be made to it: use the Custom account instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub migrated_to: Option>, + + /// Full, legal name of the recipient. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub rolled_back_from: Option>, + + /// Type of the recipient, one of `individual` or `corporation`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +impl Recipient { + /// Returns a list of your recipients. + /// + /// The recipients are returned sorted by creation date, with the most recently created recipients appearing first. + pub fn list(client: &Client, params: ListRecipients<'_>) -> Response> { + client.get_query("/recipients", ¶ms) + } + + /// Creates a new `Recipient` object and verifies the recipient’s identity. + /// Also verifies the recipient’s bank account information or debit card, if either is provided. + pub fn create(client: &Client, params: CreateRecipient<'_>) -> Response { + client.post_form("/recipients", ¶ms) + } + + /// Retrieves the details of an existing recipient. + /// + /// You need only supply the unique recipient identifier that was returned upon recipient creation. + pub fn retrieve(client: &Client, id: &RecipientId, expand: &[&str]) -> Response { + client.get_query(&format!("/recipients/{}", id), &Expand { expand }) + } + + /// Updates the specified recipient by setting the values of the parameters passed. + /// Any parameters not provided will be left unchanged. + /// + /// If you update the name or tax ID, the identity verification will automatically be rerun. + /// If you update the bank account, the bank account validation will automatically be rerun. + pub fn update( + client: &Client, + id: &RecipientId, + params: UpdateRecipient<'_>, + ) -> Response { + client.post_form(&format!("/recipients/{}", id), ¶ms) + } + + /// Permanently deletes a recipient. + /// + /// It cannot be undone. + pub fn delete(client: &Client, id: &RecipientId) -> Response> { + client.delete(&format!("/recipients/{}", id)) + } +} + +impl Object for Recipient { + type Id = RecipientId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "recipient" + } +} + +/// The parameters for `Recipient::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateRecipient<'a> { + /// An arbitrary string which you can attach to a `Recipient` object. + /// + /// It is displayed alongside the recipient in the web interface. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The recipient's email address. + /// + /// It is displayed alongside the recipient in the web interface, and can be useful for searching and tracking. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The recipient's full, legal name. + /// + /// For type `individual`, should be in the format `First Last`, `First Middle Last`, or `First M Last` (no prefixes or suffixes). + /// For `corporation`, the full, incorporated name. + pub name: &'a str, + + /// The recipient's tax ID, as a string. + /// + /// For type `individual`, the full SSN; for type `corporation`, the full EIN. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id: Option<&'a str>, + + /// Type of the recipient: either `individual` or `corporation`. + #[serde(rename = "type")] + pub type_: RecipientType, +} + +impl<'a> CreateRecipient<'a> { + pub fn new(name: &'a str, type_: RecipientType) -> Self { + CreateRecipient { + description: Default::default(), + email: Default::default(), + expand: Default::default(), + metadata: Default::default(), + name, + tax_id: Default::default(), + type_, + } + } +} + +/// The parameters for `Recipient::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListRecipients<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// Only return recipients that are verified or unverified. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified: Option, +} + +impl<'a> ListRecipients<'a> { + pub fn new() -> Self { + ListRecipients { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + type_: Default::default(), + verified: Default::default(), + } + } +} + +/// The parameters for `Recipient::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateRecipient<'a> { + /// ID of the card to set as the recipient's new default for payouts. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_card: Option<&'a str>, + + /// An arbitrary string which you can attach to a `Recipient` object. + /// + /// It is displayed alongside the recipient in the web interface. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The recipient's email address. + /// + /// It is displayed alongside the recipient in the web interface, and can be useful for searching and tracking. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The recipient's full, legal name. + /// + /// For type `individual`, should be in the format `First Last`, `First Middle Last`, or `First M Last` (no prefixes or suffixes). + /// For `corporation`, the full, incorporated name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + + /// The recipient's tax ID, as a string. + /// + /// For type `individual`, the full SSN; for type `corporation`, the full EIN. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_id: Option<&'a str>, +} + +impl<'a> UpdateRecipient<'a> { + pub fn new() -> Self { + UpdateRecipient { + default_card: Default::default(), + description: Default::default(), + email: Default::default(), + expand: Default::default(), + metadata: Default::default(), + name: Default::default(), + tax_id: Default::default(), + } + } +} + +/// An enum representing the possible values of an `ListRecipients`'s `type_` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RecipientType { + Corporation, + Individual, +} + +impl RecipientType { + pub fn as_str(self) -> &'static str { + match self { + RecipientType::Corporation => "corporation", + RecipientType::Individual => "individual", + } + } +} + +impl AsRef for RecipientType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RecipientType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/refund.rs b/ft-stripe/src/resources/refund.rs new file mode 100644 index 0000000..686ad96 --- /dev/null +++ b/ft-stripe/src/resources/refund.rs @@ -0,0 +1,286 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ChargeId, PaymentIntentId, RefundId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{BalanceTransaction, Charge, Currency, PaymentIntent, TransferReversal}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Refund". +/// +/// For more details see [https://stripe.com/docs/api/refunds/object](https://stripe.com/docs/api/refunds/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Refund { + /// Unique identifier for the object. + pub id: RefundId, + + /// Amount, in %s. + pub amount: i64, + + /// Balance transaction that describes the impact on your account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// ID of the charge that was refunded. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + /// (Available on non-card refunds only). + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// If the refund failed, this balance transaction describes the adjustment made on your account balance that reverses the initial balance transaction. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_balance_transaction: Option>, + + /// If the refund failed, the reason for refund failure if known. + /// + /// Possible values are `lost_or_stolen_card`, `expired_or_canceled_card`, or `unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// ID of the PaymentIntent that was refunded. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// Reason for the refund, either user-provided (`duplicate`, `fraudulent`, or `requested_by_customer`) or generated by Stripe internally (`expired_uncaptured_charge`). + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + + /// This is the transaction number that appears on email receipts sent for this refund. + #[serde(skip_serializing_if = "Option::is_none")] + pub receipt_number: Option, + + /// The transfer reversal that is associated with the refund. + /// + /// Only present if the charge came from another Stripe account. + /// See the Connect documentation for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_transfer_reversal: Option>, + + /// Status of the refund. + /// + /// For credit card refunds, this can be `pending`, `succeeded`, or `failed`. + /// For other types of refunds, it can be `pending`, `succeeded`, `failed`, or `canceled`. + /// Refer to our [refunds](https://stripe.com/docs/refunds#failed-refunds) documentation for more details. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + /// If the accompanying transfer was reversed, the transfer reversal object. + /// + /// Only applicable if the charge was created using the destination parameter. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_reversal: Option>, +} + +impl Refund { + /// Returns a list of all refunds you’ve previously created. + /// + /// The refunds are returned in sorted order, with the most recent refunds appearing first. + /// For convenience, the 10 most recent refunds are always available by default on the charge object. + pub fn list(client: &Client, params: ListRefunds<'_>) -> Response> { + client.get_query("/refunds", ¶ms) + } + + /// Create a refund. + pub fn create(client: &Client, params: CreateRefund<'_>) -> Response { + client.post_form("/refunds", ¶ms) + } + + /// Retrieves the details of an existing refund. + pub fn retrieve(client: &Client, id: &RefundId, expand: &[&str]) -> Response { + client.get_query(&format!("/refunds/{}", id), &Expand { expand }) + } + + /// Updates the specified refund by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. This request only accepts `metadata` as an argument. + pub fn update(client: &Client, id: &RefundId, params: UpdateRefund<'_>) -> Response { + client.post_form(&format!("/refunds/{}", id), ¶ms) + } +} + +impl Object for Refund { + type Id = RefundId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "refund" + } +} + +/// The parameters for `Refund::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateRefund<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_application_fee: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub reverse_transfer: Option, +} + +impl<'a> CreateRefund<'a> { + pub fn new() -> Self { + CreateRefund { + amount: Default::default(), + charge: Default::default(), + expand: Default::default(), + metadata: Default::default(), + payment_intent: Default::default(), + reason: Default::default(), + refund_application_fee: Default::default(), + reverse_transfer: Default::default(), + } + } +} + +/// The parameters for `Refund::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListRefunds<'a> { + /// Only return refunds for the charge specified by this charge ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return refunds for the PaymentIntent specified by this ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListRefunds<'a> { + pub fn new() -> Self { + ListRefunds { + charge: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + payment_intent: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Refund::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateRefund<'a> { + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdateRefund<'a> { + pub fn new() -> Self { + UpdateRefund { expand: Default::default(), metadata: Default::default() } + } +} + +/// An enum representing the possible values of an `CreateRefund`'s `reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum RefundReason { + Duplicate, + Fraudulent, + RequestedByCustomer, +} + +impl RefundReason { + pub fn as_str(self) -> &'static str { + match self { + RefundReason::Duplicate => "duplicate", + RefundReason::Fraudulent => "fraudulent", + RefundReason::RequestedByCustomer => "requested_by_customer", + } + } +} + +impl AsRef for RefundReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for RefundReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/reserve_transaction.rs b/ft-stripe/src/resources/reserve_transaction.rs new file mode 100644 index 0000000..388503e --- /dev/null +++ b/ft-stripe/src/resources/reserve_transaction.rs @@ -0,0 +1,32 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::Object; +use crate::resources::Currency; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "ReserveTransaction". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ReserveTransaction { + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +impl Object for ReserveTransaction { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "reserve_transaction" + } +} diff --git a/ft-stripe/src/resources/review.rs b/ft-stripe/src/resources/review.rs new file mode 100644 index 0000000..9de8467 --- /dev/null +++ b/ft-stripe/src/resources/review.rs @@ -0,0 +1,240 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::ReviewId; +use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; +use crate::resources::{Charge, PaymentIntent, ReviewReason}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "RadarReview". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Review { + /// Unique identifier for the object. + pub id: ReviewId, + + /// The ZIP or postal code of the card used, if applicable. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_zip: Option, + + /// The charge associated with this review. + #[serde(skip_serializing_if = "Option::is_none")] + pub charge: Option>, + + /// The reason the review was closed, or null if it has not yet been closed. + /// + /// One of `approved`, `refunded`, `refunded_as_fraud`, or `disputed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub closed_reason: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// The IP address where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub ip_address: Option, + + /// Information related to the location of the payment. + /// + /// Note that this information is an approximation and attempts to locate the nearest population center - it should not be used to determine a specific address. + #[serde(skip_serializing_if = "Option::is_none")] + pub ip_address_location: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// If `true`, the review needs action. + pub open: bool, + + /// The reason the review was opened. + /// + /// One of `rule` or `manual`. + pub opened_reason: ReviewOpenedReason, + + /// The PaymentIntent ID associated with this review, if one exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_intent: Option>, + + /// The reason the review is currently open or closed. + /// + /// One of `rule`, `manual`, `approved`, `refunded`, `refunded_as_fraud`, or `disputed`. + pub reason: ReviewReason, + + /// Information related to the browsing session of the user who initiated the payment. + #[serde(skip_serializing_if = "Option::is_none")] + pub session: Option, +} + +impl Review { + /// Returns a list of `Review` objects that have `open` set to `true`. + /// + /// The objects are sorted in descending order by creation date, with the most recently created object appearing first. + pub fn list(client: &Client, params: ListReviews<'_>) -> Response> { + client.get_query("/reviews", ¶ms) + } + + /// Retrieves a `Review` object. + pub fn retrieve(client: &Client, id: &ReviewId, expand: &[&str]) -> Response { + client.get_query(&format!("/reviews/{}", id), &Expand { expand }) + } +} + +impl Object for Review { + type Id = ReviewId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "review" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct RadarReviewResourceLocation { + /// The city where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option, + + /// Two-letter ISO code representing the country where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// The geographic latitude where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub latitude: Option, + + /// The geographic longitude where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub longitude: Option, + + /// The state/county/province/region where the payment originated. + #[serde(skip_serializing_if = "Option::is_none")] + pub region: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct RadarReviewResourceSession { + /// The browser used in this browser session (e.g., `Chrome`). + #[serde(skip_serializing_if = "Option::is_none")] + pub browser: Option, + + /// Information about the device used for the browser session (e.g., `Samsung SM-G930T`). + #[serde(skip_serializing_if = "Option::is_none")] + pub device: Option, + + /// The platform for the browser session (e.g., `Macintosh`). + #[serde(skip_serializing_if = "Option::is_none")] + pub platform: Option, + + /// The version for the browser session (e.g., `61.0.3163.100`). + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +/// The parameters for `Review::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListReviews<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListReviews<'a> { + pub fn new() -> Self { + ListReviews { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Review`'s `closed_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ReviewClosedReason { + Approved, + Disputed, + Refunded, + RefundedAsFraud, +} + +impl ReviewClosedReason { + pub fn as_str(self) -> &'static str { + match self { + ReviewClosedReason::Approved => "approved", + ReviewClosedReason::Disputed => "disputed", + ReviewClosedReason::Refunded => "refunded", + ReviewClosedReason::RefundedAsFraud => "refunded_as_fraud", + } + } +} + +impl AsRef for ReviewClosedReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ReviewClosedReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Review`'s `opened_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ReviewOpenedReason { + Manual, + Rule, +} + +impl ReviewOpenedReason { + pub fn as_str(self) -> &'static str { + match self { + ReviewOpenedReason::Manual => "manual", + ReviewOpenedReason::Rule => "rule", + } + } +} + +impl AsRef for ReviewOpenedReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ReviewOpenedReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/review_ext.rs b/ft-stripe/src/resources/review_ext.rs new file mode 100644 index 0000000..440b029 --- /dev/null +++ b/ft-stripe/src/resources/review_ext.rs @@ -0,0 +1,38 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `Review`'s `reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ReviewReason { + Approved, + Disputed, + Manual, + Refunded, + RefundedAsFraud, + Rule, +} + +impl ReviewReason { + pub fn as_str(self) -> &'static str { + match self { + ReviewReason::Approved => "approved", + ReviewReason::Disputed => "disputed", + ReviewReason::Manual => "manual", + ReviewReason::Refunded => "refunded", + ReviewReason::RefundedAsFraud => "refunded_as_fraud", + ReviewReason::Rule => "rule", + } + } +} + +impl AsRef for ReviewReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ReviewReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/scheduled_query_run.rs b/ft-stripe/src/resources/scheduled_query_run.rs new file mode 100644 index 0000000..bee2ca4 --- /dev/null +++ b/ft-stripe/src/resources/scheduled_query_run.rs @@ -0,0 +1,61 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::ScheduledQueryRunId; +use crate::params::{Object, Timestamp}; +use crate::resources::File; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "ScheduledQueryRun". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ScheduledQueryRun { + /// Unique identifier for the object. + pub id: ScheduledQueryRunId, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// When the query was run, Sigma contained a snapshot of your Stripe data at this time. + pub data_load_time: Timestamp, + + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + + /// The file object representing the results of the query. + #[serde(skip_serializing_if = "Option::is_none")] + pub file: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Time at which the result expires and is no longer available for download. + pub result_available_until: Timestamp, + + /// SQL for the query. + pub sql: String, + + /// The query's execution status, which will be `completed` for successful runs, and `canceled`, `failed`, or `timed_out` otherwise. + pub status: String, + + /// Title of the query. + pub title: String, +} + +impl Object for ScheduledQueryRun { + type Id = ScheduledQueryRunId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "scheduled_query_run" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SigmaScheduledQueryRunError { + /// Information about the run failure. + pub message: String, +} diff --git a/ft-stripe/src/resources/setup_intent.rs b/ft-stripe/src/resources/setup_intent.rs new file mode 100644 index 0000000..2904dcf --- /dev/null +++ b/ft-stripe/src/resources/setup_intent.rs @@ -0,0 +1,654 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, PaymentMethodId, SetupIntentId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + Account, ApiErrors, Application, Currency, Customer, Mandate, PaymentMethod, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "SetupIntent". +/// +/// For more details see [https://stripe.com/docs/api/setup_intents/object](https://stripe.com/docs/api/setup_intents/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SetupIntent { + /// Unique identifier for the object. + pub id: SetupIntentId, + + /// ID of the Connect application that created the SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option>, + + /// Reason for cancellation of this SetupIntent, one of `abandoned`, `requested_by_customer`, or `duplicate`. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellation_reason: Option, + + /// The client secret of this SetupIntent. + /// + /// Used for client-side retrieval using a publishable key. The client secret can be used to complete payment setup from your frontend. + /// It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer. + /// Make sure that you have TLS enabled on any page that includes the client secret. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// ID of the Customer this SetupIntent belongs to, if one exists. + /// + /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. + /// + /// Payment methods attached to other Customers cannot be used with this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The error encountered in the previous SetupIntent confirmation. + #[serde(skip_serializing_if = "Option::is_none")] + pub last_setup_error: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// ID of the multi use Mandate generated by the SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// If present, this property tells you what actions you need to take in order for your customer to continue payment setup. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_action: Option, + + /// The account (if any) for which the setup is intended. + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option>, + + /// ID of the payment method used with this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option>, + + /// Payment-method-specific configuration for this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_options: Option, + + /// The list of payment method types (e.g. + /// + /// card) that this SetupIntent is allowed to set up. + pub payment_method_types: Vec, + + /// ID of the single_use Mandate generated by the SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub single_use_mandate: Option>, + + /// [Status](https://stripe.com/docs/payments/intents#intent-statuses) of this SetupIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `canceled`, or `succeeded`. + pub status: SetupIntentStatus, + + /// Indicates how the payment method is intended to be used in the future. + /// + /// Use `on_session` if you intend to only reuse the payment method when the customer is in your checkout flow. + /// + /// Use `off_session` if your customer may or may not be in your checkout flow. + /// If not provided, this value defaults to `off_session`. + pub usage: String, +} + +impl SetupIntent { + /// Returns a list of SetupIntents. + pub fn list(client: &Client, params: ListSetupIntents<'_>) -> Response> { + client.get_query("/setup_intents", ¶ms) + } + + /// Creates a SetupIntent object. + /// + /// After the SetupIntent is created, attach a payment method and [confirm](https://stripe.com/docs/api/setup_intents/confirm) + /// to collect any required permissions to charge the payment method later. + pub fn create(client: &Client, params: CreateSetupIntent<'_>) -> Response { + client.post_form("/setup_intents", ¶ms) + } + + /// Retrieves the details of a SetupIntent that has previously been created. + /// + /// Client-side retrieval using a publishable key is allowed when the `client_secret` is provided in the query string. + /// When retrieved with a publishable key, only a subset of properties will be returned. + /// Please refer to the [SetupIntent](https://stripe.com/docs/api#setup_intent_object) object reference for more details. + pub fn retrieve(client: &Client, id: &SetupIntentId, expand: &[&str]) -> Response { + client.get_query(&format!("/setup_intents/{}", id), &Expand { expand }) + } + + /// Updates a SetupIntent object. + pub fn update( + client: &Client, + id: &SetupIntentId, + params: UpdateSetupIntent<'_>, + ) -> Response { + client.post_form(&format!("/setup_intents/{}", id), ¶ms) + } +} + +impl Object for SetupIntent { + type Id = SetupIntentId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "setup_intent" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SetupIntentNextAction { + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_to_url: Option, + + /// Type of the next action to perform, one of `redirect_to_url` or `use_stripe_sdk`. + #[serde(rename = "type")] + pub type_: String, + + /// When confirming a SetupIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. + /// + /// The shape of the contents is subject to change and is only intended to be used by Stripe.js. + #[serde(skip_serializing_if = "Option::is_none")] + pub use_stripe_sdk: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SetupIntentNextActionRedirectToUrl { + /// If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. + #[serde(skip_serializing_if = "Option::is_none")] + pub return_url: Option, + + /// The URL you must redirect your customer to in order to authenticate. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SetupIntentPaymentMethodOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SetupIntentPaymentMethodOptionsCard { + /// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). + /// + /// However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. + /// Permitted values include: `automatic` or `any`. + /// If not provided, defaults to `automatic`. + /// Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_three_d_secure: Option, +} + +/// The parameters for `SetupIntent::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateSetupIntent<'a> { + /// Set to `true` to attempt to confirm this SetupIntent immediately. + /// + /// This parameter defaults to `false`. + /// If the payment method attached is a card, a return_url may be provided in case additional authentication is required. + #[serde(skip_serializing_if = "Option::is_none")] + pub confirm: Option, + + /// ID of the Customer this SetupIntent belongs to, if one exists. + /// + /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. + /// + /// Payment methods attached to other Customers cannot be used with this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// This hash contains details about the Mandate to create. + /// + /// This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate_data: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The Stripe account ID for which this SetupIntent is created. + #[serde(skip_serializing_if = "Option::is_none")] + pub on_behalf_of: Option<&'a str>, + + /// ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// Payment-method-specific configuration for this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_options: Option, + + /// The list of payment method types (e.g. + /// + /// card) that this SetupIntent is allowed to use. + /// If this is not provided, defaults to ["card"]. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_types: Option>, + + /// The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. + /// + /// If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. + /// This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). + #[serde(skip_serializing_if = "Option::is_none")] + pub return_url: Option<&'a str>, + + /// If this hash is populated, this SetupIntent will generate a single_use Mandate on success. + #[serde(skip_serializing_if = "Option::is_none")] + pub single_use: Option, +} + +impl<'a> CreateSetupIntent<'a> { + pub fn new() -> Self { + CreateSetupIntent { + confirm: Default::default(), + customer: Default::default(), + description: Default::default(), + expand: Default::default(), + mandate_data: Default::default(), + metadata: Default::default(), + on_behalf_of: Default::default(), + payment_method: Default::default(), + payment_method_options: Default::default(), + payment_method_types: Default::default(), + return_url: Default::default(), + single_use: Default::default(), + } + } +} + +/// The parameters for `SetupIntent::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListSetupIntents<'a> { + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return SetupIntents for the customer specified by this customer ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return SetupIntents associated with the specified payment method. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListSetupIntents<'a> { + pub fn new() -> Self { + ListSetupIntents { + created: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + payment_method: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `SetupIntent::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSetupIntent<'a> { + /// ID of the Customer this SetupIntent belongs to, if one exists. + /// + /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. + /// + /// Payment methods attached to other Customers cannot be used with this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method: Option, + + /// Payment-method-specific configuration for this SetupIntent. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_options: Option, + + /// The list of payment method types (e.g. + /// + /// card) that this SetupIntent is allowed to set up. + /// If this is not provided, defaults to ["card"]. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_types: Option>, +} + +impl<'a> UpdateSetupIntent<'a> { + pub fn new() -> Self { + UpdateSetupIntent { + customer: Default::default(), + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + payment_method: Default::default(), + payment_method_options: Default::default(), + payment_method_types: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentMandateData { + pub customer_acceptance: CreateSetupIntentMandateDataCustomerAcceptance, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentPaymentMethodOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentSingleUse { + pub amount: i64, + + pub currency: Currency, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSetupIntentPaymentMethodOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentMandateDataCustomerAcceptance { + #[serde(skip_serializing_if = "Option::is_none")] + pub accepted_at: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub offline: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub online: Option, + + #[serde(rename = "type")] + pub type_: CreateSetupIntentMandateDataCustomerAcceptanceType, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentPaymentMethodOptionsCard { + #[serde(skip_serializing_if = "Option::is_none")] + pub request_three_d_secure: + Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSetupIntentPaymentMethodOptionsCard { + #[serde(skip_serializing_if = "Option::is_none")] + pub request_three_d_secure: + Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentMandateDataCustomerAcceptanceOffline {} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSetupIntentMandateDataCustomerAcceptanceOnline { + pub ip_address: String, + + pub user_agent: String, +} + +/// An enum representing the possible values of an `CreateSetupIntentMandateDataCustomerAcceptance`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreateSetupIntentMandateDataCustomerAcceptanceType { + Offline, + Online, +} + +impl CreateSetupIntentMandateDataCustomerAcceptanceType { + pub fn as_str(self) -> &'static str { + match self { + CreateSetupIntentMandateDataCustomerAcceptanceType::Offline => "offline", + CreateSetupIntentMandateDataCustomerAcceptanceType::Online => "online", + } + } +} + +impl AsRef for CreateSetupIntentMandateDataCustomerAcceptanceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreateSetupIntentMandateDataCustomerAcceptanceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + Any, + Automatic, +} + +impl CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + pub fn as_str(self) -> &'static str { + match self { + CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", + CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", + } + } +} + +impl AsRef for CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SetupIntent`'s `cancellation_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SetupIntentCancellationReason { + Abandoned, + Duplicate, + RequestedByCustomer, +} + +impl SetupIntentCancellationReason { + pub fn as_str(self) -> &'static str { + match self { + SetupIntentCancellationReason::Abandoned => "abandoned", + SetupIntentCancellationReason::Duplicate => "duplicate", + SetupIntentCancellationReason::RequestedByCustomer => "requested_by_customer", + } + } +} + +impl AsRef for SetupIntentCancellationReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SetupIntentCancellationReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + Any, + Automatic, + ChallengeOnly, +} + +impl SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + pub fn as_str(self) -> &'static str { + match self { + SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", + SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", + SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::ChallengeOnly => { + "challenge_only" + } + } + } +} + +impl AsRef for SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SetupIntent`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SetupIntentStatus { + Canceled, + Processing, + RequiresAction, + RequiresConfirmation, + RequiresPaymentMethod, + Succeeded, +} + +impl SetupIntentStatus { + pub fn as_str(self) -> &'static str { + match self { + SetupIntentStatus::Canceled => "canceled", + SetupIntentStatus::Processing => "processing", + SetupIntentStatus::RequiresAction => "requires_action", + SetupIntentStatus::RequiresConfirmation => "requires_confirmation", + SetupIntentStatus::RequiresPaymentMethod => "requires_payment_method", + SetupIntentStatus::Succeeded => "succeeded", + } + } +} + +impl AsRef for SetupIntentStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SetupIntentStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `UpdateSetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + Any, + Automatic, +} + +impl UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + pub fn as_str(self) -> &'static str { + match self { + UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", + UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", + } + } +} + +impl AsRef for UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/sku.rs b/ft-stripe/src/resources/sku.rs new file mode 100644 index 0000000..d2f9b02 --- /dev/null +++ b/ft-stripe/src/resources/sku.rs @@ -0,0 +1,374 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::SkuId; +use crate::params::{Deleted, Expand, Expandable, IdOrCreate, List, Metadata, Object, Timestamp}; +use crate::resources::{CreateProduct, Currency, PackageDimensions, Product}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "SKU". +/// +/// For more details see [https://stripe.com/docs/api/skus/object](https://stripe.com/docs/api/skus/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Sku { + /// Unique identifier for the object. + pub id: SkuId, + + /// Whether the SKU is available for purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A dictionary of attributes and values for the attributes defined by the product. + /// + /// If, for example, a product's attributes are `["size", "gender"]`, a valid SKU has the following dictionary of attributes: `{"size": "Medium", "gender": "Unisex"}`. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// The URL of an image for this SKU, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub inventory: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The dimensions of this SKU for shipping purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// The ID of the product this SKU is associated with. + /// + /// The product must be currently active. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>, + + /// Time at which the object was last updated. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub updated: Option, +} + +impl Sku { + /// Returns a list of your SKUs. + /// + /// The SKUs are returned sorted by creation date, with the most recently created SKUs appearing first. + pub fn list(client: &Client, params: ListSkus<'_>) -> Response> { + client.get_query("/skus", ¶ms) + } + + /// Creates a new SKU associated with a product. + pub fn create(client: &Client, params: CreateSku<'_>) -> Response { + client.post_form("/skus", ¶ms) + } + + /// Retrieves the details of an existing SKU. + /// + /// Supply the unique SKU identifier from either a SKU creation request or from the product, and Stripe will return the corresponding SKU information. + pub fn retrieve(client: &Client, id: &SkuId, expand: &[&str]) -> Response { + client.get_query(&format!("/skus/{}", id), &Expand { expand }) + } + + /// Updates the specific SKU by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. Note that a SKU’s `attributes` are not editable. + /// Instead, you would need to deactivate the existing SKU and create a new one with the new attribute values. + pub fn update(client: &Client, id: &SkuId, params: UpdateSku<'_>) -> Response { + client.post_form(&format!("/skus/{}", id), ¶ms) + } + + /// Delete a SKU. + /// + /// Deleting a SKU is only possible until it has been used in an order. + pub fn delete(client: &Client, id: &SkuId) -> Response> { + client.delete(&format!("/skus/{}", id)) + } +} + +impl Object for Sku { + type Id = SkuId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "sku" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Inventory { + /// The count of inventory available. + /// + /// Will be present if and only if `type` is `finite`. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// Inventory type. + /// + /// Possible values are `finite`, `bucket` (not quantified), and `infinite`. + #[serde(rename = "type")] + pub type_: String, + + /// An indicator of the inventory available. + /// + /// Possible values are `in_stock`, `limited`, and `out_of_stock`. + /// Will be present if and only if `type` is `bucket`. + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +/// The parameters for `Sku::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateSku<'a> { + /// Whether the SKU is available for purchase. + /// + /// Default to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A dictionary of attributes and values for the attributes defined by the product. + /// + /// If, for example, a product's attributes are `["size", "gender"]`, a valid SKU has the following dictionary of attributes: `{"size": "Medium", "gender": "Unisex"}`. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The identifier for the SKU. + /// + /// Must be unique. + /// If not provided, an identifier will be randomly generated. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option<&'a str>, + + /// The URL of an image for this SKU, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option<&'a str>, + + /// Description of the SKU's inventory. + #[serde(skip_serializing_if = "Option::is_none")] + pub inventory: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The dimensions of this SKU for shipping purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). + pub price: i64, + + /// The ID of the product this SKU is associated with. + /// + /// Must be a product with type `good`. + pub product: IdOrCreate<'a, CreateProduct<'a>>, +} + +impl<'a> CreateSku<'a> { + pub fn new( + currency: Currency, + inventory: Option, + price: i64, + product: IdOrCreate<'a, CreateProduct<'a>>, + ) -> Self { + CreateSku { + active: Default::default(), + attributes: Default::default(), + currency, + expand: Default::default(), + id: Default::default(), + image: Default::default(), + inventory, + metadata: Default::default(), + package_dimensions: Default::default(), + price, + product, + } + } +} + +/// The parameters for `Sku::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListSkus<'a> { + /// Only return SKUs that are active or inactive (e.g., pass `false` to list all inactive products). + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Only return SKUs that have the specified key-value pairs in this partially constructed dictionary. + /// + /// Can be specified only if `product` is also supplied. + /// For instance, if the associated product has attributes `["color", "size"]`, passing in `attributes[color]=red` returns all the SKUs for this product that have `color` set to `red`. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Only return SKUs with the given IDs. + #[serde(skip_serializing_if = "Option::is_none")] + pub ids: Option>, + + /// Only return SKUs that are either in stock or out of stock (e.g., pass `false` to list all SKUs that are out of stock). + /// + /// If no value is provided, all SKUs are returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub in_stock: Option, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// The ID of the product whose SKUs will be retrieved. + /// + /// Must be a product with type `good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListSkus<'a> { + pub fn new() -> Self { + ListSkus { + active: Default::default(), + attributes: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + ids: Default::default(), + in_stock: Default::default(), + limit: Default::default(), + product: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `Sku::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSku<'a> { + /// Whether this SKU is available for purchase. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// A dictionary of attributes and values for the attributes defined by the product. + /// + /// When specified, `attributes` will partially update the existing attributes dictionary on the product, with the postcondition that a value must be present for each attribute key on the product. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The URL of an image for this SKU, meant to be displayable to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option<&'a str>, + + /// Description of the SKU's inventory. + #[serde(skip_serializing_if = "Option::is_none")] + pub inventory: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The dimensions of this SKU for shipping purposes. + #[serde(skip_serializing_if = "Option::is_none")] + pub package_dimensions: Option, + + /// The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// The ID of the product that this SKU should belong to. + /// + /// The product must exist, have the same set of attribute names as the SKU's current product, and be of type `good`. + #[serde(skip_serializing_if = "Option::is_none")] + pub product: Option>>, +} + +impl<'a> UpdateSku<'a> { + pub fn new() -> Self { + UpdateSku { + active: Default::default(), + attributes: Default::default(), + currency: Default::default(), + expand: Default::default(), + image: Default::default(), + inventory: Default::default(), + metadata: Default::default(), + package_dimensions: Default::default(), + price: Default::default(), + product: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/source.rs b/ft-stripe/src/resources/source.rs new file mode 100644 index 0000000..e6a5905 --- /dev/null +++ b/ft-stripe/src/resources/source.rs @@ -0,0 +1,1511 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, SourceId, TokenId}; +use crate::params::{Expand, Metadata, Object, Timestamp}; +use crate::resources::{ + Address, BillingDetails, Currency, Shipping, SourceRedirectFlowFailureReason, + SourceRedirectFlowStatus, SourceStatus, SourceUsage, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Source". +/// +/// For more details see [https://stripe.com/docs/api/sources/object](https://stripe.com/docs/api/sources/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Source { + /// Unique identifier for the object. + pub id: SourceId, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ach_credit_transfer: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ach_debit: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub alipay: Option, + + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount associated with the source. + /// + /// This is the amount for which the source will be chargeable once ready. + /// Required for `single_use` sources. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub au_becs_debit: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bancontact: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card_present: Option, + + /// The client secret of the source. + /// + /// Used for client-side retrieval using a publishable key. + pub client_secret: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub code_verification: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. + /// + /// This is the currency for which the source will be chargeable once ready. + /// Required for `single_use` sources. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The ID of the customer to which this source is attached. + /// + /// This will not be present when the source has not been attached to a customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub eps: Option, + + /// The authentication `flow` of the source. + /// + /// `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. + pub flow: SourceFlow, + + #[serde(skip_serializing_if = "Option::is_none")] + pub giropay: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ideal: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub klarna: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub multibanco: Option, + + /// Information about the owner of the payment instrument that may be used or required by particular source types. + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub p24: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub receiver: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sepa_debit: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sofort: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub source_order: Option, + + /// Extra information about a source. + /// + /// This will appear on your customer's statement every time you charge the source. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// The status of the source, one of `canceled`, `chargeable`, `consumed`, `failed`, or `pending`. + /// + /// Only `chargeable` sources can be used to create a charge. + pub status: SourceStatus, + + #[serde(skip_serializing_if = "Option::is_none")] + pub three_d_secure: Option, + + /// The `type` of the source. + /// + /// The `type` is a payment method, one of `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, `card_present`, `eps`, `giropay`, `ideal`, `multibanco`, `klarna`, `p24`, `sepa_debit`, `sofort`, `three_d_secure`, or `wechat`. + /// An additional hash is included on the source with a name matching this value. + /// It contains additional information specific to the [payment method](https://stripe.com/docs/sources) used. + #[serde(rename = "type")] + pub type_: SourceType, + + /// Either `reusable` or `single_use`. + /// + /// Whether this source should be reusable or not. + /// Some source types may or may not be reusable by construction, while others may leave the option at creation. + /// If an incompatible value is passed, an error will be returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub usage: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub wechat: Option, +} + +impl Source { + /// Creates a new source object. + pub fn create(client: &Client, params: CreateSource<'_>) -> Response { + client.post_form("/sources", ¶ms) + } + + /// Retrieves an existing source object. + /// + /// Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. + pub fn retrieve(client: &Client, id: &SourceId, expand: &[&str]) -> Response { + client.get_query(&format!("/sources/{}", id), &Expand { expand }) + } + + /// Updates the specified source by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. This request accepts the `metadata` and `owner` as arguments. + /// It is also possible to update type specific information for selected payment methods. + /// Please refer to our [payment method guides](https://stripe.com/docs/sources) for more detail. + pub fn update(client: &Client, id: &SourceId, params: UpdateSource<'_>) -> Response { + client.post_form(&format!("/sources/{}", id), ¶ms) + } +} + +impl Object for Source { + type Id = SourceId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "source" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceCodeVerificationFlow { + /// The number of attempts remaining to authenticate the source object with a verification code. + pub attempts_remaining: i64, + + /// The status of the code verification, either `pending` (awaiting verification, `attempts_remaining` should be greater than 0), `succeeded` (successful verification) or `failed` (failed verification, cannot be verified anymore as `attempts_remaining` should be 0). + pub status: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceOrder { + /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. + pub amount: i64, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// The email address of the customer placing the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// List of items constituting the order. + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceOrderItem { + /// The amount (price) for this order item. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// This currency of this order item. + /// + /// Required when `amount` is present. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// Human-readable description for this order item. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The quantity of this order item. + /// + /// When type is `sku`, this is the number of instances of the SKU to be ordered. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The type of this order item. + /// + /// Must be `sku`, `tax`, or `shipping`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceOwner { + /// Owner's address. + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + /// Owner's email address. + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + /// Owner's full name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + /// Owner's phone number (including extension). + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + /// Verified owner's address. + /// + /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_address: Option
, + + /// Verified owner's email address. + /// + /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_email: Option, + + /// Verified owner's full name. + /// + /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_name: Option, + + /// Verified owner's phone number (including extension). + /// + /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. + /// They cannot be set or mutated. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_phone: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceReceiverFlow { + /// The address of the receiver source. + /// + /// This is the value that should be communicated to the customer to send their funds to. + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option, + + /// The total amount that was moved to your balance. + /// + /// This is almost always equal to the amount charged. + /// In rare cases when customers deposit excess funds and we are unable to refund those, those funds get moved to your balance and show up in amount_charged as well. + /// The amount charged is expressed in the source's currency. + pub amount_charged: i64, + + /// The total amount received by the receiver source. + /// + /// `amount_received = amount_returned + amount_charged` should be true for consumed sources unless customers deposit excess funds. + /// The amount received is expressed in the source's currency. + pub amount_received: i64, + + /// The total amount that was returned to the customer. + /// + /// The amount returned is expressed in the source's currency. + pub amount_returned: i64, + + /// Type of refund attribute method, one of `email`, `manual`, or `none`. + pub refund_attributes_method: String, + + /// Type of refund attribute status, one of `missing`, `requested`, or `available`. + pub refund_attributes_status: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceRedirectFlow { + /// The failure reason for the redirect, either `user_abort` (the customer aborted or dropped out of the redirect flow), `declined` (the authentication failed or the transaction was declined), or `processing_error` (the redirect failed due to a technical error). + /// + /// Present only if the redirect status is `failed`. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, + + /// The URL you provide to redirect the customer to after they authenticated their payment. + pub return_url: String, + + /// The status of the redirect, either `pending` (ready to be used by your customer to authenticate the transaction), `succeeded` (succesful authentication, cannot be reused) or `not_required` (redirect should not be used) or `failed` (failed authentication, cannot be reused). + pub status: SourceRedirectFlowStatus, + + /// The URL provided to you to redirect a customer to as part of a `redirect` authentication flow. + pub url: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeAchCreditTransfer { + #[serde(skip_serializing_if = "Option::is_none")] + pub account_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_routing_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub routing_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub swift_code: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeAchDebit { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub routing_number: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeAlipay { + #[serde(skip_serializing_if = "Option::is_none")] + pub data_string: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub native_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeAuBecsDebit { + #[serde(skip_serializing_if = "Option::is_none")] + pub bsb_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeBancontact { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bic: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub iban_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub preferred_language: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeCard { + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line1_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_zip_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_month: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_year: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub funding: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub three_d_secure: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tokenization_method: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeCardPresent { + #[serde(skip_serializing_if = "Option::is_none")] + pub application_cryptogram: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub application_preferred_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization_response_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub cvm_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub data_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dedicated_file_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub emv_auth_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence_customer_signature: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub evidence_transaction_certificate: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_month: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_year: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub funding: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pos_device_id: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pos_entry_mode: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub read_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub reader: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub terminal_verification_results: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub transaction_status_information: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeEps { + #[serde(skip_serializing_if = "Option::is_none")] + pub reference: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeGiropay { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bic: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeIdeal { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bic: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub iban_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeKlarna { + #[serde(skip_serializing_if = "Option::is_none")] + pub background_image_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub client_token: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub locale: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub logo_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub page_title: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_later_asset_urls_descriptive: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_later_asset_urls_standard: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_later_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_later_redirect_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_now_asset_urls_descriptive: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_now_asset_urls_standard: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_now_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_now_redirect_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_over_time_asset_urls_descriptive: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_over_time_asset_urls_standard: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_over_time_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub pay_over_time_redirect_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_method_categories: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub purchase_country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub purchase_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_first_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping_last_name: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeMultibanco { + #[serde(skip_serializing_if = "Option::is_none")] + pub entity: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub reference: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_city: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_line1: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_line2: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_postal_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_address_state: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_account_holder_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_iban: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeP24 { + #[serde(skip_serializing_if = "Option::is_none")] + pub reference: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeSepaDebit { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub branch_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate_reference: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate_url: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeSofort { + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bic: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub iban_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub preferred_language: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeThreeDSecure { + #[serde(skip_serializing_if = "Option::is_none")] + pub address_line1_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_zip_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub authenticated: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub cvc_check: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_month: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub exp_year: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub funding: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub three_d_secure: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tokenization_method: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceTypeWechat { + #[serde(skip_serializing_if = "Option::is_none")] + pub prepay_id: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub qr_code_url: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, +} + +/// The parameters for `Source::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateSource<'a> { + /// Amount associated with the source. + /// + /// This is the amount for which the source will be chargeable once ready. + /// Required for `single_use` sources. + /// Not supported for `receiver` type sources, where charge amount may not be specified until funds land. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. + /// + /// This is the currency for which the source will be chargeable once ready. + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + /// The `Customer` to whom the original source is attached to. + /// + /// Must be set when the original source is not a `Source` (e.g., `Card`). + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The authentication `flow` of the source to create. + /// + /// `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. + /// It is generally inferred unless a type supports multiple flows. + #[serde(skip_serializing_if = "Option::is_none")] + pub flow: Option, + + /// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The source to share. + #[serde(skip_serializing_if = "Option::is_none")] + pub original_source: Option<&'a str>, + + /// Information about the owner of the payment instrument that may be used or required by particular source types. + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + + /// Optional parameters for the receiver flow. + /// + /// Can be set only if the source is a receiver (`flow` is `receiver`). + #[serde(skip_serializing_if = "Option::is_none")] + pub receiver: Option, + + /// Parameters required for the redirect flow. + /// + /// Required if the source is authenticated by a redirect (`flow` is `redirect`). + #[serde(skip_serializing_if = "Option::is_none")] + pub redirect: Option, + + /// Information about the items and shipping associated with the source. + /// + /// Required for transactional credit (for example Klarna) sources before you can charge it. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_order: Option, + + /// An arbitrary string to be displayed on your customer's statement. + /// + /// As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option<&'a str>, + + /// An optional token used to create the source. + /// + /// When passed, token properties will override source parameters. + #[serde(skip_serializing_if = "Option::is_none")] + pub token: Option, + + /// The `type` of the source to create. + /// + /// Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide). + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option<&'a str>, +} + +impl<'a> CreateSource<'a> { + pub fn new() -> Self { + CreateSource { + amount: Default::default(), + currency: Default::default(), + customer: Default::default(), + expand: Default::default(), + flow: Default::default(), + mandate: Default::default(), + metadata: Default::default(), + original_source: Default::default(), + owner: Default::default(), + receiver: Default::default(), + redirect: Default::default(), + source_order: Default::default(), + statement_descriptor: Default::default(), + token: Default::default(), + type_: Default::default(), + } + } +} + +/// The parameters for `Source::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSource<'a> { + /// Amount associated with the source. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. + #[serde(skip_serializing_if = "Option::is_none")] + pub mandate: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Information about the owner of the payment instrument that may be used or required by particular source types. + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + + /// Information about the items and shipping associated with the source. + /// + /// Required for transactional credit (for example Klarna) sources before you can charge it. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_order: Option, +} + +impl<'a> UpdateSource<'a> { + pub fn new() -> Self { + UpdateSource { + amount: Default::default(), + expand: Default::default(), + mandate: Default::default(), + metadata: Default::default(), + owner: Default::default(), + source_order: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceReceiver { + #[serde(skip_serializing_if = "Option::is_none")] + pub refund_attributes_method: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceRedirect { + pub return_url: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceSourceOrder { + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceMandateParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub acceptance: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub notification_method: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSourceSourceOrder { + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub shipping: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceSourceOrderItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceSourceOrderShipping { + pub address: CreateSourceSourceOrderShippingAddress, + + #[serde(skip_serializing_if = "Option::is_none")] + pub carrier: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tracking_number: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceAcceptanceParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ip: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub offline: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub online: Option, + + pub status: SourceAcceptanceParamsStatus, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSourceSourceOrderItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub currency: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSourceSourceOrderShipping { + pub address: UpdateSourceSourceOrderShippingAddress, + + #[serde(skip_serializing_if = "Option::is_none")] + pub carrier: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tracking_number: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSourceSourceOrderShippingAddress { + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + pub line1: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub line2: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub postal_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceAcceptanceOfflineParams { + pub contact_email: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SourceAcceptanceOnlineParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ip: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSourceSourceOrderShippingAddress { + #[serde(skip_serializing_if = "Option::is_none")] + pub city: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + pub line1: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub line2: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub postal_code: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, +} + +/// An enum representing the possible values of an `CreateSourceSourceOrderItems`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum CreateSourceSourceOrderItemsType { + Discount, + Shipping, + Sku, + Tax, +} + +impl CreateSourceSourceOrderItemsType { + pub fn as_str(self) -> &'static str { + match self { + CreateSourceSourceOrderItemsType::Discount => "discount", + CreateSourceSourceOrderItemsType::Shipping => "shipping", + CreateSourceSourceOrderItemsType::Sku => "sku", + CreateSourceSourceOrderItemsType::Tax => "tax", + } + } +} + +impl AsRef for CreateSourceSourceOrderItemsType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for CreateSourceSourceOrderItemsType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceAcceptanceParams`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceAcceptanceParamsStatus { + Accepted, + Pending, + Refused, + Revoked, +} + +impl SourceAcceptanceParamsStatus { + pub fn as_str(self) -> &'static str { + match self { + SourceAcceptanceParamsStatus::Accepted => "accepted", + SourceAcceptanceParamsStatus::Pending => "pending", + SourceAcceptanceParamsStatus::Refused => "refused", + SourceAcceptanceParamsStatus::Revoked => "revoked", + } + } +} + +impl AsRef for SourceAcceptanceParamsStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceAcceptanceParamsStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceAcceptanceParams`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceAcceptanceParamsType { + Offline, + Online, +} + +impl SourceAcceptanceParamsType { + pub fn as_str(self) -> &'static str { + match self { + SourceAcceptanceParamsType::Offline => "offline", + SourceAcceptanceParamsType::Online => "online", + } + } +} + +impl AsRef for SourceAcceptanceParamsType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceAcceptanceParamsType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSource`'s `flow` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceFlow { + CodeVerification, + None, + Receiver, + Redirect, +} + +impl SourceFlow { + pub fn as_str(self) -> &'static str { + match self { + SourceFlow::CodeVerification => "code_verification", + SourceFlow::None => "none", + SourceFlow::Receiver => "receiver", + SourceFlow::Redirect => "redirect", + } + } +} + +impl AsRef for SourceFlow { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceFlow { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceMandateParams`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceMandateInterval { + OneTime, + Scheduled, + Variable, +} + +impl SourceMandateInterval { + pub fn as_str(self) -> &'static str { + match self { + SourceMandateInterval::OneTime => "one_time", + SourceMandateInterval::Scheduled => "scheduled", + SourceMandateInterval::Variable => "variable", + } + } +} + +impl AsRef for SourceMandateInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceMandateInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceMandateParams`'s `notification_method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceMandateNotificationMethod { + DeprecatedNone, + Email, + Manual, + None, + StripeEmail, +} + +impl SourceMandateNotificationMethod { + pub fn as_str(self) -> &'static str { + match self { + SourceMandateNotificationMethod::DeprecatedNone => "deprecated_none", + SourceMandateNotificationMethod::Email => "email", + SourceMandateNotificationMethod::Manual => "manual", + SourceMandateNotificationMethod::None => "none", + SourceMandateNotificationMethod::StripeEmail => "stripe_email", + } + } +} + +impl AsRef for SourceMandateNotificationMethod { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceMandateNotificationMethod { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSourceReceiver`'s `refund_attributes_method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceRefundNotificationMethod { + Email, + Manual, + None, +} + +impl SourceRefundNotificationMethod { + pub fn as_str(self) -> &'static str { + match self { + SourceRefundNotificationMethod::Email => "email", + SourceRefundNotificationMethod::Manual => "manual", + SourceRefundNotificationMethod::None => "none", + } + } +} + +impl AsRef for SourceRefundNotificationMethod { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceRefundNotificationMethod { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Source`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceType { + AchCreditTransfer, + AchDebit, + Alipay, + AuBecsDebit, + Bancontact, + Card, + CardPresent, + Eps, + Giropay, + Ideal, + Klarna, + Multibanco, + P24, + SepaDebit, + Sofort, + ThreeDSecure, + Wechat, +} + +impl SourceType { + pub fn as_str(self) -> &'static str { + match self { + SourceType::AchCreditTransfer => "ach_credit_transfer", + SourceType::AchDebit => "ach_debit", + SourceType::Alipay => "alipay", + SourceType::AuBecsDebit => "au_becs_debit", + SourceType::Bancontact => "bancontact", + SourceType::Card => "card", + SourceType::CardPresent => "card_present", + SourceType::Eps => "eps", + SourceType::Giropay => "giropay", + SourceType::Ideal => "ideal", + SourceType::Klarna => "klarna", + SourceType::Multibanco => "multibanco", + SourceType::P24 => "p24", + SourceType::SepaDebit => "sepa_debit", + SourceType::Sofort => "sofort", + SourceType::ThreeDSecure => "three_d_secure", + SourceType::Wechat => "wechat", + } + } +} + +impl AsRef for SourceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `UpdateSourceSourceOrderItems`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum UpdateSourceSourceOrderItemsType { + Discount, + Shipping, + Sku, + Tax, +} + +impl UpdateSourceSourceOrderItemsType { + pub fn as_str(self) -> &'static str { + match self { + UpdateSourceSourceOrderItemsType::Discount => "discount", + UpdateSourceSourceOrderItemsType::Shipping => "shipping", + UpdateSourceSourceOrderItemsType::Sku => "sku", + UpdateSourceSourceOrderItemsType::Tax => "tax", + } + } +} + +impl AsRef for UpdateSourceSourceOrderItemsType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for UpdateSourceSourceOrderItemsType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/source_ext.rs b/ft-stripe/src/resources/source_ext.rs new file mode 100644 index 0000000..e42bee8 --- /dev/null +++ b/ft-stripe/src/resources/source_ext.rs @@ -0,0 +1,129 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `Source`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceStatus { + Canceled, + Chargeable, + Consumed, + Failed, + Pending, +} + +impl SourceStatus { + pub fn as_str(self) -> &'static str { + match self { + SourceStatus::Canceled => "canceled", + SourceStatus::Chargeable => "chargeable", + SourceStatus::Consumed => "consumed", + SourceStatus::Failed => "failed", + SourceStatus::Pending => "pending", + } + } +} + +impl AsRef for SourceStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Source`'s `usage` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceUsage { + Reusable, + SingleUse, +} + +impl SourceUsage { + pub fn as_str(self) -> &'static str { + match self { + SourceUsage::Reusable => "reusable", + SourceUsage::SingleUse => "single_use", + } + } +} + +impl AsRef for SourceUsage { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceUsage { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceRedirectFlow`'s `failure_reason` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceRedirectFlowFailureReason { + Declined, + ProcessingError, + UserAbort, +} + +impl SourceRedirectFlowFailureReason { + pub fn as_str(self) -> &'static str { + match self { + SourceRedirectFlowFailureReason::Declined => "declined", + SourceRedirectFlowFailureReason::ProcessingError => "processing_error", + SourceRedirectFlowFailureReason::UserAbort => "user_abort", + } + } +} + +impl AsRef for SourceRedirectFlowFailureReason { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceRedirectFlowFailureReason { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SourceRedirectFlow`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SourceRedirectFlowStatus { + Failed, + NotRequired, + Pending, + Succeeded, +} + +impl SourceRedirectFlowStatus { + pub fn as_str(self) -> &'static str { + match self { + SourceRedirectFlowStatus::Failed => "failed", + SourceRedirectFlowStatus::NotRequired => "not_required", + SourceRedirectFlowStatus::Pending => "pending", + SourceRedirectFlowStatus::Succeeded => "succeeded", + } + } +} + +impl AsRef for SourceRedirectFlowStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SourceRedirectFlowStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/subscription.rs b/ft-stripe/src/resources/subscription.rs new file mode 100644 index 0000000..52c279c --- /dev/null +++ b/ft-stripe/src/resources/subscription.rs @@ -0,0 +1,1201 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CouponId, CustomerId, PlanId, PriceId, SubscriptionId}; +use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + CollectionMethod, Currency, Customer, Discount, Invoice, PaymentMethod, PaymentSource, Plan, + Scheduled, SetupIntent, SubscriptionBillingThresholds, SubscriptionItem, + SubscriptionItemBillingThresholds, SubscriptionSchedule, TaxRate, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Subscription". +/// +/// For more details see [https://stripe.com/docs/api/subscriptions/object](https://stripe.com/docs/api/subscriptions/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Subscription { + /// Unique identifier for the object. + pub id: SubscriptionId, + + /// A non-negative decimal between 0 and 100, with at most two decimal places. + /// + /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + /// Determines the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. + pub billing_cycle_anchor: Timestamp, + + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// A date in the future at which the subscription will automatically get canceled. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancel_at: Option, + + /// If the subscription has been canceled with the `at_period_end` flag set to `true`, `cancel_at_period_end` on the subscription will be true. + /// + /// You can use this attribute to determine whether a subscription that has a status of active is scheduled to be canceled at the end of the current period. + pub cancel_at_period_end: bool, + + /// If the subscription has been canceled, the date of that cancellation. + /// + /// If the subscription was canceled with `cancel_at_period_end`, `canceled_at` will still reflect the date of the initial cancellation request, not the end of the subscription period when the subscription is automatically moved to a canceled state. + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled_at: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. + /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// End of the current period that the subscription has been invoiced for. + /// + /// At the end of this period, a new invoice will be created. + pub current_period_end: Timestamp, + + /// Start of the current period that the subscription has been invoiced for. + pub current_period_start: Timestamp, + + /// ID of the customer who owns the subscription. + pub customer: Expandable, + + /// Number of days a customer has to pay invoices generated by this subscription. + /// + /// This value will be `null` for subscriptions where `collection_method=charge_automatically`. + #[serde(skip_serializing_if = "Option::is_none")] + pub days_until_due: Option, + + /// ID of the default payment method for the subscription. + /// + /// It must belong to the customer associated with the subscription. + /// If not set, invoices will use the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option>, + + /// ID of the default payment source for the subscription. + /// + /// It must belong to the customer associated with the subscription and be in a chargeable state. + /// If not set, defaults to the customer's default source. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option>, + + /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. + /// + /// Invoices created will have their `default_tax_rates` populated from the subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + /// Describes the current discount applied to this subscription, if there is one. + /// + /// When billing, a discount applied to a subscription overrides a discount applied on a customer-wide basis. + #[serde(skip_serializing_if = "Option::is_none")] + pub discount: Option, + + /// If the subscription has ended, the date the subscription ended. + #[serde(skip_serializing_if = "Option::is_none")] + pub ended_at: Option, + + /// List of subscription items, each with an attached plan. + pub items: List, + + /// The most recent invoice this subscription has generated. + #[serde(skip_serializing_if = "Option::is_none")] + pub latest_invoice: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at `pending_invoice_item_interval`. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_pending_invoice_item_invoice: Option, + + /// If specified, payment collection for this subscription will be paused. + #[serde(skip_serializing_if = "Option::is_none")] + pub pause_collection: Option, + + /// Specifies an interval for how often to bill for any pending invoice items. + /// + /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_invoice_item_interval: Option, + + /// 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. + /// + /// Learn more in the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-2). + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_setup_intent: Option>, + + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_update: Option, + + /// Hash describing the plan the customer is subscribed to. + /// + /// Only set if the subscription contains a single plan. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// The quantity of the plan to which the customer is subscribed. + /// + /// For example, if your plan is $10/user/month, and your customer has 5 users, you could pass 5 as the quantity to have the customer charged $50 (5 x $10) monthly. + /// Only set if the subscription contains a single plan. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The schedule attached to the subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub schedule: Option>, + + /// Date when the subscription was first created. + /// + /// The date might differ from the `created` date due to backdating. + pub start_date: Timestamp, + + /// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, or `unpaid`. + /// + /// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails. + /// A subscription in this state can only have metadata and default_source updated. + /// Once the first invoice is paid, the subscription moves into an `active` state. + /// If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`. + /// This is a terminal state, the open invoice will be voided and no further invoices will be generated. + /// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over. + /// If subscription `collection_method=charge_automatically` it becomes `past_due` when payment to renew it fails and `canceled` or `unpaid` (depending on your subscriptions settings) when Stripe has exhausted all payment retry attempts. + /// 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. + /// 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). + /// After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices. + pub status: SubscriptionStatus, + + /// If provided, each invoice created by this subscription will apply the tax rate, increasing the amount billed to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + /// If the subscription has a trial, the end of that trial. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, + + /// If the subscription has a trial, the beginning of that trial. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_start: Option, +} + +impl Subscription { + /// By default, returns a list of subscriptions that have not been canceled. + /// + /// In order to list canceled subscriptions, specify `status=canceled`. + pub fn list(client: &Client, params: ListSubscriptions<'_>) -> Response> { + client.get_query("/subscriptions", ¶ms) + } + + /// Creates a new subscription on an existing customer. + /// + /// Each customer can have up to 25 active or scheduled subscriptions. + pub fn create(client: &Client, params: CreateSubscription<'_>) -> Response { + client.post_form("/subscriptions", ¶ms) + } + + /// Retrieves the subscription with the given ID. + pub fn retrieve( + client: &Client, + id: &SubscriptionId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/subscriptions/{}", id), &Expand { expand }) + } + + /// Updates an existing subscription on a customer to match the specified parameters. + /// + /// When changing plans or quantities, we will optionally prorate the price we charge next month to make up for any price changes. + /// To preview how the proration will be calculated, use the [upcoming invoice](https://stripe.com/docs/api#upcoming_invoice) endpoint. + pub fn update( + client: &Client, + id: &SubscriptionId, + params: UpdateSubscription<'_>, + ) -> Response { + client.post_form(&format!("/subscriptions/{}", id), ¶ms) + } + + /// Cancels a customer’s subscription immediately. + /// + /// The customer will not be charged again for the subscription. Note, however, that any pending invoice items that you’ve created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). + /// If you’ve set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. + /// But if the subscription is set to cancel immediately, pending prorations will be removed. By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. + /// This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. + /// However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. + /// Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. + pub fn delete(client: &Client, id: &SubscriptionId) -> Response> { + client.delete(&format!("/subscriptions/{}", id)) + } +} + +impl Object for Subscription { + type Id = SubscriptionId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionPendingInvoiceItemInterval { + /// Specifies invoicing frequency. + /// + /// Either `day`, `week`, `month` or `year`. + pub interval: PlanInterval, + + /// The number of intervals between invoices. + /// + /// For example, `interval=month` and `interval_count=3` bills every 3 months. + /// Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). + pub interval_count: u64, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionsResourcePauseCollection { + /// The payment collection behavior for this subscription while paused. + /// + /// One of `keep_as_draft`, `mark_uncollectible`, or `void`. + pub behavior: SubscriptionsResourcePauseCollectionBehavior, + + /// The time after which the subscription will resume collecting payments. + #[serde(skip_serializing_if = "Option::is_none")] + pub resumes_at: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionsResourcePendingUpdate { + /// If the update is applied, determines the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_cycle_anchor: Option, + + /// The point after which the changes reflected by this update will be discarded and no longer applied. + pub expires_at: Timestamp, + + /// List of subscription items, each with an attached plan, that will be set if the update is applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription_items: Option>, + + /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time, if the update is applied. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, + + /// Indicates if a plan's `trial_period_days` should be applied to the subscription. + /// + /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. + /// Setting this flag to `true` together with `trial_end` is not allowed. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_from_plan: Option, +} + +/// The parameters for `Subscription::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateSubscription<'a> { + /// A list of prices and quantities that will generate invoice items appended to the first invoice for this subscription. + /// + /// You may pass up to 10 items. + #[serde(skip_serializing_if = "Option::is_none")] + pub add_invoice_items: Option>, + + /// A non-negative decimal between 0 and 100, with at most two decimal places. + /// + /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. + /// The request must be made by a platform account on a connected account in order to set an application fee percentage. + /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + /// For new subscriptions, a past timestamp to backdate the subscription's start date to. + /// + /// If set, the first invoice will contain a proration for the timespan between the start date and the current time. + /// Can be combined with trials and the billing cycle anchor. + #[serde(skip_serializing_if = "Option::is_none")] + pub backdate_start_date: Option, + + /// A future timestamp to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). + /// + /// This is used to determine the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_cycle_anchor: Option, + + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + /// + /// Pass an empty string to remove previously-defined thresholds. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// A timestamp at which the subscription should cancel. + /// + /// If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. + /// If set during a future period, this will always cause a proration for that period. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancel_at: Option, + + /// Boolean indicating whether this subscription should cancel at the end of the current period. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancel_at_period_end: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. + /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. + /// Defaults to `charge_automatically`. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// The code of the coupon to apply to this subscription. + /// + /// A coupon applied to a subscription will only affect invoices created for that particular subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// The identifier of the customer to subscribe. + pub customer: CustomerId, + + /// Number of days a customer has to pay invoices generated by this subscription. + /// + /// Valid only for subscriptions where `collection_method` is set to `send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub days_until_due: Option, + + /// ID of the default payment method for the subscription. + /// + /// It must belong to the customer associated with the subscription. + /// If not set, invoices will use the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option<&'a str>, + + /// ID of the default payment source for the subscription. + /// + /// It must belong to the customer associated with the subscription and be in a chargeable state. + /// If not set, defaults to the customer's default source. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option<&'a str>, + + /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. + /// + /// Invoices created will have their `default_tax_rates` populated from the subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A list of up to 20 subscription items, each with an attached plan. + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Indicates if a customer is on or off-session while an invoice payment is attempted. + #[serde(skip_serializing_if = "Option::is_none")] + pub off_session: Option, + + /// Use `allow_incomplete` to create subscriptions with `status=incomplete` if the first invoice cannot be paid. + /// + /// Creating subscriptions with this status allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. + /// For example, SCA regulation may require 3DS authentication to complete payment. + /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. + /// This is the default behavior. Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. + /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. + /// This was the default behavior for API versions prior to 2019-03-14. + /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. `pending_if_incomplete` is only used with updates and cannot be passed when creating a subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_behavior: Option, + + /// Specifies an interval for how often to bill for any pending invoice items. + /// + /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_invoice_item_interval: Option, + + /// This field has been renamed to `proration_behavior`. + /// + /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub prorate: Option, + + /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) resulting from the `billing_cycle_anchor`. + /// + /// Valid values are `create_prorations` or `none`. Passing `create_prorations` will cause proration invoice items to be created when applicable. + /// Prorations can be disabled by passing `none`. + /// If no value is passed, the default is `create_prorations`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + /// A non-negative decimal (with at most four decimal places) between 0 and 100. + /// + /// This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount in each billing period. + /// For example, a plan which charges $10/month with a `tax_percent` of `20.0` will charge $12 per invoice. + /// To unset a previously-set value, pass an empty string. + /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. + /// + /// This will always overwrite any trials that might apply via a subscribed plan. + /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. + /// The special value `now` can be provided to end the customer's trial immediately. + /// Can be at most two years from `billing_cycle_anchor`. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, + + /// Indicates if a plan's `trial_period_days` should be applied to the subscription. + /// + /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. + /// Setting this flag to `true` together with `trial_end` is not allowed. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_from_plan: Option, + + /// Integer representing the number of trial period days before the customer is charged for the first time. + /// + /// This will always overwrite any trials that might apply via a subscribed plan. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_period_days: Option, +} + +impl<'a> CreateSubscription<'a> { + pub fn new(customer: CustomerId) -> Self { + CreateSubscription { + add_invoice_items: Default::default(), + application_fee_percent: Default::default(), + backdate_start_date: Default::default(), + billing_cycle_anchor: Default::default(), + billing_thresholds: Default::default(), + cancel_at: Default::default(), + cancel_at_period_end: Default::default(), + collection_method: Default::default(), + coupon: Default::default(), + customer, + days_until_due: Default::default(), + default_payment_method: Default::default(), + default_source: Default::default(), + default_tax_rates: Default::default(), + expand: Default::default(), + items: Default::default(), + metadata: Default::default(), + off_session: Default::default(), + payment_behavior: Default::default(), + pending_invoice_item_interval: Default::default(), + prorate: Default::default(), + proration_behavior: Default::default(), + tax_percent: Default::default(), + trial_end: Default::default(), + trial_from_plan: Default::default(), + trial_period_days: Default::default(), + } + } +} + +/// The parameters for `Subscription::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListSubscriptions<'a> { + /// The collection method of the subscriptions to retrieve. + /// + /// Either `charge_automatically` or `send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub current_period_end: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub current_period_start: Option>, + + /// The ID of the customer whose subscriptions will be retrieved. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// The ID of the plan whose subscriptions will be retrieved. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// Filter for subscriptions that contain this recurring price ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// The status of the subscriptions to retrieve. + /// + /// One of: `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `unpaid`, `canceled`, or `all`. + /// Passing in a value of `canceled` will return all canceled subscriptions, including those belonging to deleted customers. + /// Passing in a value of `all` will return subscriptions of all statuses. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl<'a> ListSubscriptions<'a> { + pub fn new() -> Self { + ListSubscriptions { + collection_method: Default::default(), + created: Default::default(), + current_period_end: Default::default(), + current_period_start: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + plan: Default::default(), + price: Default::default(), + starting_after: Default::default(), + status: Default::default(), + } + } +} + +/// The parameters for `Subscription::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSubscription<'a> { + /// A list of prices and quantities that will generate invoice items appended to the first invoice for this subscription. + /// + /// You may pass up to 10 items. + #[serde(skip_serializing_if = "Option::is_none")] + pub add_invoice_items: Option>, + + /// A non-negative decimal between 0 and 100, with at most two decimal places. + /// + /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. + /// The request must be made by a platform account on a connected account in order to set an application fee percentage. + /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + /// Either `now` or `unchanged`. + /// + /// Setting the value to `now` resets the subscription's billing cycle anchor to the current time. + /// For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_cycle_anchor: Option, + + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + /// + /// Pass an empty string to remove previously-defined thresholds. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// A timestamp at which the subscription should cancel. + /// + /// If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. + /// If set during a future period, this will always cause a proration for that period. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancel_at: Option, + + /// Boolean indicating whether this subscription should cancel at the end of the current period. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancel_at_period_end: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. + /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. + /// Defaults to `charge_automatically`. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// The code of the coupon to apply to this subscription. + /// + /// A coupon applied to a subscription will only affect invoices created for that particular subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + /// Number of days a customer has to pay invoices generated by this subscription. + /// + /// Valid only for subscriptions where `collection_method` is set to `send_invoice`. + #[serde(skip_serializing_if = "Option::is_none")] + pub days_until_due: Option, + + /// ID of the default payment method for the subscription. + /// + /// It must belong to the customer associated with the subscription. + /// If not set, invoices will use the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option<&'a str>, + + /// ID of the default payment source for the subscription. + /// + /// It must belong to the customer associated with the subscription and be in a chargeable state. + /// If not set, defaults to the customer's default source. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_source: Option<&'a str>, + + /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. + /// + /// Invoices created will have their `default_tax_rates` populated from the subscription. + /// Pass an empty string to remove previously-defined tax rates. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// List of subscription items, each with an attached plan. + #[serde(skip_serializing_if = "Option::is_none")] + pub items: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Indicates if a customer is on or off-session while an invoice payment is attempted. + #[serde(skip_serializing_if = "Option::is_none")] + pub off_session: Option, + + /// If specified, payment collection for this subscription will be paused. + #[serde(skip_serializing_if = "Option::is_none")] + pub pause_collection: Option, + + /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. + /// + /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. + /// For example, SCA regulation may require 3DS authentication to complete payment. + /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. + /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). + /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. + /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. + /// This was the default behavior for API versions prior to 2019-03-14. + /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_behavior: Option, + + /// Specifies an interval for how often to bill for any pending invoice items. + /// + /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_invoice_item_interval: Option, + + /// This field has been renamed to `proration_behavior`. + /// + /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub prorate: Option, + + /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. + /// + /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. + /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). + /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + /// If set, the proration will be calculated as though the subscription was updated at the given time. + /// + /// This can be used to apply exactly the same proration that was previewed with [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + /// It can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_date: Option, + + /// A non-negative decimal (with at most four decimal places) between 0 and 100. + /// + /// This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount in each billing period. + /// For example, a plan which charges $10/month with a `tax_percent` of `20.0` will charge $12 per invoice. + /// To unset a previously-set value, pass an empty string. + /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. + /// + /// This will always overwrite any trials that might apply via a subscribed plan. + /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. + /// The special value `now` can be provided to end the customer's trial immediately. + /// Can be at most two years from `billing_cycle_anchor`. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, + + /// Indicates if a plan's `trial_period_days` should be applied to the subscription. + /// + /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. + /// Setting this flag to `true` together with `trial_end` is not allowed. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_from_plan: Option, +} + +impl<'a> UpdateSubscription<'a> { + pub fn new() -> Self { + UpdateSubscription { + add_invoice_items: Default::default(), + application_fee_percent: Default::default(), + billing_cycle_anchor: Default::default(), + billing_thresholds: Default::default(), + cancel_at: Default::default(), + cancel_at_period_end: Default::default(), + collection_method: Default::default(), + coupon: Default::default(), + days_until_due: Default::default(), + default_payment_method: Default::default(), + default_source: Default::default(), + default_tax_rates: Default::default(), + expand: Default::default(), + items: Default::default(), + metadata: Default::default(), + off_session: Default::default(), + pause_collection: Default::default(), + payment_behavior: Default::default(), + pending_invoice_item_interval: Default::default(), + prorate: Default::default(), + proration_behavior: Default::default(), + proration_date: Default::default(), + tax_percent: Default::default(), + trial_end: Default::default(), + trial_from_plan: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AddInvoiceItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSubscriptionItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSubscriptionPendingInvoiceItemInterval { + pub interval: PlanInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSubscriptionItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub clear_usage: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub deleted: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSubscriptionPauseCollection { + pub behavior: UpdateSubscriptionPauseCollectionBehavior, + + #[serde(skip_serializing_if = "Option::is_none")] + pub resumes_at: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSubscriptionPendingInvoiceItemInterval { + pub interval: PlanInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSubscriptionItemsBillingThresholds { + pub usage_gte: i64, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItemPriceData { + pub currency: Currency, + + pub product: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceData { + pub currency: Currency, + + pub product: String, + + pub recurring: SubscriptionItemPriceDataRecurring, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceDataRecurring { + pub interval: PlanInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, +} + +/// An enum representing the possible values of an `SubscriptionPendingInvoiceItemInterval`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanInterval { + Day, + Month, + Week, + Year, +} + +impl PlanInterval { + pub fn as_str(self) -> &'static str { + match self { + PlanInterval::Day => "day", + PlanInterval::Month => "month", + PlanInterval::Week => "week", + PlanInterval::Year => "year", + } + } +} + +impl AsRef for PlanInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `UpdateSubscription`'s `billing_cycle_anchor` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionBillingCycleAnchor { + Now, + Unchanged, +} + +impl SubscriptionBillingCycleAnchor { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionBillingCycleAnchor::Now => "now", + SubscriptionBillingCycleAnchor::Unchanged => "unchanged", + } + } +} + +impl AsRef for SubscriptionBillingCycleAnchor { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionBillingCycleAnchor { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSubscription`'s `payment_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionPaymentBehavior { + AllowIncomplete, + ErrorIfIncomplete, + PendingIfIncomplete, +} + +impl SubscriptionPaymentBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionPaymentBehavior::AllowIncomplete => "allow_incomplete", + SubscriptionPaymentBehavior::ErrorIfIncomplete => "error_if_incomplete", + SubscriptionPaymentBehavior::PendingIfIncomplete => "pending_if_incomplete", + } + } +} + +impl AsRef for SubscriptionPaymentBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionPaymentBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSubscription`'s `proration_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionProrationBehavior { + AlwaysInvoice, + CreateProrations, + None, +} + +impl SubscriptionProrationBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", + SubscriptionProrationBehavior::CreateProrations => "create_prorations", + SubscriptionProrationBehavior::None => "none", + } + } +} + +impl AsRef for SubscriptionProrationBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionProrationBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `Subscription`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionStatus { + Active, + Canceled, + Incomplete, + IncompleteExpired, + PastDue, + Trialing, + Unpaid, +} + +impl SubscriptionStatus { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionStatus::Active => "active", + SubscriptionStatus::Canceled => "canceled", + SubscriptionStatus::Incomplete => "incomplete", + SubscriptionStatus::IncompleteExpired => "incomplete_expired", + SubscriptionStatus::PastDue => "past_due", + SubscriptionStatus::Trialing => "trialing", + SubscriptionStatus::Unpaid => "unpaid", + } + } +} + +impl AsRef for SubscriptionStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListSubscriptions`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionStatusFilter { + Active, + All, + Canceled, + Ended, + Incomplete, + IncompleteExpired, + PastDue, + Trialing, + Unpaid, +} + +impl SubscriptionStatusFilter { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionStatusFilter::Active => "active", + SubscriptionStatusFilter::All => "all", + SubscriptionStatusFilter::Canceled => "canceled", + SubscriptionStatusFilter::Ended => "ended", + SubscriptionStatusFilter::Incomplete => "incomplete", + SubscriptionStatusFilter::IncompleteExpired => "incomplete_expired", + SubscriptionStatusFilter::PastDue => "past_due", + SubscriptionStatusFilter::Trialing => "trialing", + SubscriptionStatusFilter::Unpaid => "unpaid", + } + } +} + +impl AsRef for SubscriptionStatusFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionStatusFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SubscriptionsResourcePauseCollection`'s `behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionsResourcePauseCollectionBehavior { + KeepAsDraft, + MarkUncollectible, + Void, +} + +impl SubscriptionsResourcePauseCollectionBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionsResourcePauseCollectionBehavior::KeepAsDraft => "keep_as_draft", + SubscriptionsResourcePauseCollectionBehavior::MarkUncollectible => "mark_uncollectible", + SubscriptionsResourcePauseCollectionBehavior::Void => "void", + } + } +} + +impl AsRef for SubscriptionsResourcePauseCollectionBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionsResourcePauseCollectionBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `UpdateSubscriptionPauseCollection`'s `behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum UpdateSubscriptionPauseCollectionBehavior { + KeepAsDraft, + MarkUncollectible, + Void, +} + +impl UpdateSubscriptionPauseCollectionBehavior { + pub fn as_str(self) -> &'static str { + match self { + UpdateSubscriptionPauseCollectionBehavior::KeepAsDraft => "keep_as_draft", + UpdateSubscriptionPauseCollectionBehavior::MarkUncollectible => "mark_uncollectible", + UpdateSubscriptionPauseCollectionBehavior::Void => "void", + } + } +} + +impl AsRef for UpdateSubscriptionPauseCollectionBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for UpdateSubscriptionPauseCollectionBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/subscription_ext.rs b/ft-stripe/src/resources/subscription_ext.rs new file mode 100644 index 0000000..615dbc9 --- /dev/null +++ b/ft-stripe/src/resources/subscription_ext.rs @@ -0,0 +1,43 @@ +use crate::config::{Client, Response}; +use crate::ids::SubscriptionId; +use crate::resources::{CreateSubscriptionItems, Subscription}; +use serde::Serialize; + +#[derive(Clone, Debug, Default, Serialize)] +pub struct CancelSubscription { + #[serde(skip_serializing_if = "Option::is_none")] + pub at_period_end: Option, +} + +impl CancelSubscription { + pub fn new() -> CancelSubscription { + CancelSubscription { at_period_end: None } + } +} + +impl Subscription { + /// Cancels a subscription. + /// + /// For more details see https://stripe.com/docs/api#cancel_subscription. + pub fn cancel( + client: &Client, + subscription_id: &SubscriptionId, + params: CancelSubscription, + ) -> Response { + client.delete_query(&format!("/subscriptions/{}", subscription_id), params) + } +} + +impl CreateSubscriptionItems { + pub fn new() -> Self { + Self { + billing_thresholds: Default::default(), + metadata: Default::default(), + plan: Default::default(), + price: Default::default(), + price_data: Default::default(), + quantity: Default::default(), + tax_rates: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/subscription_item.rs b/ft-stripe/src/resources/subscription_item.rs new file mode 100644 index 0000000..674f5c2 --- /dev/null +++ b/ft-stripe/src/resources/subscription_item.rs @@ -0,0 +1,480 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{PlanId, PriceId, SubscriptionId, SubscriptionItemId}; +use crate::params::{Deleted, Expand, List, Metadata, Object, Timestamp}; +use crate::resources::{Currency, Plan, Price, SubscriptionItemBillingThresholds, TaxRate}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "SubscriptionItem". +/// +/// For more details see [https://stripe.com/docs/api/subscription_items/object](https://stripe.com/docs/api/subscription_items/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItem { + /// Unique identifier for the object. + pub id: SubscriptionItemId, + + /// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// The [quantity](https://stripe.com/docs/subscriptions/quantities) of the plan to which the customer should be subscribed. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The `subscription` this `subscription_item` belongs to. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option, + + /// The tax rates which apply to this `subscription_item`. + /// + /// When set, the `default_tax_rates` on the subscription do not apply to this `subscription_item`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +impl SubscriptionItem { + /// Returns a list of your subscription items for a given subscription. + pub fn list( + client: &Client, + params: ListSubscriptionItems<'_>, + ) -> Response> { + client.get_query("/subscription_items", ¶ms) + } + + /// Adds a new item to an existing subscription. + /// + /// No existing items will be changed or replaced. + pub fn create( + client: &Client, + params: CreateSubscriptionItem<'_>, + ) -> Response { + client.post_form("/subscription_items", ¶ms) + } + + /// Retrieves the invoice item with the given ID. + pub fn retrieve( + client: &Client, + id: &SubscriptionItemId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/subscription_items/{}", id), &Expand { expand }) + } + + /// Updates the plan or quantity of an item on a current subscription. + pub fn update( + client: &Client, + id: &SubscriptionItemId, + params: UpdateSubscriptionItem<'_>, + ) -> Response { + client.post_form(&format!("/subscription_items/{}", id), ¶ms) + } + + /// Deletes an item from the subscription. + /// + /// Removing a subscription item from a subscription will not cancel the subscription. + pub fn delete( + client: &Client, + id: &SubscriptionItemId, + ) -> Response> { + client.delete(&format!("/subscription_items/{}", id)) + } +} + +impl Object for SubscriptionItem { + type Id = SubscriptionItemId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription_item" + } +} + +/// The parameters for `SubscriptionItem::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateSubscriptionItem<'a> { + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + /// + /// When updating, pass an empty string to remove previously-defined thresholds. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. + /// + /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. + /// For example, SCA regulation may require 3DS authentication to complete payment. + /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. + /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). + /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. + /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. + /// This was the default behavior for API versions prior to 2019-03-14. + /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_behavior: Option, + + /// The identifier of the plan to add to the subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// The ID of the price object. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Data used to generate a new price object inline. + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + /// This field has been renamed to `proration_behavior`. + /// + /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub prorate: Option, + + /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. + /// + /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. + /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). + /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + /// If set, the proration will be calculated as though the subscription was updated at the given time. + /// + /// This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_date: Option, + + /// The quantity you'd like to apply to the subscription item you're creating. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The identifier of the subscription to modify. + pub subscription: SubscriptionId, + + /// A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. + /// + /// These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. + /// When updating, pass an empty string to remove previously-defined tax rates. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +impl<'a> CreateSubscriptionItem<'a> { + pub fn new(subscription: SubscriptionId) -> Self { + CreateSubscriptionItem { + billing_thresholds: Default::default(), + expand: Default::default(), + metadata: Default::default(), + payment_behavior: Default::default(), + plan: Default::default(), + price: Default::default(), + price_data: Default::default(), + prorate: Default::default(), + proration_behavior: Default::default(), + proration_date: Default::default(), + quantity: Default::default(), + subscription, + tax_rates: Default::default(), + } + } +} + +/// The parameters for `SubscriptionItem::list`. +#[derive(Clone, Debug, Serialize)] +pub struct ListSubscriptionItems<'a> { + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// The ID of the subscription whose items will be retrieved. + pub subscription: SubscriptionId, +} + +impl<'a> ListSubscriptionItems<'a> { + pub fn new(subscription: SubscriptionId) -> Self { + ListSubscriptionItems { + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + subscription, + } + } +} + +/// The parameters for `SubscriptionItem::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSubscriptionItem<'a> { + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + /// + /// When updating, pass an empty string to remove previously-defined thresholds. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// Indicates if a customer is on or off-session while an invoice payment is attempted. + #[serde(skip_serializing_if = "Option::is_none")] + pub off_session: Option, + + /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. + /// + /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. + /// For example, SCA regulation may require 3DS authentication to complete payment. + /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. + /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). + /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. + /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. + /// This was the default behavior for API versions prior to 2019-03-14. + /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. + #[serde(skip_serializing_if = "Option::is_none")] + pub payment_behavior: Option, + + /// The identifier of the new plan for this subscription item. + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + /// The ID of the price object. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + /// Data used to generate a new price object inline. + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + /// This field has been renamed to `proration_behavior`. + /// + /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub prorate: Option, + + /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. + /// + /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. + /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). + /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + /// If set, the proration will be calculated as though the subscription was updated at the given time. + /// + /// This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_date: Option, + + /// The quantity you'd like to apply to the subscription item you're creating. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. + /// + /// These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. + /// When updating, pass an empty string to remove previously-defined tax rates. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +impl<'a> UpdateSubscriptionItem<'a> { + pub fn new() -> Self { + UpdateSubscriptionItem { + billing_thresholds: Default::default(), + expand: Default::default(), + metadata: Default::default(), + off_session: Default::default(), + payment_behavior: Default::default(), + plan: Default::default(), + price: Default::default(), + price_data: Default::default(), + prorate: Default::default(), + proration_behavior: Default::default(), + proration_date: Default::default(), + quantity: Default::default(), + tax_rates: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceData { + pub currency: Currency, + + pub product: String, + + pub recurring: SubscriptionItemPriceDataRecurring, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceDataRecurring { + pub interval: PlanInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, +} + +/// An enum representing the possible values of an `SubscriptionItemPriceDataRecurring`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanInterval { + Day, + Month, + Week, + Year, +} + +impl PlanInterval { + pub fn as_str(self) -> &'static str { + match self { + PlanInterval::Day => "day", + PlanInterval::Month => "month", + PlanInterval::Week => "week", + PlanInterval::Year => "year", + } + } +} + +impl AsRef for PlanInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSubscriptionItem`'s `payment_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionPaymentBehavior { + AllowIncomplete, + ErrorIfIncomplete, + PendingIfIncomplete, +} + +impl SubscriptionPaymentBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionPaymentBehavior::AllowIncomplete => "allow_incomplete", + SubscriptionPaymentBehavior::ErrorIfIncomplete => "error_if_incomplete", + SubscriptionPaymentBehavior::PendingIfIncomplete => "pending_if_incomplete", + } + } +} + +impl AsRef for SubscriptionPaymentBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionPaymentBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `CreateSubscriptionItem`'s `proration_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionProrationBehavior { + AlwaysInvoice, + CreateProrations, + None, +} + +impl SubscriptionProrationBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", + SubscriptionProrationBehavior::CreateProrations => "create_prorations", + SubscriptionProrationBehavior::None => "none", + } + } +} + +impl AsRef for SubscriptionProrationBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionProrationBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/subscription_item_ext.rs b/ft-stripe/src/resources/subscription_item_ext.rs new file mode 100644 index 0000000..89b8b18 --- /dev/null +++ b/ft-stripe/src/resources/subscription_item_ext.rs @@ -0,0 +1,161 @@ +use crate::config::{Client, Response}; +use crate::ids::{InvoiceId, SubscriptionItemId, UsageRecordId, UsageRecordSummaryId}; +use crate::params::{Expand, List, Object, Timestamp}; +use crate::OpenPeriod; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "UsageRecord". +/// +/// For more details see [https://stripe.com/docs/api/usage_records/](https://stripe.com/docs/api/usage_records/). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UsageRecord { + /// Unique identifier for the object. + pub id: UsageRecordId, + + /// The usage quantity for the specified date. + pub quantity: u64, + + /// The ID of the subscription item this usage record contains data for. + pub subscription_item: SubscriptionItemId, + + /// The timestamp when this usage occurred. + pub timestamp: Timestamp, +} + +/// Creates a usage record for a specified subscription item and date, and fills it with a quantity. +/// +/// For more details see [https://stripe.com/docs/api/usage_records/create](https://stripe.com/docs/api/usage_records/create). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateUsageRecord { + /// The usage quantity for the specified date. + pub quantity: u64, + + /// The timestamp when this usage occurred. + pub timestamp: Timestamp, + + /// Valid values are `Increment` (default) or `Set`. + /// When using `Increment` the specified quantity will be added to the usage at the specified timestamp. + /// The `Set` action will overwrite the usage quantity at that timestamp. + /// If the subscription has billing thresholds, `Increment` is the only allowed value. + #[serde(skip_serializing_if = "Option::is_none")] + pub action: Option, +} + +impl CreateUsageRecord { + pub fn new(quantity: u64, timestamp: Timestamp) -> Self { + CreateUsageRecord { quantity, timestamp, action: None } + } +} + +/// An enum specifying possible values for `CreateUsageRecord`'s `action` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum UsageRecordAction { + /// Deafult. The specified quantity will be added to the usage. + Increment, + + /// Overwrites the usage quantity. + Set, +} + +impl UsageRecord { + /// Creates a usage record for a specified subscription item and date, and fills it with a quantity. + /// + /// For more details see [https://stripe.com/docs/api/usage_records/create](https://stripe.com/docs/api/usage_records/create). + pub fn create( + client: &Client, + id: SubscriptionItemId, + params: CreateUsageRecord, + ) -> Response { + client.post_form(&format!("/subscription_items/{}/usage_records", id), ¶ms) + } +} + +/// The resource representing a Stripe "UsageRecordSummary". +/// +/// For more details see [https://stripe.com/docs/api/usage_records/subscription_item_summary_list](https://stripe.com/docs/api/usage_records/subscription_item_summary_list). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UsageRecordSummary { + /// Unique identifier for the object. + pub id: UsageRecordSummaryId, + + /// The invoice in which this usage period has been billed for. + pub invoice: Option, + + // The usage period. + pub period: OpenPeriod, + + /// The ID of the subscription item this summary is describing. + pub subscription_item: SubscriptionItemId, + + /// The total usage within this usage period. + pub total_usage: u64, +} + +impl UsageRecordSummary { + /// For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that’s been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). + /// + /// The list is sorted in reverse-chronological order (newest first). The first list item represents the most current usage period that hasn’t ended yet. Since new usage records can still be added, the returned summary information for the subscription item’s ID should be seen as unstable until the subscription billing period ends. + pub fn list( + client: &Client, + id: &SubscriptionItemId, + params: ListUsageRecordSummaries<'_>, + ) -> Response> { + // This is a bit of a strange API since params.subscription_item needs to go into the URL, + // but the rest of the parameters (except subscription_item) need to be passed via query params. + let url = format!("/subscription_items/{}/usage_record_summaries", &id); + client.get_query(&url, ¶ms) + } +} + +impl Object for UsageRecordSummary { + type Id = UsageRecordSummaryId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "usage_record_summary" + } +} + +/// For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that’s been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). +/// +/// The list is sorted in reverse-chronological order (newest first). The first list item represents the most current usage period that hasn’t ended yet. Since new usage records can still be added, the returned summary information for the subscription item’s ID should be seen as unstable until the subscription billing period ends. +/// For more details see [https://stripe.com/docs/api/usage_records/subscription_item_summary_list](https://stripe.com/docs/api/usage_records/subscription_item_summary_list). +#[derive(Clone, Debug, Serialize)] +pub struct ListUsageRecordSummaries<'a> { + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListUsageRecordSummaries<'a> { + pub fn new() -> Self { + ListUsageRecordSummaries { + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/subscription_schedule.rs b/ft-stripe/src/resources/subscription_schedule.rs new file mode 100644 index 0000000..3cf3741 --- /dev/null +++ b/ft-stripe/src/resources/subscription_schedule.rs @@ -0,0 +1,820 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, SubscriptionScheduleId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{ + CollectionMethod, Coupon, Currency, Customer, PaymentMethod, Plan, Price, Scheduled, + Subscription, SubscriptionBillingThresholds, SubscriptionItemBillingThresholds, TaxRate, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "SubscriptionSchedule". +/// +/// For more details see [https://stripe.com/docs/api/subscription_schedules/object](https://stripe.com/docs/api/subscription_schedules/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionSchedule { + /// Unique identifier for the object. + pub id: SubscriptionScheduleId, + + /// Time at which the subscription schedule was canceled. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled_at: Option, + + /// Time at which the subscription schedule was completed. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Object representing the start and end dates for the current phase of the subscription schedule, if it is `active`. + #[serde(skip_serializing_if = "Option::is_none")] + pub current_phase: Option, + + /// ID of the customer who owns the subscription schedule. + pub customer: Expandable, + + pub default_settings: SubscriptionScheduleDefaultSettings, + + /// Behavior of the subscription schedule and underlying subscription when it ends. + pub end_behavior: SubscriptionScheduleEndBehavior, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// Configuration for the subscription schedule's phases. + pub phases: Vec, + + /// Time at which the subscription schedule was released. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub released_at: Option, + + /// ID of the subscription once managed by the subscription schedule (if it is released). + #[serde(skip_serializing_if = "Option::is_none")] + pub released_subscription: Option, + + /// The present status of the subscription schedule. + /// + /// Possible values are `not_started`, `active`, `completed`, `released`, and `canceled`. + /// You can read more about the different states in our [behavior guide](https://stripe.com/docs/billing/subscriptions/subscription-schedules). + pub status: SubscriptionScheduleStatus, + + /// ID of the subscription managed by the subscription schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub subscription: Option>, +} + +impl SubscriptionSchedule { + /// Retrieves the list of your subscription schedules. + pub fn list( + client: &Client, + params: ListSubscriptionSchedules<'_>, + ) -> Response> { + client.get_query("/subscription_schedules", ¶ms) + } + + /// Creates a new subscription schedule object. + /// + /// Each customer can have up to 25 active or scheduled subscriptions. + pub fn create( + client: &Client, + params: CreateSubscriptionSchedule<'_>, + ) -> Response { + client.post_form("/subscription_schedules", ¶ms) + } + + /// Retrieves the details of an existing subscription schedule. + /// + /// You only need to supply the unique subscription schedule identifier that was returned upon subscription schedule creation. + pub fn retrieve( + client: &Client, + id: &SubscriptionScheduleId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/subscription_schedules/{}", id), &Expand { expand }) + } + + /// Updates an existing subscription schedule. + pub fn update( + client: &Client, + id: &SubscriptionScheduleId, + params: UpdateSubscriptionSchedule<'_>, + ) -> Response { + client.post_form(&format!("/subscription_schedules/{}", id), ¶ms) + } +} + +impl Object for SubscriptionSchedule { + type Id = SubscriptionScheduleId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "subscription_schedule" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleCurrentPhase { + /// The end of this phase of the subscription schedule. + pub end_date: Timestamp, + + /// The start of this phase of the subscription schedule. + pub start_date: Timestamp, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionSchedulePhaseConfiguration { + #[serde(skip_serializing_if = "Option::is_none")] + pub add_invoice_items: Option>, + + /// A non-negative decimal between 0 and 100, with at most two decimal places. + /// + /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account during this phase of the schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. + /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// ID of the coupon to use during this phase of the subscription schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option>, + + /// ID of the default payment method for the subscription schedule. + /// + /// It must belong to the customer associated with the subscription schedule. + /// If not set, invoices will use the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option>, + + /// The default tax rates to apply to the subscription during this phase of the subscription schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + /// The end of this phase of the subscription schedule. + pub end_date: Timestamp, + + /// The subscription schedule's default invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + /// Plans to subscribe during this phase of the subscription schedule. + pub plans: Vec, + + /// Controls whether or not the subscription schedule will prorate when transitioning to this phase. + /// + /// Values are `create_prorations` and `none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + /// The start of this phase of the subscription schedule. + pub start_date: Timestamp, + + /// If provided, each invoice created during this phase of the subscription schedule will apply the tax rate, increasing the amount billed to the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + /// When the trial ends within the phase. + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleAddInvoiceItem { + /// ID of the price used to generate the invoice item. + pub price: Expandable, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleConfigurationItem { + /// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// ID of the plan to which the customer should be subscribed. + pub plan: Expandable, + + /// ID of the price to which the customer should be subscribed. + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option>, + + /// Quantity of the plan to which the customer should be subscribed. + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + /// The tax rates which apply to this `phase_item`. + /// + /// When set, the `default_tax_rates` on the phase do not apply to this `phase_item`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleDefaultSettings { + /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + /// Either `charge_automatically`, or `send_invoice`. + /// + /// When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. + /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + /// ID of the default payment method for the subscription schedule. + /// + /// If not set, invoices will use the default payment method in the customer's invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option>, + + /// The subscription schedule's default invoice settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, +} + +/// The parameters for `SubscriptionSchedule::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateSubscriptionSchedule<'a> { + /// The identifier of the customer to create the subscription schedule for. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// Object representing the subscription schedule's default settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_settings: Option, + + /// Configures how the subscription schedule behaves when it ends. + /// + /// Possible values are `release` or `cancel` with the default being `release`. + /// `release` will end the subscription schedule and keep the underlying subscription running.`cancel` will end the subscription schedule and cancel the underlying subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub end_behavior: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Migrate an existing subscription to be managed by a subscription schedule. + /// + /// If this parameter is set, a subscription schedule will be created using the subscription's plan(s), set to auto-renew using the subscription's interval. + /// When using this parameter, other parameters (such as phase values) cannot be set. + /// To create a subscription schedule with other modifications, we recommend making two separate API calls. + #[serde(skip_serializing_if = "Option::is_none")] + pub from_subscription: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// List representing phases of the subscription schedule. + /// + /// Each phase can be customized to have different durations, plans, and coupons. + /// If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. + #[serde(skip_serializing_if = "Option::is_none")] + pub phases: Option>, + + /// When the subscription schedule starts. + /// + /// We recommend using `now` so that it starts the subscription immediately. + /// You can also use a Unix timestamp to backdate the subscription so that it starts on a past date, or set a future date for the subscription to start on. + #[serde(skip_serializing_if = "Option::is_none")] + pub start_date: Option, +} + +impl<'a> CreateSubscriptionSchedule<'a> { + pub fn new() -> Self { + CreateSubscriptionSchedule { + customer: Default::default(), + default_settings: Default::default(), + end_behavior: Default::default(), + expand: Default::default(), + from_subscription: Default::default(), + metadata: Default::default(), + phases: Default::default(), + start_date: Default::default(), + } + } +} + +/// The parameters for `SubscriptionSchedule::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListSubscriptionSchedules<'a> { + /// Only return subscription schedules that were created canceled the given date interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub canceled_at: Option>, + + /// Only return subscription schedules that completed during the given date interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option>, + + /// Only return subscription schedules that were created during the given date interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// Only return subscription schedules for the given customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// Only return subscription schedules that were released during the given date interval. + #[serde(skip_serializing_if = "Option::is_none")] + pub released_at: Option>, + + /// Only return subscription schedules that have not started yet. + #[serde(skip_serializing_if = "Option::is_none")] + pub scheduled: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListSubscriptionSchedules<'a> { + pub fn new() -> Self { + ListSubscriptionSchedules { + canceled_at: Default::default(), + completed_at: Default::default(), + created: Default::default(), + customer: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + released_at: Default::default(), + scheduled: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `SubscriptionSchedule::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateSubscriptionSchedule<'a> { + /// Object representing the subscription schedule's default settings. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_settings: Option, + + /// Configures how the subscription schedule behaves when it ends. + /// + /// Possible values are `release` or `cancel` with the default being `release`. + /// `release` will end the subscription schedule and keep the underlying subscription running.`cancel` will end the subscription schedule and cancel the underlying subscription. + #[serde(skip_serializing_if = "Option::is_none")] + pub end_behavior: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// List representing phases of the subscription schedule. + /// + /// Each phase can be customized to have different durations, plans, and coupons. + /// If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. + /// Note that past phases can be omitted. + #[serde(skip_serializing_if = "Option::is_none")] + pub phases: Option>, + + /// This field has been renamed to `proration_behavior`. + /// + /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. + #[serde(skip_serializing_if = "Option::is_none")] + pub prorate: Option, + + /// If the update changes the current phase, indicates if the changes should be prorated. + /// + /// Valid values are `create_prorations` or `none`, and the default value is `create_prorations`. + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, +} + +impl<'a> UpdateSubscriptionSchedule<'a> { + pub fn new() -> Self { + UpdateSubscriptionSchedule { + default_settings: Default::default(), + end_behavior: Default::default(), + expand: Default::default(), + metadata: Default::default(), + phases: Default::default(), + prorate: Default::default(), + proration_behavior: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateSubscriptionSchedulePhases { + #[serde(skip_serializing_if = "Option::is_none")] + pub add_invoice_items: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub end_date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub iterations: Option, + + pub plans: Vec, + + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub trial: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleDefaultSettingsParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct UpdateSubscriptionSchedulePhases { + #[serde(skip_serializing_if = "Option::is_none")] + pub add_invoice_items: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub application_fee_percent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub collection_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub coupon: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_payment_method: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub default_tax_rates: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub end_date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub invoice_settings: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub iterations: Option, + + pub plans: Vec, + + #[serde(skip_serializing_if = "Option::is_none")] + pub proration_behavior: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub start_date: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_percent: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub trial: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub trial_end: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AddInvoiceItems { + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleBillingThresholds { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_gte: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub reset_billing_cycle_anchor: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionScheduleInvoiceSettings { + #[serde(skip_serializing_if = "Option::is_none")] + pub days_until_due: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionSchedulePhasesPlansParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_thresholds: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub price_data: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub quantity: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tax_rates: Option>, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct InvoiceItemPriceData { + pub currency: Currency, + + pub product: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceData { + pub currency: Currency, + + pub product: String, + + pub recurring: SubscriptionItemPriceDataRecurring, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub unit_amount_decimal: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemPriceDataRecurring { + pub interval: PlanInterval, + + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_count: Option, +} + +/// An enum representing the possible values of an `SubscriptionItemPriceDataRecurring`'s `interval` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PlanInterval { + Day, + Month, + Week, + Year, +} + +impl PlanInterval { + pub fn as_str(self) -> &'static str { + match self { + PlanInterval::Day => "day", + PlanInterval::Month => "month", + PlanInterval::Week => "week", + PlanInterval::Year => "year", + } + } +} + +impl AsRef for PlanInterval { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for PlanInterval { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SubscriptionSchedulePhaseConfiguration`'s `proration_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionProrationBehavior { + AlwaysInvoice, + CreateProrations, + None, +} + +impl SubscriptionProrationBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", + SubscriptionProrationBehavior::CreateProrations => "create_prorations", + SubscriptionProrationBehavior::None => "none", + } + } +} + +impl AsRef for SubscriptionProrationBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionProrationBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SubscriptionScheduleDefaultSettings`'s `collection_method` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionScheduleDefaultSettingsCollectionMethod { + ChargeAutomatically, + SendInvoice, +} + +impl SubscriptionScheduleDefaultSettingsCollectionMethod { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionScheduleDefaultSettingsCollectionMethod::ChargeAutomatically => { + "charge_automatically" + } + SubscriptionScheduleDefaultSettingsCollectionMethod::SendInvoice => "send_invoice", + } + } +} + +impl AsRef for SubscriptionScheduleDefaultSettingsCollectionMethod { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionScheduleDefaultSettingsCollectionMethod { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SubscriptionSchedule`'s `end_behavior` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionScheduleEndBehavior { + Cancel, + None, + Release, + Renew, +} + +impl SubscriptionScheduleEndBehavior { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionScheduleEndBehavior::Cancel => "cancel", + SubscriptionScheduleEndBehavior::None => "none", + SubscriptionScheduleEndBehavior::Release => "release", + SubscriptionScheduleEndBehavior::Renew => "renew", + } + } +} + +impl AsRef for SubscriptionScheduleEndBehavior { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionScheduleEndBehavior { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `SubscriptionSchedule`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionScheduleStatus { + Active, + Canceled, + Completed, + NotStarted, + Released, +} + +impl SubscriptionScheduleStatus { + pub fn as_str(self) -> &'static str { + match self { + SubscriptionScheduleStatus::Active => "active", + SubscriptionScheduleStatus::Canceled => "canceled", + SubscriptionScheduleStatus::Completed => "completed", + SubscriptionScheduleStatus::NotStarted => "not_started", + SubscriptionScheduleStatus::Released => "released", + } + } +} + +impl AsRef for SubscriptionScheduleStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for SubscriptionScheduleStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/tax_deducted_at_source.rs b/ft-stripe/src/resources/tax_deducted_at_source.rs new file mode 100644 index 0000000..972cfd6 --- /dev/null +++ b/ft-stripe/src/resources/tax_deducted_at_source.rs @@ -0,0 +1,31 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::params::{Object, Timestamp}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "TaxDeductedAtSource". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxDeductedAtSource { + /// The end of the invoicing period. + /// + /// This TDS applies to Stripe fees collected during this invoicing period. + pub period_end: Timestamp, + + /// The start of the invoicing period. + /// + /// This TDS applies to Stripe fees collected during this invoicing period. + pub period_start: Timestamp, + + /// The TAN that was supplied to Stripe when TDS was assessed. + pub tax_deduction_account_number: String, +} + +impl Object for TaxDeductedAtSource { + type Id = (); + fn id(&self) -> Self::Id {} + fn object(&self) -> &'static str { + "tax_deducted_at_source" + } +} diff --git a/ft-stripe/src/resources/tax_id.rs b/ft-stripe/src/resources/tax_id.rs new file mode 100644 index 0000000..ba980dc --- /dev/null +++ b/ft-stripe/src/resources/tax_id.rs @@ -0,0 +1,185 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::TaxIdId; +use crate::params::{Expandable, Object, Timestamp}; +use crate::resources::Customer; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "tax_id". +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxId { + /// Unique identifier for the object. + pub id: TaxIdId, + + /// Two-letter ISO code representing the country of the tax ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub country: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + /// ID of the customer. + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option>, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Type of the tax ID, one of `au_abn`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_qst`, `ch_vat`, `es_cif`, `eu_vat`, `hk_br`, `in_gst`, `jp_cn`, `kr_brn`, `li_uid`, `mx_rfc`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `ru_inn`, `sg_gst`, `sg_uen`, `th_vat`, `tw_vat`, `us_ein`, or `za_vat`. + /// + /// Note that some legacy tax IDs have type `unknown`. + #[serde(rename = "type")] + #[serde(skip_serializing_if = "Option::is_none")] + pub type_: Option, + + /// Value of the tax ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +impl Object for TaxId { + type Id = TaxIdId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "tax_id" + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxIdVerification { + /// Verification status, one of `pending`, `verified`, `unverified`, or `unavailable`. + pub status: TaxIdVerificationStatus, + + /// Verified address. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_address: Option, + + /// Verified name. + #[serde(skip_serializing_if = "Option::is_none")] + pub verified_name: Option, +} + +/// An enum representing the possible values of an `TaxId`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TaxIdType { + AuAbn, + BrCnpj, + BrCpf, + CaBn, + CaQst, + ChVat, + EsCif, + EuVat, + HkBr, + InGst, + JpCn, + KrBrn, + LiUid, + MxRfc, + MyItn, + MySst, + NoVat, + NzGst, + RuInn, + SgGst, + SgUen, + ThVat, + TwVat, + Unknown, + UsEin, + ZaVat, +} + +impl TaxIdType { + pub fn as_str(self) -> &'static str { + match self { + TaxIdType::AuAbn => "au_abn", + TaxIdType::BrCnpj => "br_cnpj", + TaxIdType::BrCpf => "br_cpf", + TaxIdType::CaBn => "ca_bn", + TaxIdType::CaQst => "ca_qst", + TaxIdType::ChVat => "ch_vat", + TaxIdType::EsCif => "es_cif", + TaxIdType::EuVat => "eu_vat", + TaxIdType::HkBr => "hk_br", + TaxIdType::InGst => "in_gst", + TaxIdType::JpCn => "jp_cn", + TaxIdType::KrBrn => "kr_brn", + TaxIdType::LiUid => "li_uid", + TaxIdType::MxRfc => "mx_rfc", + TaxIdType::MyItn => "my_itn", + TaxIdType::MySst => "my_sst", + TaxIdType::NoVat => "no_vat", + TaxIdType::NzGst => "nz_gst", + TaxIdType::RuInn => "ru_inn", + TaxIdType::SgGst => "sg_gst", + TaxIdType::SgUen => "sg_uen", + TaxIdType::ThVat => "th_vat", + TaxIdType::TwVat => "tw_vat", + TaxIdType::Unknown => "unknown", + TaxIdType::UsEin => "us_ein", + TaxIdType::ZaVat => "za_vat", + } + } +} + +impl AsRef for TaxIdType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TaxIdType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `TaxIdVerification`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TaxIdVerificationStatus { + Pending, + Unavailable, + Unverified, + Verified, +} + +impl TaxIdVerificationStatus { + pub fn as_str(self) -> &'static str { + match self { + TaxIdVerificationStatus::Pending => "pending", + TaxIdVerificationStatus::Unavailable => "unavailable", + TaxIdVerificationStatus::Unverified => "unverified", + TaxIdVerificationStatus::Verified => "verified", + } + } +} + +impl AsRef for TaxIdVerificationStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TaxIdVerificationStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/tax_rate.rs b/ft-stripe/src/resources/tax_rate.rs new file mode 100644 index 0000000..109faa3 --- /dev/null +++ b/ft-stripe/src/resources/tax_rate.rs @@ -0,0 +1,247 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::TaxRateId; +use crate::params::{Expand, List, Metadata, Object, RangeQuery, Timestamp}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "TaxRate". +/// +/// For more details see [https://stripe.com/docs/api/tax_rates/object](https://stripe.com/docs/api/tax_rates/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TaxRate { + /// Unique identifier for the object. + pub id: TaxRateId, + + /// Defaults to `true`. + /// + /// When set to `false`, this tax rate cannot be applied to objects in the API, but will still be applied to subscriptions and invoices that already have it set. + pub active: bool, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// An arbitrary string attached to the tax rate for your internal use only. + /// + /// It will not be visible to your customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The display name of the tax rates as it will appear to your customer on their receipt email, PDF, and the hosted invoice page. + pub display_name: String, + + /// This specifies if the tax rate is inclusive or exclusive. + pub inclusive: bool, + + /// The jurisdiction for the tax rate. + #[serde(skip_serializing_if = "Option::is_none")] + pub jurisdiction: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// This represents the tax rate percent out of 100. + pub percentage: f64, +} + +impl TaxRate { + /// Returns a list of your tax rates. + /// + /// Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. + pub fn list(client: &Client, params: ListTaxRates<'_>) -> Response> { + client.get_query("/tax_rates", ¶ms) + } + + /// Creates a new tax rate. + pub fn create(client: &Client, params: CreateTaxRate<'_>) -> Response { + client.post_form("/tax_rates", ¶ms) + } + + /// Retrieves a tax rate with the given ID. + pub fn retrieve(client: &Client, id: &TaxRateId, expand: &[&str]) -> Response { + client.get_query(&format!("/tax_rates/{}", id), &Expand { expand }) + } + + /// Updates an existing tax rate. + pub fn update(client: &Client, id: &TaxRateId, params: UpdateTaxRate<'_>) -> Response { + client.post_form(&format!("/tax_rates/{}", id), ¶ms) + } +} + +impl Object for TaxRate { + type Id = TaxRateId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "tax_rate" + } +} + +/// The parameters for `TaxRate::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateTaxRate<'a> { + /// Flag determining whether the tax rate is active or inactive. + /// + /// Inactive tax rates continue to work where they are currently applied however they cannot be used for new applications. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// An arbitrary string attached to the tax rate for your internal use only. + /// + /// It will not be visible to your customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The display name of the tax rate, which will be shown to users. + pub display_name: &'a str, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// This specifies if the tax rate is inclusive or exclusive. + pub inclusive: bool, + + /// The jurisdiction for the tax rate. + #[serde(skip_serializing_if = "Option::is_none")] + pub jurisdiction: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// This represents the tax rate percent out of 100. + pub percentage: f64, +} + +impl<'a> CreateTaxRate<'a> { + pub fn new(display_name: &'a str, percentage: f64) -> Self { + CreateTaxRate { + active: Default::default(), + description: Default::default(), + display_name, + expand: Default::default(), + inclusive: Default::default(), + jurisdiction: Default::default(), + metadata: Default::default(), + percentage, + } + } +} + +/// The parameters for `TaxRate::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListTaxRates<'a> { + /// Optional flag to filter by tax rates that are either active or not active (archived). + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// Optional range for filtering created date. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Optional flag to filter by tax rates that are inclusive (or those that are not inclusive). + #[serde(skip_serializing_if = "Option::is_none")] + pub inclusive: Option, + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListTaxRates<'a> { + pub fn new() -> Self { + ListTaxRates { + active: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + inclusive: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `TaxRate::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateTaxRate<'a> { + /// Flag determining whether the tax rate is active or inactive. + /// + /// Inactive tax rates continue to work where they are currently applied however they cannot be used for new applications. + #[serde(skip_serializing_if = "Option::is_none")] + pub active: Option, + + /// An arbitrary string attached to the tax rate for your internal use only. + /// + /// It will not be visible to your customers. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The display name of the tax rate, which will be shown to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_name: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// The jurisdiction for the tax rate. + #[serde(skip_serializing_if = "Option::is_none")] + pub jurisdiction: Option<&'a str>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdateTaxRate<'a> { + pub fn new() -> Self { + UpdateTaxRate { + active: Default::default(), + description: Default::default(), + display_name: Default::default(), + expand: Default::default(), + jurisdiction: Default::default(), + metadata: Default::default(), + } + } +} diff --git a/ft-stripe/src/resources/token.rs b/ft-stripe/src/resources/token.rs new file mode 100644 index 0000000..82c93af --- /dev/null +++ b/ft-stripe/src/resources/token.rs @@ -0,0 +1,229 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{CustomerId, TokenId}; +use crate::params::{Expand, Metadata, Object, Timestamp}; +use crate::resources::{ + Address, BankAccount, BusinessType, Card, CompanyParams, Dob, PersonParams, TokenType, +}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Token". +/// +/// For more details see [https://stripe.com/docs/api/tokens/object](https://stripe.com/docs/api/tokens/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Token { + /// Unique identifier for the object. + pub id: TokenId, + + #[serde(skip_serializing_if = "Option::is_none")] + pub bank_account: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + + /// IP address of the client that generated the token. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_ip: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Type of the token: `account`, `bank_account`, `card`, or `pii`. + #[serde(rename = "type")] + pub type_: TokenType, + + /// Whether this token has already been used (tokens can be used only once). + pub used: bool, +} + +impl Token { + /// Creates a single-use token that represents a bank account’s details. + /// This token can be used with any API method in place of a bank account dictionary. + /// + /// This token can be used only once, by attaching it to a [Custom account](https://stripe.com/docs/api#accounts). + pub fn create(client: &Client, params: CreateToken<'_>) -> Response { + client.post_form("/tokens", ¶ms) + } + + /// Retrieves the token with the given ID. + pub fn retrieve(client: &Client, id: &TokenId, expand: &[&str]) -> Response { + client.get_query(&format!("/tokens/{}", id), &Expand { expand }) + } +} + +impl Object for Token { + type Id = TokenId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "token" + } +} + +/// The parameters for `Token::create`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct CreateToken<'a> { + /// Information for the account this token will represent. + #[serde(skip_serializing_if = "Option::is_none")] + pub account: Option, + + /// The customer (owned by the application's account) for which to create a token. + /// + /// This can be used only with an [OAuth access token](https://stripe.com/docs/connect/standard-accounts) or [Stripe-Account header](https://stripe.com/docs/connect/authentication). + /// For more details, see [Cloning Saved Payment Methods](https://stripe.com/docs/connect/cloning-saved-payment-methods). + #[serde(skip_serializing_if = "Option::is_none")] + pub customer: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Information for the person this token will represent. + #[serde(skip_serializing_if = "Option::is_none")] + pub person: Option, + + /// The PII this token will represent. + #[serde(skip_serializing_if = "Option::is_none")] + pub pii: Option, +} + +impl<'a> CreateToken<'a> { + pub fn new() -> Self { + CreateToken { + account: Default::default(), + customer: Default::default(), + expand: Default::default(), + person: Default::default(), + pii: Default::default(), + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateTokenAccount { + #[serde(skip_serializing_if = "Option::is_none")] + pub business_type: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub company: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub individual: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub tos_shown_and_accepted: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateTokenPerson { + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kana: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub address_kanji: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub dob: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub first_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub gender: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id_number: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kana: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub last_name_kanji: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub maiden_name: Option, + + #[serde(default)] + pub metadata: Metadata, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub relationship: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub ssn_last_4: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub verification: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateTokenPii { + #[serde(skip_serializing_if = "Option::is_none")] + pub id_number: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CreateTokenPersonRelationship { + #[serde(skip_serializing_if = "Option::is_none")] + pub director: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub executive: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub percent_ownership: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub representative: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PersonVerificationParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_document: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub document: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct VerificationDocumentParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub back: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub front: Option, +} diff --git a/ft-stripe/src/resources/token_ext.rs b/ft-stripe/src/resources/token_ext.rs new file mode 100644 index 0000000..8763f40 --- /dev/null +++ b/ft-stripe/src/resources/token_ext.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `Token`'s `type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TokenType { + Account, + BankAccount, + Card, + Pii, +} + +impl TokenType { + pub fn as_str(self) -> &'static str { + match self { + TokenType::Account => "account", + TokenType::BankAccount => "bank_account", + TokenType::Card => "card", + TokenType::Pii => "pii", + } + } +} + +impl AsRef for TokenType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TokenType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/topup.rs b/ft-stripe/src/resources/topup.rs new file mode 100644 index 0000000..ff2b9e2 --- /dev/null +++ b/ft-stripe/src/resources/topup.rs @@ -0,0 +1,271 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::TopupId; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{BalanceTransaction, Currency, Source}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Topup". +/// +/// For more details see [https://stripe.com/docs/api/topups/object](https://stripe.com/docs/api/topups/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Topup { + /// Unique identifier for the object. + pub id: TopupId, + + /// Amount transferred. + pub amount: i64, + + /// ID of the balance transaction that describes the impact of this top-up on your account balance. + /// + /// May not be specified depending on status of top-up. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// Date the funds are expected to arrive in your Stripe account for payouts. + /// + /// This factors in delays like weekends or bank holidays. + /// May not be specified depending on status of top-up. + #[serde(skip_serializing_if = "Option::is_none")] + pub expected_availability_date: Option, + + /// Error code explaining reason for top-up failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_code: Option, + + /// Message to user further explaining reason for top-up failure if available. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_message: Option, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + pub source: Source, + + /// Extra information about a top-up. + /// + /// This will appear on your source's bank statement. + /// It must contain at least one letter. + #[serde(skip_serializing_if = "Option::is_none")] + pub statement_descriptor: Option, + + /// The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. + pub status: TopupStatus, + + /// A string that identifies this top-up as part of a group. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option, +} + +impl Topup { + /// Returns a list of top-ups. + pub fn list(client: &Client, params: ListTopups<'_>) -> Response> { + client.get_query("/topups", ¶ms) + } + + /// Retrieves the details of a top-up that has previously been created. + /// + /// Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. + pub fn retrieve(client: &Client, id: &TopupId, expand: &[&str]) -> Response { + client.get_query(&format!("/topups/{}", id), &Expand { expand }) + } + + /// Updates the metadata of a top-up. + /// + /// Other top-up details are not editable by design. + pub fn update(client: &Client, id: &TopupId, params: UpdateTopup<'_>) -> Response { + client.post_form(&format!("/topups/{}", id), ¶ms) + } +} + +impl Object for Topup { + type Id = TopupId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "topup" + } +} + +/// The parameters for `Topup::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListTopups<'a> { + /// A positive integer representing how much to transfer. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option>, + + /// A filter on the list, based on the object `created` field. + /// + /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return top-ups that have the given status. + /// + /// One of `canceled`, `failed`, `pending` or `succeeded`. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl<'a> ListTopups<'a> { + pub fn new() -> Self { + ListTopups { + amount: Default::default(), + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + status: Default::default(), + } + } +} + +/// The parameters for `Topup::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateTopup<'a> { + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdateTopup<'a> { + pub fn new() -> Self { + UpdateTopup { + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + } + } +} + +/// An enum representing the possible values of an `Topup`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TopupStatus { + Canceled, + Failed, + Pending, + Reversed, + Succeeded, +} + +impl TopupStatus { + pub fn as_str(self) -> &'static str { + match self { + TopupStatus::Canceled => "canceled", + TopupStatus::Failed => "failed", + TopupStatus::Pending => "pending", + TopupStatus::Reversed => "reversed", + TopupStatus::Succeeded => "succeeded", + } + } +} + +impl AsRef for TopupStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TopupStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of an `ListTopups`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TopupStatusFilter { + Canceled, + Failed, + Pending, + Succeeded, +} + +impl TopupStatusFilter { + pub fn as_str(self) -> &'static str { + match self { + TopupStatusFilter::Canceled => "canceled", + TopupStatusFilter::Failed => "failed", + TopupStatusFilter::Pending => "pending", + TopupStatusFilter::Succeeded => "succeeded", + } + } +} + +impl AsRef for TopupStatusFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TopupStatusFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/transfer.rs b/ft-stripe/src/resources/transfer.rs new file mode 100644 index 0000000..778c389 --- /dev/null +++ b/ft-stripe/src/resources/transfer.rs @@ -0,0 +1,303 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::{ChargeId, TransferId}; +use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; +use crate::resources::{Account, BalanceTransaction, Charge, Currency, TransferReversal}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "Transfer". +/// +/// For more details see [https://stripe.com/docs/api/transfers/object](https://stripe.com/docs/api/transfers/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Transfer { + /// Unique identifier for the object. + pub id: TransferId, + + /// Amount in %s to be transferred. + pub amount: i64, + + /// Amount in %s reversed (can be less than the amount attribute on the transfer if a partial reversal was issued). + pub amount_reversed: i64, + + /// Balance transaction that describes the impact of this transfer on your account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// Time that this record of the transfer was first created. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// ID of the Stripe account the transfer was sent to. + #[serde(skip_serializing_if = "Option::is_none")] + pub destination: Option>, + + /// If the destination is a Stripe account, this will be the ID of the payment that the destination account received for the transfer. + #[serde(skip_serializing_if = "Option::is_none")] + pub destination_payment: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + pub livemode: bool, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// A list of reversals that have been applied to the transfer. + pub reversals: List, + + /// Whether the transfer has been fully reversed. + /// + /// If the transfer is only partially reversed, this attribute will still be false. + pub reversed: bool, + + /// ID of the charge or payment that was used to fund the transfer. + /// + /// If null, the transfer was funded from the available balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_transaction: Option>, + + /// The source balance this transfer came from. + /// + /// One of `card`, `fpx`, or `bank_account`. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_type: Option, + + /// A string that identifies this transaction as part of a group. + /// + /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option, +} + +impl Transfer { + /// Returns a list of existing transfers sent to connected accounts. + /// + /// The transfers are returned in sorted order, with the most recently created transfers appearing first. + pub fn list(client: &Client, params: ListTransfers<'_>) -> Response> { + client.get_query("/transfers", ¶ms) + } + + /// To send funds from your Stripe account to a connected account, you create a new transfer object. + /// + /// Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the transfer amount, or you’ll receive an “Insufficient Funds” error. + pub fn create(client: &Client, params: CreateTransfer<'_>) -> Response { + client.post_form("/transfers", ¶ms) + } + + /// Retrieves the details of an existing transfer. + /// + /// Supply the unique transfer ID from either a transfer creation request or the transfer list, and Stripe will return the corresponding transfer information. + pub fn retrieve(client: &Client, id: &TransferId, expand: &[&str]) -> Response { + client.get_query(&format!("/transfers/{}", id), &Expand { expand }) + } + + /// Updates the specified transfer by setting the values of the parameters passed. + /// + /// Any parameters not provided will be left unchanged. This request accepts only metadata as an argument. + pub fn update( + client: &Client, + id: &TransferId, + params: UpdateTransfer<'_>, + ) -> Response { + client.post_form(&format!("/transfers/{}", id), ¶ms) + } +} + +impl Object for Transfer { + type Id = TransferId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "transfer" + } +} + +/// The parameters for `Transfer::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateTransfer<'a> { + /// A positive integer in %s representing how much to transfer. + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + /// 3-letter [ISO code for currency](https://stripe.com/docs/payouts). + pub currency: Currency, + + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// You can use this parameter to transfer funds from a charge before they are added to your available balance. + /// + /// A pending balance will transfer immediately but the funds will not become available until the original charge becomes available. + /// [See the Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-availability) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_transaction: Option, + + /// The source balance to use for this transfer. + /// + /// One of `bank_account`, `card`, or `fpx`. + /// For most users, this will default to `card`. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_type: Option, + + /// A string that identifies this transaction as part of a group. + /// + /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> CreateTransfer<'a> { + pub fn new(currency: Currency) -> Self { + CreateTransfer { + amount: Default::default(), + currency, + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + source_transaction: Default::default(), + source_type: Default::default(), + transfer_group: Default::default(), + } + } +} + +/// The parameters for `Transfer::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListTransfers<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option>, + + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, + + /// Only return transfers with the specified transfer group. + #[serde(skip_serializing_if = "Option::is_none")] + pub transfer_group: Option<&'a str>, +} + +impl<'a> ListTransfers<'a> { + pub fn new() -> Self { + ListTransfers { + created: Default::default(), + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + transfer_group: Default::default(), + } + } +} + +/// The parameters for `Transfer::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateTransfer<'a> { + /// An arbitrary string attached to the object. + /// + /// Often useful for displaying to users. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl<'a> UpdateTransfer<'a> { + pub fn new() -> Self { + UpdateTransfer { + description: Default::default(), + expand: Default::default(), + metadata: Default::default(), + } + } +} + +/// An enum representing the possible values of an `CreateTransfer`'s `source_type` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TransferSourceType { + BankAccount, + Card, + Fpx, +} + +impl TransferSourceType { + pub fn as_str(self) -> &'static str { + match self { + TransferSourceType::BankAccount => "bank_account", + TransferSourceType::Card => "card", + TransferSourceType::Fpx => "fpx", + } + } +} + +impl AsRef for TransferSourceType { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for TransferSourceType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/transfer_reversal.rs b/ft-stripe/src/resources/transfer_reversal.rs new file mode 100644 index 0000000..5f1ca6c --- /dev/null +++ b/ft-stripe/src/resources/transfer_reversal.rs @@ -0,0 +1,60 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::ids::TransferReversalId; +use crate::params::{Expandable, Metadata, Object, Timestamp}; +use crate::resources::{BalanceTransaction, Currency, Refund, Transfer}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "TransferReversal". +/// +/// For more details see [https://stripe.com/docs/api/transfer_reversals/object](https://stripe.com/docs/api/transfer_reversals/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct TransferReversal { + /// Unique identifier for the object. + pub id: TransferReversalId, + + /// Amount, in %s. + pub amount: i64, + + /// Balance transaction that describes the impact on your account balance. + #[serde(skip_serializing_if = "Option::is_none")] + pub balance_transaction: Option>, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + pub created: Timestamp, + + /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. + /// + /// Must be a [supported currency](https://stripe.com/docs/currencies). + pub currency: Currency, + + /// Linked payment refund for the transfer reversal. + #[serde(skip_serializing_if = "Option::is_none")] + pub destination_payment_refund: Option>, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + pub metadata: Metadata, + + /// ID of the refund responsible for the transfer reversal. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_refund: Option>, + + /// ID of the transfer that was reversed. + pub transfer: Expandable, +} + +impl Object for TransferReversal { + type Id = TransferReversalId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "transfer_reversal" + } +} diff --git a/ft-stripe/src/resources/types.rs b/ft-stripe/src/resources/types.rs new file mode 100644 index 0000000..78c4a48 --- /dev/null +++ b/ft-stripe/src/resources/types.rs @@ -0,0 +1,725 @@ +use crate::params::Timestamp; +use crate::resources::card::{CardBrand, CardType}; +use serde::{Deserialize, Serialize}; + +/// An enum representing the versions of the Stripe API. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ApiVersion { + #[serde(rename = "2011-01-01")] + V2011_01_01, + #[serde(rename = "2011-06-21")] + V2011_06_21, + #[serde(rename = "2011-06-28")] + V2011_06_28, + #[serde(rename = "2011-08-01")] + V2011_08_01, + #[serde(rename = "2011-09-15")] + V2011_09_15, + #[serde(rename = "2011-11-17")] + V2011_11_17, + #[serde(rename = "2012-02-23")] + V2012_02_23, + #[serde(rename = "2012-03-25")] + V2012_03_25, + #[serde(rename = "2012-06-18")] + V2012_06_18, + #[serde(rename = "2012-06-28")] + V2012_06_28, + #[serde(rename = "2012-07-09")] + V2012_07_09, + #[serde(rename = "2012-09-24")] + V2012_09_24, + #[serde(rename = "2012-10-26")] + V2012_10_26, + #[serde(rename = "2012-11-07")] + V2012_11_07, + #[serde(rename = "2013-02-11")] + V2013_02_11, + #[serde(rename = "2013-02-13")] + V2013_02_13, + #[serde(rename = "2013-07-05")] + V2013_07_05, + #[serde(rename = "2013-08-12")] + V2013_08_12, + #[serde(rename = "2013-08-13")] + V2013_08_13, + #[serde(rename = "2013-10-29")] + V2013_10_29, + #[serde(rename = "2013-12-03")] + V2013_12_03, + #[serde(rename = "2014-01-31")] + V2014_01_31, + #[serde(rename = "2014-03-13")] + V2014_03_13, + #[serde(rename = "2014-03-28")] + V2014_03_28, + #[serde(rename = "2014-05-19")] + V2014_05_19, + #[serde(rename = "2014-06-13")] + V2014_06_13, + #[serde(rename = "2014-06-17")] + V2014_06_17, + #[serde(rename = "2014-07-22")] + V2014_07_22, + #[serde(rename = "2014-07-26")] + V2014_07_26, + #[serde(rename = "2014-08-04")] + V2014_08_04, + #[serde(rename = "2014-08-20")] + V2014_08_20, + #[serde(rename = "2014-09-08")] + V2014_09_08, + #[serde(rename = "2014-10-07")] + V2014_10_07, + #[serde(rename = "2014-11-05")] + V2014_11_05, + #[serde(rename = "2014-11-20")] + V2014_11_20, + #[serde(rename = "2014-12-08")] + V2014_12_08, + #[serde(rename = "2014-12-17")] + V2014_12_17, + #[serde(rename = "2014-12-22")] + V2014_12_22, + #[serde(rename = "2015-01-11")] + V2015_01_11, + #[serde(rename = "2015-01-26")] + V2015_01_26, + #[serde(rename = "2015-02-10")] + V2015_02_10, + #[serde(rename = "2015-02-16")] + V2015_02_16, + #[serde(rename = "2015-02-18")] + V2015_02_18, + #[serde(rename = "2015-03-24")] + V2015_03_24, + #[serde(rename = "2015-04-07")] + V2015_04_07, + #[serde(rename = "2015-06-15")] + V2015_06_15, + #[serde(rename = "2015-07-07")] + V2015_07_07, + #[serde(rename = "2015-07-13")] + V2015_07_13, + #[serde(rename = "2015-07-28")] + V2015_07_28, + #[serde(rename = "2015-08-07")] + V2015_08_07, + #[serde(rename = "2015-08-19")] + V2015_08_19, + #[serde(rename = "2015-09-03")] + V2015_09_03, + #[serde(rename = "2015-09-08")] + V2015_09_08, + #[serde(rename = "2015-09-23")] + V2015_09_23, + #[serde(rename = "2015-10-01")] + V2015_10_01, + #[serde(rename = "2015-10-12")] + V2015_10_12, + #[serde(rename = "2015-10-16")] + V2015_10_16, + #[serde(rename = "2016-02-03")] + V2016_02_03, + #[serde(rename = "2016-02-19")] + V2016_02_19, + #[serde(rename = "2016-02-22")] + V2016_02_22, + #[serde(rename = "2016-02-23")] + V2016_02_23, + #[serde(rename = "2016-02-29")] + V2016_02_29, + #[serde(rename = "2016-03-07")] + V2016_03_07, + #[serde(rename = "2016-06-15")] + V2016_06_15, + #[serde(rename = "2016-07-06")] + V2016_07_06, + #[serde(rename = "2016-10-19")] + V2016_10_19, + #[serde(rename = "2017-01-27")] + V2017_01_27, + #[serde(rename = "2017-02-14")] + V2017_02_14, + #[serde(rename = "2017-04-06")] + V2017_04_06, + #[serde(rename = "2017-05-25")] + V2017_05_25, + #[serde(rename = "2017-06-05")] + V2017_06_05, + #[serde(rename = "2017-08-15")] + V2017_08_15, + #[serde(rename = "2017-12-14")] + V2017_12_14, + #[serde(rename = "2018-01-23")] + V2018_01_23, + #[serde(rename = "2018-02-05")] + V2018_02_05, + #[serde(rename = "2018-02-06")] + V2018_02_06, + #[serde(rename = "2018-02-28")] + V2018_02_28, + #[serde(rename = "2018-05-21")] + V2018_05_21, + #[serde(rename = "2018-07-27")] + V2018_07_27, + #[serde(rename = "2018-08-23")] + V2018_08_23, + #[serde(rename = "2018-09-06")] + V2018_09_06, + #[serde(rename = "2018-09-24")] + V2018_09_24, + #[serde(rename = "2018-10-31")] + V2018_10_31, + #[serde(rename = "2018-11-08")] + V2018_11_08, + #[serde(rename = "2019-02-11")] + V2019_02_11, + #[serde(rename = "2019-02-19")] + V2019_02_19, + #[serde(rename = "2019-03-14")] + V2019_03_14, + #[serde(rename = "2019-05-16")] + V2019_05_16, + #[serde(rename = "2019-08-14")] + V2019_08_14, + #[serde(rename = "2019-09-09")] + V2019_09_09, +} + +impl ApiVersion { + pub fn as_str(self) -> &'static str { + match self { + ApiVersion::V2011_01_01 => "2011-01-01", + ApiVersion::V2011_06_21 => "2011-06-21", + ApiVersion::V2011_06_28 => "2011-06-28", + ApiVersion::V2011_08_01 => "2011-08-01", + ApiVersion::V2011_09_15 => "2011-09-15", + ApiVersion::V2011_11_17 => "2011-11-17", + ApiVersion::V2012_02_23 => "2012-02-23", + ApiVersion::V2012_03_25 => "2012-03-25", + ApiVersion::V2012_06_18 => "2012-06-18", + ApiVersion::V2012_06_28 => "2012-06-28", + ApiVersion::V2012_07_09 => "2012-07-09", + ApiVersion::V2012_09_24 => "2012-09-24", + ApiVersion::V2012_10_26 => "2012-10-26", + ApiVersion::V2012_11_07 => "2012-11-07", + ApiVersion::V2013_02_11 => "2013-02-11", + ApiVersion::V2013_02_13 => "2013-02-13", + ApiVersion::V2013_07_05 => "2013-07-05", + ApiVersion::V2013_08_12 => "2013-08-12", + ApiVersion::V2013_08_13 => "2013-08-13", + ApiVersion::V2013_10_29 => "2013-10-29", + ApiVersion::V2013_12_03 => "2013-12-03", + ApiVersion::V2014_01_31 => "2014-01-31", + ApiVersion::V2014_03_13 => "2014-03-13", + ApiVersion::V2014_03_28 => "2014-03-28", + ApiVersion::V2014_05_19 => "2014-05-19", + ApiVersion::V2014_06_13 => "2014-06-13", + ApiVersion::V2014_06_17 => "2014-06-17", + ApiVersion::V2014_07_22 => "2014-07-22", + ApiVersion::V2014_07_26 => "2014-07-26", + ApiVersion::V2014_08_04 => "2014-08-04", + ApiVersion::V2014_08_20 => "2014-08-20", + ApiVersion::V2014_09_08 => "2014-09-08", + ApiVersion::V2014_10_07 => "2014-10-07", + ApiVersion::V2014_11_05 => "2014-11-05", + ApiVersion::V2014_11_20 => "2014-11-20", + ApiVersion::V2014_12_08 => "2014-12-08", + ApiVersion::V2014_12_17 => "2014-12-17", + ApiVersion::V2014_12_22 => "2014-12-22", + ApiVersion::V2015_01_11 => "2015-01-11", + ApiVersion::V2015_01_26 => "2015-01-26", + ApiVersion::V2015_02_10 => "2015-02-10", + ApiVersion::V2015_02_16 => "2015-02-16", + ApiVersion::V2015_02_18 => "2015-02-18", + ApiVersion::V2015_03_24 => "2015-03-24", + ApiVersion::V2015_04_07 => "2015-04-07", + ApiVersion::V2015_06_15 => "2015-06-15", + ApiVersion::V2015_07_07 => "2015-07-07", + ApiVersion::V2015_07_13 => "2015-07-13", + ApiVersion::V2015_07_28 => "2015-07-28", + ApiVersion::V2015_08_07 => "2015-08-07", + ApiVersion::V2015_08_19 => "2015-08-19", + ApiVersion::V2015_09_03 => "2015-09-03", + ApiVersion::V2015_09_08 => "2015-09-08", + ApiVersion::V2015_09_23 => "2015-09-23", + ApiVersion::V2015_10_01 => "2015-10-01", + ApiVersion::V2015_10_12 => "2015-10-12", + ApiVersion::V2015_10_16 => "2015-10-16", + ApiVersion::V2016_02_03 => "2016-02-03", + ApiVersion::V2016_02_19 => "2016-02-19", + ApiVersion::V2016_02_22 => "2016-02-22", + ApiVersion::V2016_02_23 => "2016-02-23", + ApiVersion::V2016_02_29 => "2016-02-29", + ApiVersion::V2016_03_07 => "2016-03-07", + ApiVersion::V2016_06_15 => "2016-06-15", + ApiVersion::V2016_07_06 => "2016-07-06", + ApiVersion::V2016_10_19 => "2016-10-19", + ApiVersion::V2017_01_27 => "2017-01-27", + ApiVersion::V2017_02_14 => "2017-02-14", + ApiVersion::V2017_04_06 => "2017-04-06", + ApiVersion::V2017_05_25 => "2017-05-25", + ApiVersion::V2017_06_05 => "2017-06-05", + ApiVersion::V2017_08_15 => "2017-08-15", + ApiVersion::V2017_12_14 => "2017-12-14", + ApiVersion::V2018_01_23 => "2018-01-23", + ApiVersion::V2018_02_05 => "2018-02-05", + ApiVersion::V2018_02_06 => "2018-02-06", + ApiVersion::V2018_02_28 => "2018-02-28", + ApiVersion::V2018_05_21 => "2018-05-21", + ApiVersion::V2018_07_27 => "2018-07-27", + ApiVersion::V2018_08_23 => "2018-08-23", + ApiVersion::V2018_09_06 => "2018-09-06", + ApiVersion::V2018_09_24 => "2018-09-24", + ApiVersion::V2018_10_31 => "2018-10-31", + ApiVersion::V2018_11_08 => "2018-11-08", + ApiVersion::V2019_02_11 => "2019-02-11", + ApiVersion::V2019_02_19 => "2019-02-19", + ApiVersion::V2019_03_14 => "2019-03-14", + ApiVersion::V2019_05_16 => "2019-05-16", + ApiVersion::V2019_08_14 => "2019-08-14", + ApiVersion::V2019_09_09 => "2019-09-09", + } + } +} + +impl AsRef for ApiVersion { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for ApiVersion { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} + +/// An enum representing the possible values of a `BankAccount`'s `account_holder_type` field. +/// +/// For more details see [https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_type](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_type) +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum AccountHolderType { + Individual, + Company, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Address { + /// Address line 1 or block/building number (e.g. Street address/PO Box/Company name) + pub line1: Option, + /// Address line 2 or building details (e.g. Apartment/Suite/Unit/Building) + pub line2: Option, + /// City (or Ward) + pub city: Option, + /// State (or Prefecture) + pub state: Option, + /// ZIP or postal code + pub postal_code: Option, + /// Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)) + pub country: Option, + /// The town/cho-me (Japan only) + pub town: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct BillingDetails { + #[serde(skip_serializing_if = "Option::is_none")] + pub address: Option
, + + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CustomField { + pub name: String, + pub value: String, +} + +/// A date of birth. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Dob { + pub day: i64, + pub month: i64, + pub year: i64, +} + +/// An enum representing the possible values of a `FraudDetails`'s `report` fields. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum FraudDetailsReport { + Fraudulent, + Safe, +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct PackageDimensions { + pub height: f64, + pub length: f64, + pub weight: f64, + pub width: f64, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodAchDebit { + /// Type of entity that holds the account. This can be either `individual` or `company`. + pub account_holder_type: AccountHolderType, + + /// Name of the bank associated with the bank account. + pub bank_name: String, + + /// Two-letter ISO code representing the country the bank account is located in. + pub country: String, + + /// Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. + pub fingerprint: String, + + /// Last four digits of the bank account number. + pub last4: String, + + /// Routing transit number of the bank account. + pub routing_number: String, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +pub enum PaymentMethodCardBrand { + #[serde(rename = "amex")] + AmericanExpress, + #[serde(rename = "diners")] + DinersClub, + #[serde(rename = "discover")] + Discover, + #[serde(rename = "jcb")] + JCB, + #[serde(rename = "visa")] + Visa, + #[serde(rename = "mastercard")] + MasterCard, + #[serde(rename = "unionpay")] + UnionPay, + + /// An unknown card brand. + /// + /// May also be a variant not yet supported by the library. + #[serde(other)] + #[serde(rename = "unknown")] + Unknown, +} + +impl From for CardBrand { + fn from(brand: PaymentMethodCardBrand) -> Self { + match brand { + PaymentMethodCardBrand::AmericanExpress => CardBrand::AmericanExpress, + PaymentMethodCardBrand::DinersClub => CardBrand::DinersClub, + PaymentMethodCardBrand::Discover => CardBrand::Discover, + PaymentMethodCardBrand::JCB => CardBrand::JCB, + PaymentMethodCardBrand::Visa => CardBrand::Visa, + PaymentMethodCardBrand::MasterCard => CardBrand::MasterCard, + PaymentMethodCardBrand::UnionPay => CardBrand::UnionPay, + PaymentMethodCardBrand::Unknown => CardBrand::Unknown, + } + } +} + +impl From for PaymentMethodCardBrand { + fn from(brand: CardBrand) -> Self { + match brand { + CardBrand::AmericanExpress => PaymentMethodCardBrand::AmericanExpress, + CardBrand::DinersClub => PaymentMethodCardBrand::DinersClub, + CardBrand::Discover => PaymentMethodCardBrand::Discover, + CardBrand::JCB => PaymentMethodCardBrand::JCB, + CardBrand::Visa => PaymentMethodCardBrand::Visa, + CardBrand::MasterCard => PaymentMethodCardBrand::MasterCard, + CardBrand::UnionPay => PaymentMethodCardBrand::UnionPay, + CardBrand::Unknown => PaymentMethodCardBrand::Unknown, + } + } +} + +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +pub struct PaymentMethodCard { + /// Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub brand: Option, + + /// Two-letter ISO code representing the country of the card. + /// + /// You could use this attribute to get a sense of the international breakdown of cards you've collected. + pub country: String, + + /// Two-digit number representing the card's expiration month. + pub exp_month: i64, + + /// Four-digit number representing the card's expiration year. + pub exp_year: i64, + + /// Uniquely identifies this particular card number. + /// + /// You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. + pub fingerprint: String, + + /// Card funding type. + /// + /// Can be `credit`, `debit`, `prepaid`, or `unknown`. + #[serde(skip_serializing_if = "Option::is_none")] + pub funding: Option, + + /// The last four digits of the card. + pub last4: String, +} + +// TODO: Implement +/// This type is a stub that still needs to be implemented. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum PaymentMethodDetailsType { + AchDebit, + Card, + + /// An unknown payment method details type. + /// + /// May also be a variant not yet supported by the library. + #[serde(other)] + Unknown, +} + +// TODO: Implement +/// This type is a stub that still needs to be implemented. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct PaymentMethodDetails { + #[serde(skip_serializing_if = "Option::is_none")] + pub ach_debit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub card: Option, + pub r#type: PaymentMethodDetailsType, +} + +/// Period is a structure representing a start and end dates. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Period { + pub start: Timestamp, + pub end: Timestamp, +} + +/// OpenPeriod is a structure representing a possibly open-ended period with optional start and end dates. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct OpenPeriod { + pub start: Option, + pub end: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Shipping { + pub name: String, + pub address: Address, + #[serde(skip_serializing_if = "Option::is_none")] + pub carrier: Option, // eg. Fedex, UPS, USPS + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tracking_number: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct ShippingParams { + pub address: Address, + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SpendingLimit { + /// Maximum amount allowed to spend per time interval. + pub amount: i64, + + /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) on which to apply the spending limit. + /// + /// Leave this blank to limit all charges. + #[serde(skip_serializing_if = "Option::is_none")] + pub categories: Option>, + + /// The time interval with which to apply this spending limit towards. + /// + /// Allowed values are `per_authorization`, `daily`, `weekly`, `monthly`, `yearly`, or `all_time`. + pub interval: SpendingLimitInterval, +} + +/// An enum representing the possible values of an `SpendingLimit`'s `interval` field. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SpendingLimitInterval { + AllTime, + Daily, + Monthly, + PerAuthorization, + Weekly, + Yearly, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionBillingThresholds { + #[serde(skip_serializing_if = "Option::is_none")] + pub amount_gte: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reset_billing_cycle_anchor: Option, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(untagged)] +pub enum DelayDays { + Days(u32), + Other(DelayDaysOther), +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum DelayDaysOther { + Minimum, +} + +impl DelayDays { + pub fn days(n: u32) -> Self { + DelayDays::Days(n) + } + pub fn minimum() -> Self { + DelayDays::Other(DelayDaysOther::Minimum) + } +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(untagged)] +pub enum Scheduled { + Timestamp(Timestamp), + Other(ScheduledOther), +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ScheduledOther { + Now, +} + +impl Scheduled { + pub fn at(ts: Timestamp) -> Self { + Scheduled::Timestamp(ts) + } + pub fn now() -> Self { + Scheduled::Other(ScheduledOther::Now) + } +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(untagged)] +pub enum UpTo { + Max(u64), + Other(UpToOther), +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum UpToOther { + Inf, +} + +impl UpTo { + pub fn max(n: u64) -> Self { + UpTo::Max(n) + } + pub fn now() -> Self { + UpTo::Other(UpToOther::Inf) + } +} + +/// A day of the week. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Weekday { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(untagged)] +pub enum PaymentIntentOffSession { + Exists(bool), + Other(OffSessionOther), +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum OffSessionOther { + #[serde(rename = "one_off")] + OneOff, + #[serde(rename = "recurring")] + Recurring, +} + +impl PaymentIntentOffSession { + pub fn exists(n: bool) -> Self { + PaymentIntentOffSession::Exists(n) + } + pub fn frequency(n: OffSessionOther) -> Self { + match n { + OffSessionOther::OneOff => PaymentIntentOffSession::Other(OffSessionOther::OneOff), + OffSessionOther::Recurring => { + PaymentIntentOffSession::Other(OffSessionOther::Recurring) + } + } + } +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum SetupIntentUsage { + #[serde(rename = "on_session")] + OnSession, + #[serde(rename = "off_session")] + OffSession, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct SubscriptionItemBillingThresholds { + pub usage_gte: i64, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum BusinessType { + Individual, + Company, +} + +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ApiErrors { + #[serde(rename = "api_connection_error")] + ApiConnectionError, + #[serde(rename = "api_error")] + ApiError, + #[serde(rename = "authentication_error")] + AuthenticationError, + #[serde(rename = "card_error")] + CardError, + #[serde(rename = "idempotency_error")] + IdempotencyError, + #[serde(rename = "invalid_request_error")] + InvalidRequestError, + #[serde(rename = "rate_limit_error")] + RateLimitError, +} diff --git a/ft-stripe/src/resources/webhook_endpoint.rs b/ft-stripe/src/resources/webhook_endpoint.rs new file mode 100644 index 0000000..a9fa56e --- /dev/null +++ b/ft-stripe/src/resources/webhook_endpoint.rs @@ -0,0 +1,744 @@ +// ====================================== +// This file was automatically generated. +// ====================================== + +use crate::config::{Client, Response}; +use crate::ids::WebhookEndpointId; +use crate::params::{Deleted, Expand, List, Metadata, Object, Timestamp}; +use crate::resources::{ApiVersion, WebhookEndpointStatus}; +use serde::{Deserialize, Serialize}; + +/// The resource representing a Stripe "NotificationWebhookEndpoint". +/// +/// For more details see [https://stripe.com/docs/api/webhook_endpoints/object](https://stripe.com/docs/api/webhook_endpoints/object). +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WebhookEndpoint { + /// Unique identifier for the object. + pub id: WebhookEndpointId, + + /// The API version events are rendered as for this webhook endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub api_version: Option, + + /// The ID of the associated Connect application. + #[serde(skip_serializing_if = "Option::is_none")] + pub application: Option, + + /// Time at which the object was created. + /// + /// Measured in seconds since the Unix epoch. + #[serde(skip_serializing_if = "Option::is_none")] + pub created: Option, + + // Always true for a deleted object + #[serde(default)] + pub deleted: bool, + + /// An optional description of what the wehbook is used for. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + + /// The list of events to enable for this endpoint. + /// + /// `['*']` indicates that all events are enabled, except those that require explicit selection. + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled_events: Option>, + + /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub livemode: Option, + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + #[serde(default)] + pub metadata: Metadata, + + /// The endpoint's secret, used to generate [webhook signatures](https://stripe.com/docs/webhooks/signatures). + /// + /// Only returned at creation. + #[serde(skip_serializing_if = "Option::is_none")] + pub secret: Option, + + /// The status of the webhook. + /// + /// It can be `enabled` or `disabled`. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + /// The URL of the webhook endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +impl WebhookEndpoint { + /// Returns a list of your webhook endpoints. + pub fn list( + client: &Client, + params: ListWebhookEndpoints<'_>, + ) -> Response> { + client.get_query("/webhook_endpoints", ¶ms) + } + + /// A webhook endpoint must have a `url` and a list of `enabled_events`. + /// + /// You may optionally specify the Boolean `connect` parameter. + /// If set to true, then a Connect webhook endpoint that notifies the specified `url` about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified `url` only about events from your account is created. + /// You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. + pub fn create(client: &Client, params: CreateWebhookEndpoint<'_>) -> Response { + client.post_form("/webhook_endpoints", ¶ms) + } + + /// Retrieves the webhook endpoint with the given ID. + pub fn retrieve( + client: &Client, + id: &WebhookEndpointId, + expand: &[&str], + ) -> Response { + client.get_query(&format!("/webhook_endpoints/{}", id), &Expand { expand }) + } + + /// Updates the webhook endpoint. + /// + /// You may edit the `url`, the list of `enabled_events`, and the status of your endpoint. + pub fn update( + client: &Client, + id: &WebhookEndpointId, + params: UpdateWebhookEndpoint<'_>, + ) -> Response { + client.post_form(&format!("/webhook_endpoints/{}", id), ¶ms) + } + + /// You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. + pub fn delete(client: &Client, id: &WebhookEndpointId) -> Response> { + client.delete(&format!("/webhook_endpoints/{}", id)) + } +} + +impl Object for WebhookEndpoint { + type Id = WebhookEndpointId; + fn id(&self) -> Self::Id { + self.id.clone() + } + fn object(&self) -> &'static str { + "webhook_endpoint" + } +} + +/// The parameters for `WebhookEndpoint::create`. +#[derive(Clone, Debug, Serialize)] +pub struct CreateWebhookEndpoint<'a> { + /// Events sent to this endpoint will be generated with this Stripe Version instead of your account's default Stripe Version. + #[serde(skip_serializing_if = "Option::is_none")] + pub api_version: Option, + + /// Whether this endpoint should receive events from connected accounts (`true`), or from your account (`false`). + /// + /// Defaults to `false`. + #[serde(skip_serializing_if = "Option::is_none")] + pub connect: Option, + + /// An optional description of what the wehbook is used for. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// The list of events to enable for this endpoint. + /// + /// You may specify `['*']` to enable all events, except those that require explicit selection. + pub enabled_events: Vec, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The URL of the webhook endpoint. + pub url: &'a str, +} + +impl<'a> CreateWebhookEndpoint<'a> { + pub fn new(enabled_events: Vec, url: &'a str) -> Self { + CreateWebhookEndpoint { + api_version: Default::default(), + connect: Default::default(), + description: Default::default(), + enabled_events, + expand: Default::default(), + metadata: Default::default(), + url, + } + } +} + +/// The parameters for `WebhookEndpoint::list`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct ListWebhookEndpoints<'a> { + /// A cursor for use in pagination. + /// + /// `ending_before` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub ending_before: Option, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// A limit on the number of objects to be returned. + /// + /// Limit can range between 1 and 100, and the default is 10. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + + /// A cursor for use in pagination. + /// + /// `starting_after` is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub starting_after: Option, +} + +impl<'a> ListWebhookEndpoints<'a> { + pub fn new() -> Self { + ListWebhookEndpoints { + ending_before: Default::default(), + expand: Default::default(), + limit: Default::default(), + starting_after: Default::default(), + } + } +} + +/// The parameters for `WebhookEndpoint::update`. +#[derive(Clone, Debug, Serialize, Default)] +pub struct UpdateWebhookEndpoint<'a> { + /// An optional description of what the wehbook is used for. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, + + /// Disable the webhook endpoint if set to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled: Option, + + /// The list of events to enable for this endpoint. + /// + /// You may specify `['*']` to enable all events, except those that require explicit selection. + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled_events: Option>, + + /// Specifies which fields in the response should be expanded. + #[serde(skip_serializing_if = "Expand::is_empty")] + pub expand: &'a [&'a str], + + /// Set of key-value pairs that you can attach to an object. + /// + /// This can be useful for storing additional information about the object in a structured format. + /// Individual keys can be unset by posting an empty value to them. + /// All keys can be unset by posting an empty value to `metadata`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + + /// The URL of the webhook endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option<&'a str>, +} + +impl<'a> UpdateWebhookEndpoint<'a> { + pub fn new() -> Self { + UpdateWebhookEndpoint { + description: Default::default(), + disabled: Default::default(), + enabled_events: Default::default(), + expand: Default::default(), + metadata: Default::default(), + url: Default::default(), + } + } +} + +/// An enum representing the possible values of an `CreateWebhookEndpoint`'s `enabled_events` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum EventFilter { + #[serde(rename = "*")] + All, + #[serde(rename = "account.application.authorized")] + AccountApplicationAuthorized, + #[serde(rename = "account.application.deauthorized")] + AccountApplicationDeauthorized, + #[serde(rename = "account.external_account.created")] + AccountExternalAccountCreated, + #[serde(rename = "account.external_account.deleted")] + AccountExternalAccountDeleted, + #[serde(rename = "account.external_account.updated")] + AccountExternalAccountUpdated, + #[serde(rename = "account.updated")] + AccountUpdated, + #[serde(rename = "application_fee.created")] + ApplicationFeeCreated, + #[serde(rename = "application_fee.refund.updated")] + ApplicationFeeRefundUpdated, + #[serde(rename = "application_fee.refunded")] + ApplicationFeeRefunded, + #[serde(rename = "balance.available")] + BalanceAvailable, + #[serde(rename = "capability.updated")] + CapabilityUpdated, + #[serde(rename = "charge.captured")] + ChargeCaptured, + #[serde(rename = "charge.dispute.closed")] + ChargeDisputeClosed, + #[serde(rename = "charge.dispute.created")] + ChargeDisputeCreated, + #[serde(rename = "charge.dispute.funds_reinstated")] + ChargeDisputeFundsReinstated, + #[serde(rename = "charge.dispute.funds_withdrawn")] + ChargeDisputeFundsWithdrawn, + #[serde(rename = "charge.dispute.updated")] + ChargeDisputeUpdated, + #[serde(rename = "charge.expired")] + ChargeExpired, + #[serde(rename = "charge.failed")] + ChargeFailed, + #[serde(rename = "charge.pending")] + ChargePending, + #[serde(rename = "charge.refund.updated")] + ChargeRefundUpdated, + #[serde(rename = "charge.refunded")] + ChargeRefunded, + #[serde(rename = "charge.succeeded")] + ChargeSucceeded, + #[serde(rename = "charge.updated")] + ChargeUpdated, + #[serde(rename = "checkout.session.completed")] + CheckoutSessionCompleted, + #[serde(rename = "coupon.created")] + CouponCreated, + #[serde(rename = "coupon.deleted")] + CouponDeleted, + #[serde(rename = "coupon.updated")] + CouponUpdated, + #[serde(rename = "credit_note.created")] + CreditNoteCreated, + #[serde(rename = "credit_note.updated")] + CreditNoteUpdated, + #[serde(rename = "credit_note.voided")] + CreditNoteVoided, + #[serde(rename = "customer.created")] + CustomerCreated, + #[serde(rename = "customer.deleted")] + CustomerDeleted, + #[serde(rename = "customer.discount.created")] + CustomerDiscountCreated, + #[serde(rename = "customer.discount.deleted")] + CustomerDiscountDeleted, + #[serde(rename = "customer.discount.updated")] + CustomerDiscountUpdated, + #[serde(rename = "customer.source.created")] + CustomerSourceCreated, + #[serde(rename = "customer.source.deleted")] + CustomerSourceDeleted, + #[serde(rename = "customer.source.expiring")] + CustomerSourceExpiring, + #[serde(rename = "customer.source.updated")] + CustomerSourceUpdated, + #[serde(rename = "customer.subscription.created")] + CustomerSubscriptionCreated, + #[serde(rename = "customer.subscription.deleted")] + CustomerSubscriptionDeleted, + #[serde(rename = "customer.subscription.pending_update_applied")] + CustomerSubscriptionPendingUpdateApplied, + #[serde(rename = "customer.subscription.pending_update_expired")] + CustomerSubscriptionPendingUpdateExpired, + #[serde(rename = "customer.subscription.trial_will_end")] + CustomerSubscriptionTrialWillEnd, + #[serde(rename = "customer.subscription.updated")] + CustomerSubscriptionUpdated, + #[serde(rename = "customer.tax_id.created")] + CustomerTaxIdCreated, + #[serde(rename = "customer.tax_id.deleted")] + CustomerTaxIdDeleted, + #[serde(rename = "customer.tax_id.updated")] + CustomerTaxIdUpdated, + #[serde(rename = "customer.updated")] + CustomerUpdated, + #[serde(rename = "file.created")] + FileCreated, + #[serde(rename = "invoice.created")] + InvoiceCreated, + #[serde(rename = "invoice.deleted")] + InvoiceDeleted, + #[serde(rename = "invoice.finalized")] + InvoiceFinalized, + #[serde(rename = "invoice.marked_uncollectible")] + InvoiceMarkedUncollectible, + #[serde(rename = "invoice.payment_action_required")] + InvoicePaymentActionRequired, + #[serde(rename = "invoice.payment_failed")] + InvoicePaymentFailed, + #[serde(rename = "invoice.payment_succeeded")] + InvoicePaymentSucceeded, + #[serde(rename = "invoice.sent")] + InvoiceSent, + #[serde(rename = "invoice.upcoming")] + InvoiceUpcoming, + #[serde(rename = "invoice.updated")] + InvoiceUpdated, + #[serde(rename = "invoice.voided")] + InvoiceVoided, + #[serde(rename = "invoiceitem.created")] + InvoiceitemCreated, + #[serde(rename = "invoiceitem.deleted")] + InvoiceitemDeleted, + #[serde(rename = "invoiceitem.updated")] + InvoiceitemUpdated, + #[serde(rename = "issuing_authorization.created")] + IssuingAuthorizationCreated, + #[serde(rename = "issuing_authorization.request")] + IssuingAuthorizationRequest, + #[serde(rename = "issuing_authorization.updated")] + IssuingAuthorizationUpdated, + #[serde(rename = "issuing_card.created")] + IssuingCardCreated, + #[serde(rename = "issuing_card.updated")] + IssuingCardUpdated, + #[serde(rename = "issuing_cardholder.created")] + IssuingCardholderCreated, + #[serde(rename = "issuing_cardholder.updated")] + IssuingCardholderUpdated, + #[serde(rename = "issuing_transaction.created")] + IssuingTransactionCreated, + #[serde(rename = "issuing_transaction.updated")] + IssuingTransactionUpdated, + #[serde(rename = "mandate.updated")] + MandateUpdated, + #[serde(rename = "order.created")] + OrderCreated, + #[serde(rename = "order.payment_failed")] + OrderPaymentFailed, + #[serde(rename = "order.payment_succeeded")] + OrderPaymentSucceeded, + #[serde(rename = "order.updated")] + OrderUpdated, + #[serde(rename = "order_return.created")] + OrderReturnCreated, + #[serde(rename = "payment_intent.amount_capturable_updated")] + PaymentIntentAmountCapturableUpdated, + #[serde(rename = "payment_intent.canceled")] + PaymentIntentCanceled, + #[serde(rename = "payment_intent.created")] + PaymentIntentCreated, + #[serde(rename = "payment_intent.payment_failed")] + PaymentIntentPaymentFailed, + #[serde(rename = "payment_intent.processing")] + PaymentIntentProcessing, + #[serde(rename = "payment_intent.succeeded")] + PaymentIntentSucceeded, + #[serde(rename = "payment_method.attached")] + PaymentMethodAttached, + #[serde(rename = "payment_method.card_automatically_updated")] + PaymentMethodCardAutomaticallyUpdated, + #[serde(rename = "payment_method.detached")] + PaymentMethodDetached, + #[serde(rename = "payment_method.updated")] + PaymentMethodUpdated, + #[serde(rename = "payout.canceled")] + PayoutCanceled, + #[serde(rename = "payout.created")] + PayoutCreated, + #[serde(rename = "payout.failed")] + PayoutFailed, + #[serde(rename = "payout.paid")] + PayoutPaid, + #[serde(rename = "payout.updated")] + PayoutUpdated, + #[serde(rename = "person.created")] + PersonCreated, + #[serde(rename = "person.deleted")] + PersonDeleted, + #[serde(rename = "person.updated")] + PersonUpdated, + #[serde(rename = "plan.created")] + PlanCreated, + #[serde(rename = "plan.deleted")] + PlanDeleted, + #[serde(rename = "plan.updated")] + PlanUpdated, + #[serde(rename = "product.created")] + ProductCreated, + #[serde(rename = "product.deleted")] + ProductDeleted, + #[serde(rename = "product.updated")] + ProductUpdated, + #[serde(rename = "radar.early_fraud_warning.created")] + RadarEarlyFraudWarningCreated, + #[serde(rename = "radar.early_fraud_warning.updated")] + RadarEarlyFraudWarningUpdated, + #[serde(rename = "recipient.created")] + RecipientCreated, + #[serde(rename = "recipient.deleted")] + RecipientDeleted, + #[serde(rename = "recipient.updated")] + RecipientUpdated, + #[serde(rename = "reporting.report_run.failed")] + ReportingReportRunFailed, + #[serde(rename = "reporting.report_run.succeeded")] + ReportingReportRunSucceeded, + #[serde(rename = "reporting.report_type.updated")] + ReportingReportTypeUpdated, + #[serde(rename = "review.closed")] + ReviewClosed, + #[serde(rename = "review.opened")] + ReviewOpened, + #[serde(rename = "setup_intent.canceled")] + SetupIntentCanceled, + #[serde(rename = "setup_intent.created")] + SetupIntentCreated, + #[serde(rename = "setup_intent.setup_failed")] + SetupIntentSetupFailed, + #[serde(rename = "setup_intent.succeeded")] + SetupIntentSucceeded, + #[serde(rename = "sigma.scheduled_query_run.created")] + SigmaScheduledQueryRunCreated, + #[serde(rename = "sku.created")] + SkuCreated, + #[serde(rename = "sku.deleted")] + SkuDeleted, + #[serde(rename = "sku.updated")] + SkuUpdated, + #[serde(rename = "source.canceled")] + SourceCanceled, + #[serde(rename = "source.chargeable")] + SourceChargeable, + #[serde(rename = "source.failed")] + SourceFailed, + #[serde(rename = "source.mandate_notification")] + SourceMandateNotification, + #[serde(rename = "source.refund_attributes_required")] + SourceRefundAttributesRequired, + #[serde(rename = "source.transaction.created")] + SourceTransactionCreated, + #[serde(rename = "source.transaction.updated")] + SourceTransactionUpdated, + #[serde(rename = "subscription_schedule.aborted")] + SubscriptionScheduleAborted, + #[serde(rename = "subscription_schedule.canceled")] + SubscriptionScheduleCanceled, + #[serde(rename = "subscription_schedule.completed")] + SubscriptionScheduleCompleted, + #[serde(rename = "subscription_schedule.created")] + SubscriptionScheduleCreated, + #[serde(rename = "subscription_schedule.expiring")] + SubscriptionScheduleExpiring, + #[serde(rename = "subscription_schedule.released")] + SubscriptionScheduleReleased, + #[serde(rename = "subscription_schedule.updated")] + SubscriptionScheduleUpdated, + #[serde(rename = "tax_rate.created")] + TaxRateCreated, + #[serde(rename = "tax_rate.updated")] + TaxRateUpdated, + #[serde(rename = "topup.canceled")] + TopupCanceled, + #[serde(rename = "topup.created")] + TopupCreated, + #[serde(rename = "topup.failed")] + TopupFailed, + #[serde(rename = "topup.reversed")] + TopupReversed, + #[serde(rename = "topup.succeeded")] + TopupSucceeded, + #[serde(rename = "transfer.created")] + TransferCreated, + #[serde(rename = "transfer.failed")] + TransferFailed, + #[serde(rename = "transfer.paid")] + TransferPaid, + #[serde(rename = "transfer.reversed")] + TransferReversed, + #[serde(rename = "transfer.updated")] + TransferUpdated, +} + +impl EventFilter { + pub fn as_str(self) -> &'static str { + match self { + EventFilter::All => "*", + EventFilter::AccountApplicationAuthorized => "account.application.authorized", + EventFilter::AccountApplicationDeauthorized => "account.application.deauthorized", + EventFilter::AccountExternalAccountCreated => "account.external_account.created", + EventFilter::AccountExternalAccountDeleted => "account.external_account.deleted", + EventFilter::AccountExternalAccountUpdated => "account.external_account.updated", + EventFilter::AccountUpdated => "account.updated", + EventFilter::ApplicationFeeCreated => "application_fee.created", + EventFilter::ApplicationFeeRefundUpdated => "application_fee.refund.updated", + EventFilter::ApplicationFeeRefunded => "application_fee.refunded", + EventFilter::BalanceAvailable => "balance.available", + EventFilter::CapabilityUpdated => "capability.updated", + EventFilter::ChargeCaptured => "charge.captured", + EventFilter::ChargeDisputeClosed => "charge.dispute.closed", + EventFilter::ChargeDisputeCreated => "charge.dispute.created", + EventFilter::ChargeDisputeFundsReinstated => "charge.dispute.funds_reinstated", + EventFilter::ChargeDisputeFundsWithdrawn => "charge.dispute.funds_withdrawn", + EventFilter::ChargeDisputeUpdated => "charge.dispute.updated", + EventFilter::ChargeExpired => "charge.expired", + EventFilter::ChargeFailed => "charge.failed", + EventFilter::ChargePending => "charge.pending", + EventFilter::ChargeRefundUpdated => "charge.refund.updated", + EventFilter::ChargeRefunded => "charge.refunded", + EventFilter::ChargeSucceeded => "charge.succeeded", + EventFilter::ChargeUpdated => "charge.updated", + EventFilter::CheckoutSessionCompleted => "checkout.session.completed", + EventFilter::CouponCreated => "coupon.created", + EventFilter::CouponDeleted => "coupon.deleted", + EventFilter::CouponUpdated => "coupon.updated", + EventFilter::CreditNoteCreated => "credit_note.created", + EventFilter::CreditNoteUpdated => "credit_note.updated", + EventFilter::CreditNoteVoided => "credit_note.voided", + EventFilter::CustomerCreated => "customer.created", + EventFilter::CustomerDeleted => "customer.deleted", + EventFilter::CustomerDiscountCreated => "customer.discount.created", + EventFilter::CustomerDiscountDeleted => "customer.discount.deleted", + EventFilter::CustomerDiscountUpdated => "customer.discount.updated", + EventFilter::CustomerSourceCreated => "customer.source.created", + EventFilter::CustomerSourceDeleted => "customer.source.deleted", + EventFilter::CustomerSourceExpiring => "customer.source.expiring", + EventFilter::CustomerSourceUpdated => "customer.source.updated", + EventFilter::CustomerSubscriptionCreated => "customer.subscription.created", + EventFilter::CustomerSubscriptionDeleted => "customer.subscription.deleted", + EventFilter::CustomerSubscriptionPendingUpdateApplied => { + "customer.subscription.pending_update_applied" + } + EventFilter::CustomerSubscriptionPendingUpdateExpired => { + "customer.subscription.pending_update_expired" + } + EventFilter::CustomerSubscriptionTrialWillEnd => "customer.subscription.trial_will_end", + EventFilter::CustomerSubscriptionUpdated => "customer.subscription.updated", + EventFilter::CustomerTaxIdCreated => "customer.tax_id.created", + EventFilter::CustomerTaxIdDeleted => "customer.tax_id.deleted", + EventFilter::CustomerTaxIdUpdated => "customer.tax_id.updated", + EventFilter::CustomerUpdated => "customer.updated", + EventFilter::FileCreated => "file.created", + EventFilter::InvoiceCreated => "invoice.created", + EventFilter::InvoiceDeleted => "invoice.deleted", + EventFilter::InvoiceFinalized => "invoice.finalized", + EventFilter::InvoiceMarkedUncollectible => "invoice.marked_uncollectible", + EventFilter::InvoicePaymentActionRequired => "invoice.payment_action_required", + EventFilter::InvoicePaymentFailed => "invoice.payment_failed", + EventFilter::InvoicePaymentSucceeded => "invoice.payment_succeeded", + EventFilter::InvoiceSent => "invoice.sent", + EventFilter::InvoiceUpcoming => "invoice.upcoming", + EventFilter::InvoiceUpdated => "invoice.updated", + EventFilter::InvoiceVoided => "invoice.voided", + EventFilter::InvoiceitemCreated => "invoiceitem.created", + EventFilter::InvoiceitemDeleted => "invoiceitem.deleted", + EventFilter::InvoiceitemUpdated => "invoiceitem.updated", + EventFilter::IssuingAuthorizationCreated => "issuing_authorization.created", + EventFilter::IssuingAuthorizationRequest => "issuing_authorization.request", + EventFilter::IssuingAuthorizationUpdated => "issuing_authorization.updated", + EventFilter::IssuingCardCreated => "issuing_card.created", + EventFilter::IssuingCardUpdated => "issuing_card.updated", + EventFilter::IssuingCardholderCreated => "issuing_cardholder.created", + EventFilter::IssuingCardholderUpdated => "issuing_cardholder.updated", + EventFilter::IssuingTransactionCreated => "issuing_transaction.created", + EventFilter::IssuingTransactionUpdated => "issuing_transaction.updated", + EventFilter::MandateUpdated => "mandate.updated", + EventFilter::OrderCreated => "order.created", + EventFilter::OrderPaymentFailed => "order.payment_failed", + EventFilter::OrderPaymentSucceeded => "order.payment_succeeded", + EventFilter::OrderUpdated => "order.updated", + EventFilter::OrderReturnCreated => "order_return.created", + EventFilter::PaymentIntentAmountCapturableUpdated => { + "payment_intent.amount_capturable_updated" + } + EventFilter::PaymentIntentCanceled => "payment_intent.canceled", + EventFilter::PaymentIntentCreated => "payment_intent.created", + EventFilter::PaymentIntentPaymentFailed => "payment_intent.payment_failed", + EventFilter::PaymentIntentProcessing => "payment_intent.processing", + EventFilter::PaymentIntentSucceeded => "payment_intent.succeeded", + EventFilter::PaymentMethodAttached => "payment_method.attached", + EventFilter::PaymentMethodCardAutomaticallyUpdated => { + "payment_method.card_automatically_updated" + } + EventFilter::PaymentMethodDetached => "payment_method.detached", + EventFilter::PaymentMethodUpdated => "payment_method.updated", + EventFilter::PayoutCanceled => "payout.canceled", + EventFilter::PayoutCreated => "payout.created", + EventFilter::PayoutFailed => "payout.failed", + EventFilter::PayoutPaid => "payout.paid", + EventFilter::PayoutUpdated => "payout.updated", + EventFilter::PersonCreated => "person.created", + EventFilter::PersonDeleted => "person.deleted", + EventFilter::PersonUpdated => "person.updated", + EventFilter::PlanCreated => "plan.created", + EventFilter::PlanDeleted => "plan.deleted", + EventFilter::PlanUpdated => "plan.updated", + EventFilter::ProductCreated => "product.created", + EventFilter::ProductDeleted => "product.deleted", + EventFilter::ProductUpdated => "product.updated", + EventFilter::RadarEarlyFraudWarningCreated => "radar.early_fraud_warning.created", + EventFilter::RadarEarlyFraudWarningUpdated => "radar.early_fraud_warning.updated", + EventFilter::RecipientCreated => "recipient.created", + EventFilter::RecipientDeleted => "recipient.deleted", + EventFilter::RecipientUpdated => "recipient.updated", + EventFilter::ReportingReportRunFailed => "reporting.report_run.failed", + EventFilter::ReportingReportRunSucceeded => "reporting.report_run.succeeded", + EventFilter::ReportingReportTypeUpdated => "reporting.report_type.updated", + EventFilter::ReviewClosed => "review.closed", + EventFilter::ReviewOpened => "review.opened", + EventFilter::SetupIntentCanceled => "setup_intent.canceled", + EventFilter::SetupIntentCreated => "setup_intent.created", + EventFilter::SetupIntentSetupFailed => "setup_intent.setup_failed", + EventFilter::SetupIntentSucceeded => "setup_intent.succeeded", + EventFilter::SigmaScheduledQueryRunCreated => "sigma.scheduled_query_run.created", + EventFilter::SkuCreated => "sku.created", + EventFilter::SkuDeleted => "sku.deleted", + EventFilter::SkuUpdated => "sku.updated", + EventFilter::SourceCanceled => "source.canceled", + EventFilter::SourceChargeable => "source.chargeable", + EventFilter::SourceFailed => "source.failed", + EventFilter::SourceMandateNotification => "source.mandate_notification", + EventFilter::SourceRefundAttributesRequired => "source.refund_attributes_required", + EventFilter::SourceTransactionCreated => "source.transaction.created", + EventFilter::SourceTransactionUpdated => "source.transaction.updated", + EventFilter::SubscriptionScheduleAborted => "subscription_schedule.aborted", + EventFilter::SubscriptionScheduleCanceled => "subscription_schedule.canceled", + EventFilter::SubscriptionScheduleCompleted => "subscription_schedule.completed", + EventFilter::SubscriptionScheduleCreated => "subscription_schedule.created", + EventFilter::SubscriptionScheduleExpiring => "subscription_schedule.expiring", + EventFilter::SubscriptionScheduleReleased => "subscription_schedule.released", + EventFilter::SubscriptionScheduleUpdated => "subscription_schedule.updated", + EventFilter::TaxRateCreated => "tax_rate.created", + EventFilter::TaxRateUpdated => "tax_rate.updated", + EventFilter::TopupCanceled => "topup.canceled", + EventFilter::TopupCreated => "topup.created", + EventFilter::TopupFailed => "topup.failed", + EventFilter::TopupReversed => "topup.reversed", + EventFilter::TopupSucceeded => "topup.succeeded", + EventFilter::TransferCreated => "transfer.created", + EventFilter::TransferFailed => "transfer.failed", + EventFilter::TransferPaid => "transfer.paid", + EventFilter::TransferReversed => "transfer.reversed", + EventFilter::TransferUpdated => "transfer.updated", + } + } +} + +impl AsRef for EventFilter { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for EventFilter { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/resources/webhook_endpoint_ext.rs b/ft-stripe/src/resources/webhook_endpoint_ext.rs new file mode 100644 index 0000000..660d359 --- /dev/null +++ b/ft-stripe/src/resources/webhook_endpoint_ext.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +/// An enum representing the possible values of an `WebhookEndpoint`'s `status` field. +#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum WebhookEndpointStatus { + Disabled, + Enabled, +} + +impl WebhookEndpointStatus { + pub fn as_str(self) -> &'static str { + match self { + WebhookEndpointStatus::Disabled => "disabled", + WebhookEndpointStatus::Enabled => "enabled", + } + } +} + +impl AsRef for WebhookEndpointStatus { + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl std::fmt::Display for WebhookEndpointStatus { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.as_str().fmt(f) + } +} diff --git a/ft-stripe/src/types.rs b/ft-stripe/src/types.rs new file mode 100644 index 0000000..63437c5 --- /dev/null +++ b/ft-stripe/src/types.rs @@ -0,0 +1,36 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct Address { + /// Address line 1 or block/building number (e.g. Street address/PO Box/Company name) + pub line1: Option, + /// Address line 2 or building details (e.g. Apartment/Suite/Unit/Building) + pub line2: Option, + /// City (or Ward) + pub city: Option, + /// State (or Prefecture) + pub state: Option, + /// ZIP or postal code + pub postal_code: Option, + /// Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)) + pub country: Option, + /// The town/cho-me (Japan only) + pub town: Option, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct CouponId(pub String); + + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct CustomField { + pub name: String, + pub value: String, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct ShippingParams { + pub address: Address, + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub phone: Option, +} From 863ededc5376a466ff68d92bec3ab7e2c439085b Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Thu, 20 Jun 2024 11:06:45 +0530 Subject: [PATCH 23/24] Added source of ft-stripe --- ft-stripe/Cargo.toml | 1 + ft-stripe/src/ids.rs | 1 + ft-stripe/src/params.rs | 1 + ft-stripe/src/payment_source.rs | 108 ------------------ ft-stripe/src/resources.rs | 1 + ft-stripe/src/resources/account.rs | 1 + ft-stripe/src/resources/alipay_account.rs | 1 + ft-stripe/src/resources/application.rs | 1 + ft-stripe/src/resources/application_fee.rs | 1 + ft-stripe/src/resources/balance.rs | 1 + .../src/resources/balance_transaction.rs | 1 + .../src/resources/balance_transaction_ext.rs | 1 + ft-stripe/src/resources/bank_account.rs | 1 + ft-stripe/src/resources/bank_account_ext.rs | 1 + ft-stripe/src/resources/card.rs | 1 + ft-stripe/src/resources/charge.rs | 1 + ft-stripe/src/resources/charge_ext.rs | 1 + ft-stripe/src/resources/checkout_session.rs | 1 + .../resources/connect_collection_transfer.rs | 1 + ft-stripe/src/resources/coupon.rs | 1 + ft-stripe/src/resources/currency.rs | 1 + ft-stripe/src/resources/customer.rs | 1 + ft-stripe/src/resources/customer_ext.rs | 1 + ft-stripe/src/resources/discount.rs | 1 + ft-stripe/src/resources/dispute.rs | 1 + ft-stripe/src/resources/event.rs | 1 + ft-stripe/src/resources/fee_refund.rs | 1 + ft-stripe/src/resources/file.rs | 1 + ft-stripe/src/resources/file_link.rs | 1 + ft-stripe/src/resources/invoice.rs | 1 + ft-stripe/src/resources/invoice_ext.rs | 1 + ft-stripe/src/resources/invoiceitem.rs | 1 + .../src/resources/issuing_authorization.rs | 1 + .../resources/issuing_authorization_ext.rs | 1 + ft-stripe/src/resources/issuing_card.rs | 1 + ft-stripe/src/resources/issuing_card_ext.rs | 1 + ft-stripe/src/resources/issuing_cardholder.rs | 1 + ft-stripe/src/resources/issuing_dispute.rs | 1 + .../src/resources/issuing_dispute_ext.rs | 1 + .../src/resources/issuing_merchant_data.rs | 1 + .../src/resources/issuing_transaction.rs | 1 + .../src/resources/issuing_transaction_ext.rs | 1 + ft-stripe/src/resources/item.rs | 1 + ft-stripe/src/resources/line_item.rs | 1 + ft-stripe/src/resources/line_item_ext.rs | 1 + ft-stripe/src/resources/mandate.rs | 1 + ft-stripe/src/resources/order.rs | 1 + ft-stripe/src/resources/order_ext.rs | 1 + ft-stripe/src/resources/order_item.rs | 1 + ft-stripe/src/resources/order_return.rs | 1 + ft-stripe/src/resources/payment_intent.rs | 1 + ft-stripe/src/resources/payment_method.rs | 1 + ft-stripe/src/resources/payment_method_ext.rs | 1 + ft-stripe/src/resources/payment_source.rs | 1 + ft-stripe/src/resources/payout.rs | 1 + ft-stripe/src/resources/payout_ext.rs | 1 + ft-stripe/src/resources/person.rs | 1 + ft-stripe/src/resources/placeholders.rs | 1 + ft-stripe/src/resources/plan.rs | 1 + ft-stripe/src/resources/platform_tax_fee.rs | 1 + ft-stripe/src/resources/price.rs | 1 + ft-stripe/src/resources/product.rs | 1 + ft-stripe/src/resources/recipient.rs | 1 + ft-stripe/src/resources/refund.rs | 1 + .../src/resources/reserve_transaction.rs | 1 + ft-stripe/src/resources/review.rs | 1 + ft-stripe/src/resources/review_ext.rs | 1 + .../src/resources/scheduled_query_run.rs | 1 + ft-stripe/src/resources/setup_intent.rs | 1 + ft-stripe/src/resources/sku.rs | 1 + ft-stripe/src/resources/source.rs | 1 + ft-stripe/src/resources/source_ext.rs | 1 + ft-stripe/src/resources/subscription.rs | 1 + ft-stripe/src/resources/subscription_ext.rs | 1 + ft-stripe/src/resources/subscription_item.rs | 1 + .../src/resources/subscription_item_ext.rs | 1 + .../src/resources/subscription_schedule.rs | 1 + .../src/resources/tax_deducted_at_source.rs | 1 + ft-stripe/src/resources/tax_id.rs | 1 + ft-stripe/src/resources/tax_rate.rs | 1 + ft-stripe/src/resources/token.rs | 1 + ft-stripe/src/resources/token_ext.rs | 1 + ft-stripe/src/resources/topup.rs | 1 + ft-stripe/src/resources/transfer.rs | 1 + ft-stripe/src/resources/transfer_reversal.rs | 1 + ft-stripe/src/resources/types.rs | 1 + ft-stripe/src/resources/webhook_endpoint.rs | 1 + .../src/resources/webhook_endpoint_ext.rs | 1 + ft-stripe/src/types.rs | 36 ------ 89 files changed, 87 insertions(+), 144 deletions(-) delete mode 100644 ft-stripe/src/payment_source.rs delete mode 100644 ft-stripe/src/types.rs diff --git a/ft-stripe/Cargo.toml b/ft-stripe/Cargo.toml index 9869ad9..5005f7c 100644 --- a/ft-stripe/Cargo.toml +++ b/ft-stripe/Cargo.toml @@ -1,3 +1,4 @@ +# Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c [package] name = "ft-stripe" version = "0.1.0" diff --git a/ft-stripe/src/ids.rs b/ft-stripe/src/ids.rs index 4ab076a..42f4032 100644 --- a/ft-stripe/src/ids.rs +++ b/ft-stripe/src/ids.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c macro_rules! def_id_serde_impls { ($struct_name:ident) => { impl serde::Serialize for $struct_name { diff --git a/ft-stripe/src/params.rs b/ft-stripe/src/params.rs index 7b910f5..44a070a 100644 --- a/ft-stripe/src/params.rs +++ b/ft-stripe/src/params.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::resources::ApiVersion; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; diff --git a/ft-stripe/src/payment_source.rs b/ft-stripe/src/payment_source.rs deleted file mode 100644 index 7fbedc7..0000000 --- a/ft-stripe/src/payment_source.rs +++ /dev/null @@ -1,108 +0,0 @@ -use serde::{Deserialize, Serialize}; -use serde::ser::SerializeStruct; -use stripe::{Account, AlipayAccount, BankAccount, Card, Currency, Object, PaymentSourceId, Source}; - -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -#[serde(untagged)] -pub enum PaymentSourceParams { - /// Creates a payment method (e.g. card or bank account) from tokenized data, - /// using a token typically received from Stripe Elements. - Token(ft_stripe::TokenId), - - /// Attach an existing source to an existing customer or - /// create a new customer from an existing source. - Source(ft_stripe::SourceId), -} - - -/// A PaymentSource represents a payment method _associated with a customer or charge_. -/// This value is usually returned as a subresource on another request. -/// -/// Not to be confused with `Source` which represents a "generic" payment method -/// returned by the `Source::get` (which could still be a credit card, etc) -/// but is not necessarily attached to either a customer or charge. - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum PaymentSource { - Card(Card), - Source(Source), - Account(Account), - BankAccount(BankAccount), - AlipayAccount(AlipayAccount), -} - -impl ft_stripe::Object for stripe::PaymentSource { - type Id = PaymentSourceId; - fn id(&self) -> Self::Id { - match self { - PaymentSource::Card(x) => PaymentSourceId::Card(x.id()), - PaymentSource::Source(x) => PaymentSourceId::Source(x.id()), - PaymentSource::Account(x) => PaymentSourceId::Account(x.id()), - PaymentSource::BankAccount(x) => PaymentSourceId::BankAccount(x.id()), - PaymentSource::AlipayAccount(x) => PaymentSourceId::AlipayAccount(x.id()), - } - } - fn object(&self) -> &'static str { - match self { - PaymentSource::Card(x) => x.object(), - PaymentSource::Source(x) => x.object(), - PaymentSource::Account(x) => x.object(), - PaymentSource::BankAccount(x) => x.object(), - PaymentSource::AlipayAccount(x) => x.object(), - } - } -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct BankAccountParams<'a> { - pub country: &'a str, - pub currency: Currency, - pub account_holder_name: Option<&'a str>, - pub account_holder_type: Option<&'a str>, - pub routing_number: Option<&'a str>, - pub account_number: &'a str, -} - -impl<'a> serde::ser::Serialize for BankAccountParams<'a> { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - let mut s = serializer.serialize_struct("BankAccountParams", 6)?; - s.serialize_field("object", "bank_account")?; - s.serialize_field("country", &self.country)?; - s.serialize_field("currency", &self.currency)?; - s.serialize_field("account_holder_name", &self.account_holder_name)?; - s.serialize_field("routing_number", &self.routing_number)?; - s.serialize_field("account_number", &self.account_number)?; - s.end() - } -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct CardParams<'a> { - pub exp_month: &'a str, // eg. "12" - pub exp_year: &'a str, // eg. "17" or 2017" - - pub number: &'a str, // card number - pub name: Option<&'a str>, // cardholder's full name - pub cvc: Option<&'a str>, // card security code -} - -impl<'a> serde::ser::Serialize for CardParams<'a> { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - let mut s = serializer.serialize_struct("CardParams", 6)?; - s.serialize_field("object", "card")?; - s.serialize_field("exp_month", &self.exp_month)?; - s.serialize_field("exp_year", &self.exp_year)?; - s.serialize_field("number", &self.number)?; - s.serialize_field("name", &self.name)?; - s.serialize_field("cvc", &self.cvc)?; - s.end() - } -} \ No newline at end of file diff --git a/ft-stripe/src/resources.rs b/ft-stripe/src/resources.rs index 6f56471..bb43330 100644 --- a/ft-stripe/src/resources.rs +++ b/ft-stripe/src/resources.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // Builtin types mod currency; mod types; diff --git a/ft-stripe/src/resources/account.rs b/ft-stripe/src/resources/account.rs index 7e35747..d77ba19 100644 --- a/ft-stripe/src/resources/account.rs +++ b/ft-stripe/src/resources/account.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/alipay_account.rs b/ft-stripe/src/resources/alipay_account.rs index cae8cc3..65a8cb4 100644 --- a/ft-stripe/src/resources/alipay_account.rs +++ b/ft-stripe/src/resources/alipay_account.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/application.rs b/ft-stripe/src/resources/application.rs index c0ae4b4..d601ff4 100644 --- a/ft-stripe/src/resources/application.rs +++ b/ft-stripe/src/resources/application.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/application_fee.rs b/ft-stripe/src/resources/application_fee.rs index bf1a892..c88fe35 100644 --- a/ft-stripe/src/resources/application_fee.rs +++ b/ft-stripe/src/resources/application_fee.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/balance.rs b/ft-stripe/src/resources/balance.rs index ce360f5..d37a959 100644 --- a/ft-stripe/src/resources/balance.rs +++ b/ft-stripe/src/resources/balance.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/balance_transaction.rs b/ft-stripe/src/resources/balance_transaction.rs index ccb4808..f8407ab 100644 --- a/ft-stripe/src/resources/balance_transaction.rs +++ b/ft-stripe/src/resources/balance_transaction.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/balance_transaction_ext.rs b/ft-stripe/src/resources/balance_transaction_ext.rs index a833485..726918e 100644 --- a/ft-stripe/src/resources/balance_transaction_ext.rs +++ b/ft-stripe/src/resources/balance_transaction_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::ids::BalanceTransactionSourceId; use crate::params::Object; use crate::resources::BalanceTransactionSource; diff --git a/ft-stripe/src/resources/bank_account.rs b/ft-stripe/src/resources/bank_account.rs index 4862d2e..422183b 100644 --- a/ft-stripe/src/resources/bank_account.rs +++ b/ft-stripe/src/resources/bank_account.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/bank_account_ext.rs b/ft-stripe/src/resources/bank_account_ext.rs index 0da1534..9b0afa4 100644 --- a/ft-stripe/src/resources/bank_account_ext.rs +++ b/ft-stripe/src/resources/bank_account_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `BankAccount`'s `status` field. diff --git a/ft-stripe/src/resources/card.rs b/ft-stripe/src/resources/card.rs index d62f0ab..7b98cc6 100644 --- a/ft-stripe/src/resources/card.rs +++ b/ft-stripe/src/resources/card.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::ids::CardId; use crate::params::{Expandable, Metadata, Object}; use crate::resources::{Account, Currency, Customer, Recipient}; diff --git a/ft-stripe/src/resources/charge.rs b/ft-stripe/src/resources/charge.rs index 490223b..b622bfa 100644 --- a/ft-stripe/src/resources/charge.rs +++ b/ft-stripe/src/resources/charge.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/charge_ext.rs b/ft-stripe/src/resources/charge_ext.rs index dcf66d3..1e06ac1 100644 --- a/ft-stripe/src/resources/charge_ext.rs +++ b/ft-stripe/src/resources/charge_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{BankAccountId, CardId, ChargeId, SourceId, TokenId}; use crate::params::Object; diff --git a/ft-stripe/src/resources/checkout_session.rs b/ft-stripe/src/resources/checkout_session.rs index cfebabf..01598b0 100644 --- a/ft-stripe/src/resources/checkout_session.rs +++ b/ft-stripe/src/resources/checkout_session.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/connect_collection_transfer.rs b/ft-stripe/src/resources/connect_collection_transfer.rs index 69e1f4b..e9b1494 100644 --- a/ft-stripe/src/resources/connect_collection_transfer.rs +++ b/ft-stripe/src/resources/connect_collection_transfer.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/coupon.rs b/ft-stripe/src/resources/coupon.rs index 4edfd12..2606d21 100644 --- a/ft-stripe/src/resources/coupon.rs +++ b/ft-stripe/src/resources/coupon.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/currency.rs b/ft-stripe/src/resources/currency.rs index 93f9c59..48b76d3 100644 --- a/ft-stripe/src/resources/currency.rs +++ b/ft-stripe/src/resources/currency.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::params::to_snakecase; use serde::{Deserialize, Serialize}; diff --git a/ft-stripe/src/resources/customer.rs b/ft-stripe/src/resources/customer.rs index 7c0c615..dcbe0fb 100644 --- a/ft-stripe/src/resources/customer.rs +++ b/ft-stripe/src/resources/customer.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/customer_ext.rs b/ft-stripe/src/resources/customer_ext.rs index 27f98ed..981e6d6 100644 --- a/ft-stripe/src/resources/customer_ext.rs +++ b/ft-stripe/src/resources/customer_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{BankAccountId, CardId, CustomerId, PaymentSourceId}; use crate::params::Deleted; diff --git a/ft-stripe/src/resources/discount.rs b/ft-stripe/src/resources/discount.rs index d9e0f2a..73581bb 100644 --- a/ft-stripe/src/resources/discount.rs +++ b/ft-stripe/src/resources/discount.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/dispute.rs b/ft-stripe/src/resources/dispute.rs index 8b79a11..dfcdfc9 100644 --- a/ft-stripe/src/resources/dispute.rs +++ b/ft-stripe/src/resources/dispute.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/event.rs b/ft-stripe/src/resources/event.rs index 8ca0f1a..5196bf8 100644 --- a/ft-stripe/src/resources/event.rs +++ b/ft-stripe/src/resources/event.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::error::WebhookError; use crate::ids::{AccountId, EventId}; use crate::resources::*; diff --git a/ft-stripe/src/resources/fee_refund.rs b/ft-stripe/src/resources/fee_refund.rs index 95588ca..4fdd1f4 100644 --- a/ft-stripe/src/resources/fee_refund.rs +++ b/ft-stripe/src/resources/fee_refund.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/file.rs b/ft-stripe/src/resources/file.rs index 5557865..24ec5ce 100644 --- a/ft-stripe/src/resources/file.rs +++ b/ft-stripe/src/resources/file.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/file_link.rs b/ft-stripe/src/resources/file_link.rs index b931ba1..444f685 100644 --- a/ft-stripe/src/resources/file_link.rs +++ b/ft-stripe/src/resources/file_link.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/invoice.rs b/ft-stripe/src/resources/invoice.rs index 56196ce..7311e13 100644 --- a/ft-stripe/src/resources/invoice.rs +++ b/ft-stripe/src/resources/invoice.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/invoice_ext.rs b/ft-stripe/src/resources/invoice_ext.rs index 9ec15d2..c3fb306 100644 --- a/ft-stripe/src/resources/invoice_ext.rs +++ b/ft-stripe/src/resources/invoice_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{CouponId, CustomerId, InvoiceId, PlanId, SubscriptionId, SubscriptionItemId}; use crate::params::{Metadata, Timestamp}; diff --git a/ft-stripe/src/resources/invoiceitem.rs b/ft-stripe/src/resources/invoiceitem.rs index eca618d..91bf089 100644 --- a/ft-stripe/src/resources/invoiceitem.rs +++ b/ft-stripe/src/resources/invoiceitem.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_authorization.rs b/ft-stripe/src/resources/issuing_authorization.rs index b7f1290..6bf0094 100644 --- a/ft-stripe/src/resources/issuing_authorization.rs +++ b/ft-stripe/src/resources/issuing_authorization.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_authorization_ext.rs b/ft-stripe/src/resources/issuing_authorization_ext.rs index 08067e2..a812a2c 100644 --- a/ft-stripe/src/resources/issuing_authorization_ext.rs +++ b/ft-stripe/src/resources/issuing_authorization_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of the `IssuingAuthorizationVerificationData` fields. diff --git a/ft-stripe/src/resources/issuing_card.rs b/ft-stripe/src/resources/issuing_card.rs index 0f26c16..95767d5 100644 --- a/ft-stripe/src/resources/issuing_card.rs +++ b/ft-stripe/src/resources/issuing_card.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_card_ext.rs b/ft-stripe/src/resources/issuing_card_ext.rs index 06a3a7f..3199ea2 100644 --- a/ft-stripe/src/resources/issuing_card_ext.rs +++ b/ft-stripe/src/resources/issuing_card_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `IssuingCardPin`'s `status` field. diff --git a/ft-stripe/src/resources/issuing_cardholder.rs b/ft-stripe/src/resources/issuing_cardholder.rs index 9399541..bd86c6e 100644 --- a/ft-stripe/src/resources/issuing_cardholder.rs +++ b/ft-stripe/src/resources/issuing_cardholder.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_dispute.rs b/ft-stripe/src/resources/issuing_dispute.rs index 7b5ef02..2325775 100644 --- a/ft-stripe/src/resources/issuing_dispute.rs +++ b/ft-stripe/src/resources/issuing_dispute.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_dispute_ext.rs b/ft-stripe/src/resources/issuing_dispute_ext.rs index 170fbc9..6ba0e72 100644 --- a/ft-stripe/src/resources/issuing_dispute_ext.rs +++ b/ft-stripe/src/resources/issuing_dispute_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `IssuingDispute`'s `reason` field. diff --git a/ft-stripe/src/resources/issuing_merchant_data.rs b/ft-stripe/src/resources/issuing_merchant_data.rs index d6765e9..7f37dc2 100644 --- a/ft-stripe/src/resources/issuing_merchant_data.rs +++ b/ft-stripe/src/resources/issuing_merchant_data.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// The resource representing a Stripe "IssuingAuthorizationMerchantData". diff --git a/ft-stripe/src/resources/issuing_transaction.rs b/ft-stripe/src/resources/issuing_transaction.rs index 1d0cbd0..217d945 100644 --- a/ft-stripe/src/resources/issuing_transaction.rs +++ b/ft-stripe/src/resources/issuing_transaction.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/issuing_transaction_ext.rs b/ft-stripe/src/resources/issuing_transaction_ext.rs index aa64fcb..22b5a67 100644 --- a/ft-stripe/src/resources/issuing_transaction_ext.rs +++ b/ft-stripe/src/resources/issuing_transaction_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `IssuingTransaction`'s `type` field. diff --git a/ft-stripe/src/resources/item.rs b/ft-stripe/src/resources/item.rs index f6bf253..0525d63 100644 --- a/ft-stripe/src/resources/item.rs +++ b/ft-stripe/src/resources/item.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/line_item.rs b/ft-stripe/src/resources/line_item.rs index 8ea34fc..e605565 100644 --- a/ft-stripe/src/resources/line_item.rs +++ b/ft-stripe/src/resources/line_item.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/line_item_ext.rs b/ft-stripe/src/resources/line_item_ext.rs index 1af7d7a..b282d63 100644 --- a/ft-stripe/src/resources/line_item_ext.rs +++ b/ft-stripe/src/resources/line_item_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{CustomerId, InvoiceId}; use crate::resources::{Currency, InvoiceLineItem}; diff --git a/ft-stripe/src/resources/mandate.rs b/ft-stripe/src/resources/mandate.rs index 8d350ef..85ee42c 100644 --- a/ft-stripe/src/resources/mandate.rs +++ b/ft-stripe/src/resources/mandate.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/order.rs b/ft-stripe/src/resources/order.rs index 3642eaf..983eebe 100644 --- a/ft-stripe/src/resources/order.rs +++ b/ft-stripe/src/resources/order.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/order_ext.rs b/ft-stripe/src/resources/order_ext.rs index f189621..6d55862 100644 --- a/ft-stripe/src/resources/order_ext.rs +++ b/ft-stripe/src/resources/order_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `ListOrders`'s `status` field. diff --git a/ft-stripe/src/resources/order_item.rs b/ft-stripe/src/resources/order_item.rs index d65a4ee..32a47ea 100644 --- a/ft-stripe/src/resources/order_item.rs +++ b/ft-stripe/src/resources/order_item.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/order_return.rs b/ft-stripe/src/resources/order_return.rs index e3a266d..bf20ae1 100644 --- a/ft-stripe/src/resources/order_return.rs +++ b/ft-stripe/src/resources/order_return.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/payment_intent.rs b/ft-stripe/src/resources/payment_intent.rs index eccb2bb..e799183 100644 --- a/ft-stripe/src/resources/payment_intent.rs +++ b/ft-stripe/src/resources/payment_intent.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{CustomerId, PaymentIntentId}; use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; diff --git a/ft-stripe/src/resources/payment_method.rs b/ft-stripe/src/resources/payment_method.rs index 96833d8..8a65434 100644 --- a/ft-stripe/src/resources/payment_method.rs +++ b/ft-stripe/src/resources/payment_method.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/payment_method_ext.rs b/ft-stripe/src/resources/payment_method_ext.rs index 21f9aa0..acc5a49 100644 --- a/ft-stripe/src/resources/payment_method_ext.rs +++ b/ft-stripe/src/resources/payment_method_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{CustomerId, PaymentMethodId}; use crate::resources::PaymentMethod; diff --git a/ft-stripe/src/resources/payment_source.rs b/ft-stripe/src/resources/payment_source.rs index 122c479..49a545d 100644 --- a/ft-stripe/src/resources/payment_source.rs +++ b/ft-stripe/src/resources/payment_source.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::ids::{PaymentSourceId, SourceId, TokenId}; use crate::params::Object; use crate::resources::{Account, AlipayAccount, BankAccount, Card, Currency, Source}; diff --git a/ft-stripe/src/resources/payout.rs b/ft-stripe/src/resources/payout.rs index fb6389d..d017832 100644 --- a/ft-stripe/src/resources/payout.rs +++ b/ft-stripe/src/resources/payout.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/payout_ext.rs b/ft-stripe/src/resources/payout_ext.rs index 026659f..ff3ce7c 100644 --- a/ft-stripe/src/resources/payout_ext.rs +++ b/ft-stripe/src/resources/payout_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{PayoutDestinationId, PayoutId}; use crate::params::Object; diff --git a/ft-stripe/src/resources/person.rs b/ft-stripe/src/resources/person.rs index eaf6a86..69b4fca 100644 --- a/ft-stripe/src/resources/person.rs +++ b/ft-stripe/src/resources/person.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/placeholders.rs b/ft-stripe/src/resources/placeholders.rs index dd12957..6bca72e 100644 --- a/ft-stripe/src/resources/placeholders.rs +++ b/ft-stripe/src/resources/placeholders.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::ids::*; use crate::params::Object; use serde::{Deserialize, Serialize}; diff --git a/ft-stripe/src/resources/plan.rs b/ft-stripe/src/resources/plan.rs index 6aecefd..6b5a87d 100644 --- a/ft-stripe/src/resources/plan.rs +++ b/ft-stripe/src/resources/plan.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/platform_tax_fee.rs b/ft-stripe/src/resources/platform_tax_fee.rs index d3d3f57..61b0721 100644 --- a/ft-stripe/src/resources/platform_tax_fee.rs +++ b/ft-stripe/src/resources/platform_tax_fee.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/price.rs b/ft-stripe/src/resources/price.rs index 4723e11..9aa27dc 100644 --- a/ft-stripe/src/resources/price.rs +++ b/ft-stripe/src/resources/price.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/product.rs b/ft-stripe/src/resources/product.rs index 274e962..dea7989 100644 --- a/ft-stripe/src/resources/product.rs +++ b/ft-stripe/src/resources/product.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/recipient.rs b/ft-stripe/src/resources/recipient.rs index 564d335..f3f65fa 100644 --- a/ft-stripe/src/resources/recipient.rs +++ b/ft-stripe/src/resources/recipient.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/refund.rs b/ft-stripe/src/resources/refund.rs index 686ad96..8412717 100644 --- a/ft-stripe/src/resources/refund.rs +++ b/ft-stripe/src/resources/refund.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/reserve_transaction.rs b/ft-stripe/src/resources/reserve_transaction.rs index 388503e..013c905 100644 --- a/ft-stripe/src/resources/reserve_transaction.rs +++ b/ft-stripe/src/resources/reserve_transaction.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/review.rs b/ft-stripe/src/resources/review.rs index 9de8467..3b57e15 100644 --- a/ft-stripe/src/resources/review.rs +++ b/ft-stripe/src/resources/review.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/review_ext.rs b/ft-stripe/src/resources/review_ext.rs index 440b029..6e57e63 100644 --- a/ft-stripe/src/resources/review_ext.rs +++ b/ft-stripe/src/resources/review_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `Review`'s `reason` field. diff --git a/ft-stripe/src/resources/scheduled_query_run.rs b/ft-stripe/src/resources/scheduled_query_run.rs index bee2ca4..f2b84c0 100644 --- a/ft-stripe/src/resources/scheduled_query_run.rs +++ b/ft-stripe/src/resources/scheduled_query_run.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/setup_intent.rs b/ft-stripe/src/resources/setup_intent.rs index 2904dcf..3bed533 100644 --- a/ft-stripe/src/resources/setup_intent.rs +++ b/ft-stripe/src/resources/setup_intent.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/sku.rs b/ft-stripe/src/resources/sku.rs index d2f9b02..d3240de 100644 --- a/ft-stripe/src/resources/sku.rs +++ b/ft-stripe/src/resources/sku.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/source.rs b/ft-stripe/src/resources/source.rs index e6a5905..cb49314 100644 --- a/ft-stripe/src/resources/source.rs +++ b/ft-stripe/src/resources/source.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/source_ext.rs b/ft-stripe/src/resources/source_ext.rs index e42bee8..d9f4260 100644 --- a/ft-stripe/src/resources/source_ext.rs +++ b/ft-stripe/src/resources/source_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `Source`'s `status` field. diff --git a/ft-stripe/src/resources/subscription.rs b/ft-stripe/src/resources/subscription.rs index 52c279c..e172226 100644 --- a/ft-stripe/src/resources/subscription.rs +++ b/ft-stripe/src/resources/subscription.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/subscription_ext.rs b/ft-stripe/src/resources/subscription_ext.rs index 615dbc9..c0b4eee 100644 --- a/ft-stripe/src/resources/subscription_ext.rs +++ b/ft-stripe/src/resources/subscription_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::SubscriptionId; use crate::resources::{CreateSubscriptionItems, Subscription}; diff --git a/ft-stripe/src/resources/subscription_item.rs b/ft-stripe/src/resources/subscription_item.rs index 674f5c2..c17b804 100644 --- a/ft-stripe/src/resources/subscription_item.rs +++ b/ft-stripe/src/resources/subscription_item.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/subscription_item_ext.rs b/ft-stripe/src/resources/subscription_item_ext.rs index 89b8b18..8e19303 100644 --- a/ft-stripe/src/resources/subscription_item_ext.rs +++ b/ft-stripe/src/resources/subscription_item_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::config::{Client, Response}; use crate::ids::{InvoiceId, SubscriptionItemId, UsageRecordId, UsageRecordSummaryId}; use crate::params::{Expand, List, Object, Timestamp}; diff --git a/ft-stripe/src/resources/subscription_schedule.rs b/ft-stripe/src/resources/subscription_schedule.rs index 3cf3741..3ddb45a 100644 --- a/ft-stripe/src/resources/subscription_schedule.rs +++ b/ft-stripe/src/resources/subscription_schedule.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/tax_deducted_at_source.rs b/ft-stripe/src/resources/tax_deducted_at_source.rs index 972cfd6..6a3f7dd 100644 --- a/ft-stripe/src/resources/tax_deducted_at_source.rs +++ b/ft-stripe/src/resources/tax_deducted_at_source.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/tax_id.rs b/ft-stripe/src/resources/tax_id.rs index ba980dc..4914721 100644 --- a/ft-stripe/src/resources/tax_id.rs +++ b/ft-stripe/src/resources/tax_id.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/tax_rate.rs b/ft-stripe/src/resources/tax_rate.rs index 109faa3..6b66031 100644 --- a/ft-stripe/src/resources/tax_rate.rs +++ b/ft-stripe/src/resources/tax_rate.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/token.rs b/ft-stripe/src/resources/token.rs index 82c93af..327a846 100644 --- a/ft-stripe/src/resources/token.rs +++ b/ft-stripe/src/resources/token.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/token_ext.rs b/ft-stripe/src/resources/token_ext.rs index 8763f40..54c6b71 100644 --- a/ft-stripe/src/resources/token_ext.rs +++ b/ft-stripe/src/resources/token_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `Token`'s `type` field. diff --git a/ft-stripe/src/resources/topup.rs b/ft-stripe/src/resources/topup.rs index ff2b9e2..162928a 100644 --- a/ft-stripe/src/resources/topup.rs +++ b/ft-stripe/src/resources/topup.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/transfer.rs b/ft-stripe/src/resources/transfer.rs index 778c389..9f69a2e 100644 --- a/ft-stripe/src/resources/transfer.rs +++ b/ft-stripe/src/resources/transfer.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/transfer_reversal.rs b/ft-stripe/src/resources/transfer_reversal.rs index 5f1ca6c..4d1bd30 100644 --- a/ft-stripe/src/resources/transfer_reversal.rs +++ b/ft-stripe/src/resources/transfer_reversal.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/types.rs b/ft-stripe/src/resources/types.rs index 78c4a48..610f8c7 100644 --- a/ft-stripe/src/resources/types.rs +++ b/ft-stripe/src/resources/types.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use crate::params::Timestamp; use crate::resources::card::{CardBrand, CardType}; use serde::{Deserialize, Serialize}; diff --git a/ft-stripe/src/resources/webhook_endpoint.rs b/ft-stripe/src/resources/webhook_endpoint.rs index a9fa56e..6a45050 100644 --- a/ft-stripe/src/resources/webhook_endpoint.rs +++ b/ft-stripe/src/resources/webhook_endpoint.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c // ====================================== // This file was automatically generated. // ====================================== diff --git a/ft-stripe/src/resources/webhook_endpoint_ext.rs b/ft-stripe/src/resources/webhook_endpoint_ext.rs index 660d359..38e9865 100644 --- a/ft-stripe/src/resources/webhook_endpoint_ext.rs +++ b/ft-stripe/src/resources/webhook_endpoint_ext.rs @@ -1,3 +1,4 @@ +// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c use serde::{Deserialize, Serialize}; /// An enum representing the possible values of an `WebhookEndpoint`'s `status` field. diff --git a/ft-stripe/src/types.rs b/ft-stripe/src/types.rs deleted file mode 100644 index 63437c5..0000000 --- a/ft-stripe/src/types.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct Address { - /// Address line 1 or block/building number (e.g. Street address/PO Box/Company name) - pub line1: Option, - /// Address line 2 or building details (e.g. Apartment/Suite/Unit/Building) - pub line2: Option, - /// City (or Ward) - pub city: Option, - /// State (or Prefecture) - pub state: Option, - /// ZIP or postal code - pub postal_code: Option, - /// Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)) - pub country: Option, - /// The town/cho-me (Japan only) - pub town: Option, -} - -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct CouponId(pub String); - - -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct CustomField { - pub name: String, - pub value: String, -} - -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct ShippingParams { - pub address: Address, - pub name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, -} From 23ae0ae895cb51a05dad3fe933a1fb9d8e9747c2 Mon Sep 17 00:00:00 2001 From: Arpita-Jaiswal Date: Thu, 20 Jun 2024 11:31:03 +0530 Subject: [PATCH 24/24] Remove ft-stripe --- Cargo.lock | 24 - Cargo.toml | 1 - ft-stripe/Cargo.toml | 21 - ft-stripe/src/client.rs | 167 -- ft-stripe/src/ids.rs | 627 ------- ft-stripe/src/lib.rs | 91 - ft-stripe/src/params.rs | 254 --- ft-stripe/src/resources.rs | 305 ---- ft-stripe/src/resources/account.rs | 1421 ---------------- ft-stripe/src/resources/alipay_account.rs | 76 - ft-stripe/src/resources/application.rs | 29 - ft-stripe/src/resources/application_fee.rs | 146 -- ft-stripe/src/resources/balance.rs | 77 - .../src/resources/balance_transaction.rs | 321 ---- .../src/resources/balance_transaction_ext.rs | 112 -- ft-stripe/src/resources/bank_account.rs | 97 -- ft-stripe/src/resources/bank_account_ext.rs | 37 - ft-stripe/src/resources/card.rs | 218 --- ft-stripe/src/resources/charge.rs | 627 ------- ft-stripe/src/resources/charge_ext.rs | 56 - ft-stripe/src/resources/checkout_session.rs | 1043 ------------ .../resources/connect_collection_transfer.rs | 34 - ft-stripe/src/resources/coupon.rs | 319 ---- ft-stripe/src/resources/currency.rs | 464 ----- ft-stripe/src/resources/customer.rs | 679 -------- ft-stripe/src/resources/customer_ext.rs | 84 - ft-stripe/src/resources/discount.rs | 47 - ft-stripe/src/resources/dispute.rs | 339 ---- ft-stripe/src/resources/event.rs | 404 ----- ft-stripe/src/resources/fee_refund.rs | 53 - ft-stripe/src/resources/file.rs | 175 -- ft-stripe/src/resources/file_link.rs | 205 --- ft-stripe/src/resources/invoice.rs | 903 ---------- ft-stripe/src/resources/invoice_ext.rs | 73 - ft-stripe/src/resources/invoiceitem.rs | 453 ----- .../src/resources/issuing_authorization.rs | 208 --- .../resources/issuing_authorization_ext.rs | 70 - ft-stripe/src/resources/issuing_card.rs | 313 ---- ft-stripe/src/resources/issuing_card_ext.rs | 126 -- ft-stripe/src/resources/issuing_cardholder.rs | 308 ---- ft-stripe/src/resources/issuing_dispute.rs | 28 - .../src/resources/issuing_dispute_ext.rs | 64 - .../src/resources/issuing_merchant_data.rs | 326 ---- .../src/resources/issuing_transaction.rs | 211 --- .../src/resources/issuing_transaction_ext.rs | 39 - ft-stripe/src/resources/item.rs | 63 - ft-stripe/src/resources/line_item.rs | 139 -- ft-stripe/src/resources/line_item_ext.rs | 46 - ft-stripe/src/resources/mandate.rs | 234 --- ft-stripe/src/resources/order.rs | 523 ------ ft-stripe/src/resources/order_ext.rs | 35 - ft-stripe/src/resources/order_item.rs | 51 - ft-stripe/src/resources/order_return.rs | 121 -- ft-stripe/src/resources/payment_intent.rs | 602 ------- ft-stripe/src/resources/payment_method.rs | 949 ----------- ft-stripe/src/resources/payment_method_ext.rs | 33 - ft-stripe/src/resources/payment_source.rs | 115 -- ft-stripe/src/resources/payout.rs | 383 ----- ft-stripe/src/resources/payout_ext.rs | 30 - ft-stripe/src/resources/person.rs | 398 ----- ft-stripe/src/resources/placeholders.rs | 599 ------- ft-stripe/src/resources/plan.rs | 675 -------- ft-stripe/src/resources/platform_tax_fee.rs | 29 - ft-stripe/src/resources/price.rs | 921 ---------- ft-stripe/src/resources/product.rs | 501 ------ ft-stripe/src/resources/recipient.rs | 326 ---- ft-stripe/src/resources/refund.rs | 287 ---- .../src/resources/reserve_transaction.rs | 33 - ft-stripe/src/resources/review.rs | 241 --- ft-stripe/src/resources/review_ext.rs | 39 - .../src/resources/scheduled_query_run.rs | 62 - ft-stripe/src/resources/setup_intent.rs | 655 ------- ft-stripe/src/resources/sku.rs | 375 ---- ft-stripe/src/resources/source.rs | 1512 ----------------- ft-stripe/src/resources/source_ext.rs | 130 -- ft-stripe/src/resources/subscription.rs | 1202 ------------- ft-stripe/src/resources/subscription_ext.rs | 44 - ft-stripe/src/resources/subscription_item.rs | 481 ------ .../src/resources/subscription_item_ext.rs | 162 -- .../src/resources/subscription_schedule.rs | 821 --------- .../src/resources/tax_deducted_at_source.rs | 32 - ft-stripe/src/resources/tax_id.rs | 186 -- ft-stripe/src/resources/tax_rate.rs | 248 --- ft-stripe/src/resources/token.rs | 230 --- ft-stripe/src/resources/token_ext.rs | 35 - ft-stripe/src/resources/topup.rs | 272 --- ft-stripe/src/resources/transfer.rs | 304 ---- ft-stripe/src/resources/transfer_reversal.rs | 61 - ft-stripe/src/resources/types.rs | 726 -------- ft-stripe/src/resources/webhook_endpoint.rs | 745 -------- .../src/resources/webhook_endpoint_ext.rs | 31 - 91 files changed, 27362 deletions(-) delete mode 100644 ft-stripe/Cargo.toml delete mode 100644 ft-stripe/src/client.rs delete mode 100644 ft-stripe/src/ids.rs delete mode 100644 ft-stripe/src/lib.rs delete mode 100644 ft-stripe/src/params.rs delete mode 100644 ft-stripe/src/resources.rs delete mode 100644 ft-stripe/src/resources/account.rs delete mode 100644 ft-stripe/src/resources/alipay_account.rs delete mode 100644 ft-stripe/src/resources/application.rs delete mode 100644 ft-stripe/src/resources/application_fee.rs delete mode 100644 ft-stripe/src/resources/balance.rs delete mode 100644 ft-stripe/src/resources/balance_transaction.rs delete mode 100644 ft-stripe/src/resources/balance_transaction_ext.rs delete mode 100644 ft-stripe/src/resources/bank_account.rs delete mode 100644 ft-stripe/src/resources/bank_account_ext.rs delete mode 100644 ft-stripe/src/resources/card.rs delete mode 100644 ft-stripe/src/resources/charge.rs delete mode 100644 ft-stripe/src/resources/charge_ext.rs delete mode 100644 ft-stripe/src/resources/checkout_session.rs delete mode 100644 ft-stripe/src/resources/connect_collection_transfer.rs delete mode 100644 ft-stripe/src/resources/coupon.rs delete mode 100644 ft-stripe/src/resources/currency.rs delete mode 100644 ft-stripe/src/resources/customer.rs delete mode 100644 ft-stripe/src/resources/customer_ext.rs delete mode 100644 ft-stripe/src/resources/discount.rs delete mode 100644 ft-stripe/src/resources/dispute.rs delete mode 100644 ft-stripe/src/resources/event.rs delete mode 100644 ft-stripe/src/resources/fee_refund.rs delete mode 100644 ft-stripe/src/resources/file.rs delete mode 100644 ft-stripe/src/resources/file_link.rs delete mode 100644 ft-stripe/src/resources/invoice.rs delete mode 100644 ft-stripe/src/resources/invoice_ext.rs delete mode 100644 ft-stripe/src/resources/invoiceitem.rs delete mode 100644 ft-stripe/src/resources/issuing_authorization.rs delete mode 100644 ft-stripe/src/resources/issuing_authorization_ext.rs delete mode 100644 ft-stripe/src/resources/issuing_card.rs delete mode 100644 ft-stripe/src/resources/issuing_card_ext.rs delete mode 100644 ft-stripe/src/resources/issuing_cardholder.rs delete mode 100644 ft-stripe/src/resources/issuing_dispute.rs delete mode 100644 ft-stripe/src/resources/issuing_dispute_ext.rs delete mode 100644 ft-stripe/src/resources/issuing_merchant_data.rs delete mode 100644 ft-stripe/src/resources/issuing_transaction.rs delete mode 100644 ft-stripe/src/resources/issuing_transaction_ext.rs delete mode 100644 ft-stripe/src/resources/item.rs delete mode 100644 ft-stripe/src/resources/line_item.rs delete mode 100644 ft-stripe/src/resources/line_item_ext.rs delete mode 100644 ft-stripe/src/resources/mandate.rs delete mode 100644 ft-stripe/src/resources/order.rs delete mode 100644 ft-stripe/src/resources/order_ext.rs delete mode 100644 ft-stripe/src/resources/order_item.rs delete mode 100644 ft-stripe/src/resources/order_return.rs delete mode 100644 ft-stripe/src/resources/payment_intent.rs delete mode 100644 ft-stripe/src/resources/payment_method.rs delete mode 100644 ft-stripe/src/resources/payment_method_ext.rs delete mode 100644 ft-stripe/src/resources/payment_source.rs delete mode 100644 ft-stripe/src/resources/payout.rs delete mode 100644 ft-stripe/src/resources/payout_ext.rs delete mode 100644 ft-stripe/src/resources/person.rs delete mode 100644 ft-stripe/src/resources/placeholders.rs delete mode 100644 ft-stripe/src/resources/plan.rs delete mode 100644 ft-stripe/src/resources/platform_tax_fee.rs delete mode 100644 ft-stripe/src/resources/price.rs delete mode 100644 ft-stripe/src/resources/product.rs delete mode 100644 ft-stripe/src/resources/recipient.rs delete mode 100644 ft-stripe/src/resources/refund.rs delete mode 100644 ft-stripe/src/resources/reserve_transaction.rs delete mode 100644 ft-stripe/src/resources/review.rs delete mode 100644 ft-stripe/src/resources/review_ext.rs delete mode 100644 ft-stripe/src/resources/scheduled_query_run.rs delete mode 100644 ft-stripe/src/resources/setup_intent.rs delete mode 100644 ft-stripe/src/resources/sku.rs delete mode 100644 ft-stripe/src/resources/source.rs delete mode 100644 ft-stripe/src/resources/source_ext.rs delete mode 100644 ft-stripe/src/resources/subscription.rs delete mode 100644 ft-stripe/src/resources/subscription_ext.rs delete mode 100644 ft-stripe/src/resources/subscription_item.rs delete mode 100644 ft-stripe/src/resources/subscription_item_ext.rs delete mode 100644 ft-stripe/src/resources/subscription_schedule.rs delete mode 100644 ft-stripe/src/resources/tax_deducted_at_source.rs delete mode 100644 ft-stripe/src/resources/tax_id.rs delete mode 100644 ft-stripe/src/resources/tax_rate.rs delete mode 100644 ft-stripe/src/resources/token.rs delete mode 100644 ft-stripe/src/resources/token_ext.rs delete mode 100644 ft-stripe/src/resources/topup.rs delete mode 100644 ft-stripe/src/resources/transfer.rs delete mode 100644 ft-stripe/src/resources/transfer_reversal.rs delete mode 100644 ft-stripe/src/resources/types.rs delete mode 100644 ft-stripe/src/resources/webhook_endpoint.rs delete mode 100644 ft-stripe/src/resources/webhook_endpoint_ext.rs diff --git a/Cargo.lock b/Cargo.lock index 4ea7c59..bf7de12 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -214,21 +214,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "ft-stripe" -version = "0.1.0" -dependencies = [ - "bytes", - "ft-sdk", - "ft-sys", - "http", - "serde", - "serde_json", - "serde_urlencoded", - "smol_str", - "thiserror", -] - [[package]] name = "ft-sys" version = "0.1.3" @@ -535,15 +520,6 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" -[[package]] -name = "smol_str" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fad6c857cbab2627dcf01ec85a623ca4e7dcb5691cbaa3d7fb7653671f0d09c9" -dependencies = [ - "serde", -] - [[package]] name = "syn" version = "1.0.109" diff --git a/Cargo.toml b/Cargo.toml index 06b0dcf..8a353d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,6 @@ members = [ "ft-sdk", "ft-sys", "ft-sys-shared", - "ft-stripe", ] exclude = ["examples", "f"] resolver = "2" diff --git a/ft-stripe/Cargo.toml b/ft-stripe/Cargo.toml deleted file mode 100644 index 5005f7c..0000000 --- a/ft-stripe/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -# Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -[package] -name = "ft-stripe" -version = "0.1.0" -authors.workspace = true -edition.workspace = true -description.workspace = true -license.workspace = true -repository.workspace = true -homepage.workspace = true - -[dependencies] -thiserror.workspace = true -http.workspace = true -ft-sdk.workspace = true -bytes.workspace = true -serde.workspace = true -serde_json.workspace = true -serde_urlencoded.workspace = true -ft-sys.workspace = true -smol_str = "0.1" diff --git a/ft-stripe/src/client.rs b/ft-stripe/src/client.rs deleted file mode 100644 index aeb7365..0000000 --- a/ft-stripe/src/client.rs +++ /dev/null @@ -1,167 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c - -use serde::de::DeserializeOwned; -use crate::params::{AppInfo, Headers}; -use crate::resources::ApiVersion; -use crate::config::Response; -use http::header::{HeaderMap, HeaderName, HeaderValue}; - -#[derive(Clone)] -pub struct Client { - host: String, - secret_key: String, - headers: Headers, - app_info: Option, -} - -impl Client { - /// Creates a new client pointed to `https://api.stripe.com/` - pub fn new(secret_key: impl Into) -> Client { - Client::from_url("https://api.stripe.com/", secret_key) - } - - /// Creates a new client posted to a custom `scheme://host/` - pub fn from_url(scheme_host: impl Into, secret_key: impl Into) -> Client { - let url = scheme_host.into(); - let host = if url.ends_with('/') { format!("{}v1", url) } else { format!("{}/v1", url) }; - let mut headers = Headers::default(); - // TODO: Automatically determine the latest supported api version in codegen? - headers.stripe_version = Some(ApiVersion::V2019_09_09); - - Client { - host, - secret_key: secret_key.into(), - headers, - app_info: Some(AppInfo::default()), - } - } - - - /// Clones a new client with different headers. - /// - /// This is the recommended way to send requests for many different Stripe accounts - /// or with different Meta, Extra, and Expand headers while using the same secret key. - pub fn with_headers(&self, headers: Headers) -> Client { - let mut client = self.clone(); - client.headers = headers; - client - } - - pub fn set_app_info(&mut self, name: String, version: Option, url: Option) { - self.app_info = Some(AppInfo { name, url, version }); - } - - /// Sets a value for the Stripe-Account header - /// - /// This is recommended if you are acting as only one Account for the lifetime of the client. - /// Otherwise, prefer `client.with(Headers{stripe_account: "acct_ABC", ..})`. - pub fn set_stripe_account>(&mut self, account_id: S) { - self.headers.stripe_account = Some(account_id.into()); - } - - /// Make a `GET` http request with just a path - pub fn get(&self, path: &str) -> Response { - todo!() - } - - /// Make a `GET` http request with url query parameters - pub fn get_query( - &self, - path: &str, - params: P, - ) -> Response { - todo!() - } - - /// Make a `DELETE` http request with just a path - pub fn delete(&self, path: &str) -> Response { - todo!() - } - - /// Make a `DELETE` http request with url query parameters - pub fn delete_query( - &self, - path: &str, - params: P, - ) -> Response { - todo!() - } - - /// Make a `POST` http request with just a path - pub fn post(&self, path: &str) -> Response { - todo!() - } - - /// Make a `POST` http request with urlencoded body - pub fn post_form( - &self, - path: &str, - form: F, - ) -> Response { - todo!() - } - - fn url(&self, path: &str) -> String { - format!("{}/{}", self.host, path.trim_start_matches('/')) - } - - // fn url_with_params(&self, path: &str, params: P) -> Result { - //todo: Result - fn url_with_params(&self, path: &str, params: P) -> Result { - todo!() - } - - fn headers(&self) -> HeaderMap { - let mut headers = HeaderMap::new(); - headers.insert( - HeaderName::from_static("authorization"), - HeaderValue::from_str(&format!("Bearer {}", self.secret_key)).unwrap(), - ); - if let Some(account) = &self.headers.stripe_account { - headers.insert( - HeaderName::from_static("stripe-account"), - HeaderValue::from_str(account).unwrap(), - ); - } - if let Some(client_id) = &self.headers.client_id { - headers.insert( - HeaderName::from_static("client-id"), - HeaderValue::from_str(client_id).unwrap(), - ); - } - if let Some(stripe_version) = &self.headers.stripe_version { - headers.insert( - HeaderName::from_static("stripe-version"), - HeaderValue::from_str(stripe_version.as_str()).unwrap(), - ); - } - const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION"); - let user_agent: String = format!("Stripe/v3 RustBindings/{}", CRATE_VERSION); - if let Some(app_info) = &self.app_info { - let formatted: String = format_app_info(app_info); - let user_agent_app_info: String = - format!("{} {}", user_agent, formatted).trim().to_owned(); - headers.insert( - HeaderName::from_static("user-agent"), - HeaderValue::from_str(user_agent_app_info.as_str()).unwrap(), - ); - } else { - headers.insert( - HeaderName::from_static("user-agent"), - HeaderValue::from_str(user_agent.as_str()).unwrap(), - ); - }; - headers - } -} - - -fn format_app_info(info: &AppInfo) -> String { - let formatted: String = match (&info.version, &info.url) { - (Some(a), Some(b)) => format!("{}/{} ({})", &info.name, a, b), - (Some(a), None) => format!("{}/{}", &info.name, a), - (None, Some(b)) => format!("{}/{}", &info.name, b), - _ => info.name.to_string(), - }; - formatted -} \ No newline at end of file diff --git a/ft-stripe/src/ids.rs b/ft-stripe/src/ids.rs deleted file mode 100644 index 42f4032..0000000 --- a/ft-stripe/src/ids.rs +++ /dev/null @@ -1,627 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -macro_rules! def_id_serde_impls { - ($struct_name:ident) => { - impl serde::Serialize for $struct_name { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - self.as_str().serialize(serializer) - } - } - - impl<'de> serde::Deserialize<'de> for $struct_name { - fn deserialize(deserializer: D) -> Result - where - D: serde::de::Deserializer<'de>, - { - let s: String = serde::Deserialize::deserialize(deserializer)?; - s.parse::().map_err(::serde::de::Error::custom) - } - } - }; - ($struct_name:ident, _) => {}; -} - -macro_rules! def_id { - ($struct_name:ident: String) => { - #[derive(Clone, Debug, Eq, PartialEq, Hash)] - pub struct $struct_name(smol_str::SmolStr); - - impl $struct_name { - /// Extracts a string slice containing the entire id. - #[inline(always)] - pub fn as_str(&self) -> &str { - self.0.as_str() - } - } - - impl PartialEq for $struct_name { - fn eq(&self, other: &str) -> bool { - self.as_str() == other - } - } - - impl PartialEq<&str> for $struct_name { - fn eq(&self, other: &&str) -> bool { - self.as_str() == *other - } - } - - impl PartialEq for $struct_name { - fn eq(&self, other: &String) -> bool { - self.as_str() == other - } - } - - impl PartialOrd for $struct_name { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - - impl Ord for $struct_name { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.as_str().cmp(other.as_str()) - } - } - - impl AsRef for $struct_name { - fn as_ref(&self) -> &str { - self.as_str() - } - } - - impl crate::params::AsCursor for $struct_name {} - - impl std::ops::Deref for $struct_name { - type Target = str; - - fn deref(&self) -> &str { - self.as_str() - } - } - - impl std::fmt::Display for $struct_name { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } - } - - impl std::str::FromStr for $struct_name { - type Err = ParseIdError; - - fn from_str(s: &str) -> Result { - Ok($struct_name(s.into())) - } - } - - impl serde::Serialize for $struct_name { - fn serialize(&self, serializer: S) -> Result - where S: serde::ser::Serializer - { - self.as_str().serialize(serializer) - } - } - - impl<'de> serde::Deserialize<'de> for $struct_name { - fn deserialize(deserializer: D) -> Result - where D: serde::de::Deserializer<'de> - { - let s: String = serde::Deserialize::deserialize(deserializer)?; - s.parse::().map_err(::serde::de::Error::custom) - } - } - }; - ($struct_name:ident, $prefix:literal $(| $alt_prefix:literal)* $(, { $generate_hint:tt })?) => { - /// An id for the corresponding object type. - /// - /// This type _typically_ will not allocate and - /// therefore is usually cheaply clonable. - #[derive(Clone, Debug, Eq, PartialEq, Hash)] - pub struct $struct_name(smol_str::SmolStr); - - impl $struct_name { - /// The prefix of the id type (e.g. `cus_` for a `CustomerId`). - #[inline(always)] - #[deprecated(note = "Please use prefixes or is_valid_prefix")] - pub fn prefix() -> &'static str { - $prefix - } - - /// The valid prefixes of the id type (e.g. [`ch_`, `py_`\ for a `ChargeId`). - #[inline(always)] - pub fn prefixes() -> &'static [&'static str] { - &[$prefix$(, $alt_prefix)*] - } - - /// Extracts a string slice containing the entire id. - #[inline(always)] - pub fn as_str(&self) -> &str { - self.0.as_str() - } - - /// Check is provided prefix would be a valid prefix for id's of this type - pub fn is_valid_prefix(prefix: &str) -> bool { - prefix == $prefix $( || prefix == $alt_prefix )* - } - } - - impl PartialEq for $struct_name { - fn eq(&self, other: &str) -> bool { - self.as_str() == other - } - } - - impl PartialEq<&str> for $struct_name { - fn eq(&self, other: &&str) -> bool { - self.as_str() == *other - } - } - - impl PartialEq for $struct_name { - fn eq(&self, other: &String) -> bool { - self.as_str() == other - } - } - - impl PartialOrd for $struct_name { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - - impl Ord for $struct_name { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.as_str().cmp(other.as_str()) - } - } - - impl AsRef for $struct_name { - fn as_ref(&self) -> &str { - self.as_str() - } - } - - impl crate::params::AsCursor for $struct_name {} - - impl std::ops::Deref for $struct_name { - type Target = str; - - fn deref(&self) -> &str { - self.as_str() - } - } - - impl std::fmt::Display for $struct_name { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } - } - - impl std::str::FromStr for $struct_name { - type Err = ParseIdError; - - fn from_str(s: &str) -> Result { - if !s.starts_with($prefix) $( - && !s.starts_with($alt_prefix) - )* { - - // N.B. For debugging - eprintln!("bad id is: {} (expected: {:?})", s, $prefix); - - Err(ParseIdError { - typename: stringify!($struct_name), - expected: stringify!(id to start with $prefix $(or $alt_prefix)*), - }) - } else { - Ok($struct_name(s.into())) - } - } - } - - def_id_serde_impls!($struct_name $(, $generate_hint )*); - }; - (#[optional] enum $enum_name:ident { $( $variant_name:ident($($variant_type:tt)*) ),* $(,)* }) => { - #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] - pub enum $enum_name { - None, - $( $variant_name($($variant_type)*), )* - } - - impl $enum_name { - pub fn as_str(&self) -> &str { - match *self { - $enum_name::None => "", - $( $enum_name::$variant_name(ref id) => id.as_str(), )* - } - } - } - - impl PartialEq for $enum_name { - fn eq(&self, other: &str) -> bool { - self.as_str() == other - } - } - - impl PartialEq<&str> for $enum_name { - fn eq(&self, other: &&str) -> bool { - self.as_str() == *other - } - } - - impl PartialEq for $enum_name { - fn eq(&self, other: &String) -> bool { - self.as_str() == other - } - } - - impl AsRef for $enum_name { - fn as_ref(&self) -> &str { - self.as_str() - } - } - - impl crate::params::AsCursor for $enum_name {} - - impl std::ops::Deref for $enum_name { - type Target = str; - - fn deref(&self) -> &str { - self.as_str() - } - } - - impl std::fmt::Display for $enum_name { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match *self { - $enum_name::None => Ok(()), - $( $enum_name::$variant_name(ref id) => id.fmt(f), )* - } - } - } - - impl std::str::FromStr for $enum_name { - type Err = ParseIdError; - - fn from_str(s: &str) -> Result { - let prefix = s.find('_') - .map(|i| &s[0..=i]) - .ok_or_else(|| ParseIdError { - typename: stringify!($enum_name), - expected: "id to start with a prefix (as in 'prefix_')" - })?; - - match prefix { - $(_ if $($variant_type)*::is_valid_prefix(prefix) => { - Ok($enum_name::$variant_name(s.parse()?)) - })* - _ => { - Err(ParseIdError { - typename: stringify!($enum_name), - expected: "unknown id prefix", - }) - } - } - } - } - - impl serde::Serialize for $enum_name { - fn serialize(&self, serializer: S) -> Result - where S: serde::ser::Serializer - { - self.as_str().serialize(serializer) - } - } - - impl<'de> serde::Deserialize<'de> for $enum_name { - fn deserialize(deserializer: D) -> Result - where D: serde::de::Deserializer<'de> - { - let s: String = serde::Deserialize::deserialize(deserializer)?; - s.parse::().map_err(::serde::de::Error::custom) - } - } - - $( - impl From<$($variant_type)*> for $enum_name { - fn from(id: $($variant_type)*) -> Self { - $enum_name::$variant_name(id) - } - } - )* - }; - (enum $enum_name:ident { $( $variant_name:ident($($variant_type:tt)*) ),* $(,)* }) => { - #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] - pub enum $enum_name { - $( $variant_name($($variant_type)*), )* - } - - impl $enum_name { - pub fn as_str(&self) -> &str { - match *self { - $( $enum_name::$variant_name(ref id) => id.as_str(), )* - } - } - } - - impl PartialEq for $enum_name { - fn eq(&self, other: &str) -> bool { - self.as_str() == other - } - } - - impl PartialEq<&str> for $enum_name { - fn eq(&self, other: &&str) -> bool { - self.as_str() == *other - } - } - - impl PartialEq for $enum_name { - fn eq(&self, other: &String) -> bool { - self.as_str() == other - } - } - - impl AsRef for $enum_name { - fn as_ref(&self) -> &str { - self.as_str() - } - } - - impl crate::params::AsCursor for $enum_name {} - - impl std::ops::Deref for $enum_name { - type Target = str; - - fn deref(&self) -> &str { - self.as_str() - } - } - - impl std::fmt::Display for $enum_name { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match *self { - $( $enum_name::$variant_name(ref id) => id.fmt(f), )* - } - } - } - - impl std::str::FromStr for $enum_name { - type Err = ParseIdError; - - fn from_str(s: &str) -> Result { - let prefix = s.find('_') - .map(|i| &s[0..=i]) - .ok_or_else(|| ParseIdError { - typename: stringify!($enum_name), - expected: "id to start with a prefix (as in 'prefix_')" - })?; - - match prefix { - $(_ if $($variant_type)*::is_valid_prefix(prefix) => { - Ok($enum_name::$variant_name(s.parse()?)) - })* - _ => { - Err(ParseIdError { - typename: stringify!($enum_name), - expected: "unknown id prefix", - }) - } - } - } - } - - impl serde::Serialize for $enum_name { - fn serialize(&self, serializer: S) -> Result - where S: serde::ser::Serializer - { - self.as_str().serialize(serializer) - } - } - - impl<'de> serde::Deserialize<'de> for $enum_name { - fn deserialize(deserializer: D) -> Result - where D: serde::de::Deserializer<'de> - { - let s: String = serde::Deserialize::deserialize(deserializer)?; - s.parse::().map_err(::serde::de::Error::custom) - } - } - - $( - impl From<$($variant_type)*> for $enum_name { - fn from(id: $($variant_type)*) -> Self { - $enum_name::$variant_name(id) - } - } - )* - }; -} - -#[derive(Clone, Debug)] -pub struct ParseIdError { - typename: &'static str, - expected: &'static str, -} - -impl std::fmt::Display for ParseIdError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "invalid `{}`, expected {}", self.typename, self.expected) - } -} - -impl std::error::Error for ParseIdError { - fn description(&self) -> &str { - "error parsing an id" - } -} - -def_id!(AccountId, "acct_"); -def_id!(AlipayAccountId, "aliacc_"); -def_id!(ApplicationId, "ca_"); -def_id!(ApplicationFeeId, "fee_"); -def_id!(ApplicationFeeRefundId, "fr_"); -def_id!(BalanceTransactionId, "txn_"); -def_id!(BankAccountId, "ba_"); -def_id!(BankTokenId, "btok_"); -def_id!( - #[optional] - enum BalanceTransactionSourceId { - ApplicationFee(ApplicationFeeId), - Charge(ChargeId), - Dispute(DisputeId), - ApplicationFeeRefund(ApplicationFeeRefundId), - IssuingAuthorization(IssuingAuthorizationId), - IssuingTransaction(IssuingTransactionId), - Payout(PayoutId), - Refund(RefundId), - Topup(TopupId), - Transfer(TransferId), - TransferReversal(TransferReversalId), - } -); -def_id!(CardId, "card_"); -def_id!(CardTokenId, "tok_"); -def_id!(ChargeId, "ch_" | "py_"); // TODO: Understand (and then document) why "py_" is a valid charge id -def_id!(CheckoutSessionId, "cs_"); -def_id!(CheckoutSessionItemId: String); // TODO: Figure out what prefix this id has -def_id!(CouponId: String); // N.B. A coupon id can be user-provided so can be any arbitrary string -def_id!(CustomerId, "cus_"); -def_id!(DisputeId, "dp_" | "du_"); -def_id!(EventId, "evt_"); -def_id!(FileId, "file_"); -def_id!(FileLinkId, "link_"); -def_id!(InvoiceId, "in_", { _ }); -def_id!(InvoiceItemId, "ii_"); -def_id!( - enum InvoiceLineItemId { - Item(InvoiceItemId), - Subscription(SubscriptionLineId), - } -); -def_id!(IssuingAuthorizationId, "iauth_"); -def_id!(IssuingCardId, "ic_"); -def_id!(IssuingCardholderId, "ich_"); -def_id!(IssuingDisputeId, "idp_"); -def_id!(IssuingTransactionId, "ipi_"); -def_id!(OrderId, "or_"); -def_id!(OrderReturnId, "orret_"); -def_id!(MandateId: String); // TODO: Figure out what prefix this id has -def_id!(PaymentIntentId, "pi_"); -def_id!(PaymentMethodId, "pm" | "card_"); -def_id!( - enum PaymentSourceId { - Account(AccountId), - AlipayAccount(AlipayAccountId), - BankAccount(BankAccountId), - Card(CardId), - Source(SourceId), - } -); -def_id!(PayoutId, "po_"); -def_id!( - enum PayoutDestinationId { - BankAccount(BankAccountId), - Card(CardId), - } -); -def_id!(PersonId, "person_"); -def_id!(PlanId: String); // N.B. A plan id can be user-provided so can be any arbitrary string -def_id!(PriceId: String); // TODO: Figure out what prefix this id has -def_id!(ProductId: String); // N.B. A product id can be user-provided so can be any arbitrary string -def_id!(RecipientId: String); // FIXME: This doesn't seem to be documented yet -def_id!(RefundId, "re_" | "pyr_"); -def_id!(ReviewId, "prv_"); -def_id!(ScheduledQueryRunId, "sqr_"); -def_id!(SetupIntentId, "seti_"); -def_id!(SkuId, "sku_"); -def_id!(SourceId, "src_"); -def_id!(SubscriptionId, "sub_"); -def_id!(SubscriptionItemId, "si_"); -def_id!(SubscriptionLineId, "sli_"); -def_id!(SubscriptionScheduleId, "sub_sched_"); -def_id!(TaxIdId, "txi_"); -def_id!(TaxRateId, "txr_"); -def_id!( - enum TokenId { - Card(CardTokenId), - Bank(BankTokenId), - } -); -def_id!(TopupId, "tu_"); -def_id!(TransferId, "tr_"); -def_id!(TransferReversalId, "trr_"); -def_id!(UsageRecordId, "mbur_"); -def_id!(UsageRecordSummaryId, "sis_"); -def_id!(WebhookEndpointId, "we_"); - -impl InvoiceId { - pub(crate) fn none() -> Self { - Self("".into()) - } - - /// An InvoiceId may have a `None` representation when - /// received from Stripe if the Invoice is an upcoming invoice. - pub fn is_none(&self) -> bool { - self.0.is_empty() - } -} -impl serde::Serialize for InvoiceId { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - if self.0.is_empty() { - let val: Option<&str> = None; - val.serialize(serializer) - } else { - self.as_str().serialize(serializer) - } - } -} -impl<'de> serde::Deserialize<'de> for InvoiceId { - fn deserialize(deserializer: D) -> Result - where - D: serde::de::Deserializer<'de>, - { - let s: String = serde::Deserialize::deserialize(deserializer)?; - if s.is_empty() { - Ok(InvoiceId::none()) - } else { - s.parse::().map_err(::serde::de::Error::custom) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parse_customer() { - assert!("cus_123".parse::().is_ok()); - let bad_parse = "zzz_123".parse::(); - assert!(bad_parse.is_err()); - if let Err(err) = bad_parse { - assert_eq!( - format!("{}", err), - "invalid `CustomerId`, expected id to start with \"cus_\"" - ); - } - } - - #[test] - fn test_parse_charge() { - assert!("ch_123".parse::().is_ok()); - assert!("py_123".parse::().is_ok()); - let bad_parse = "zz_123".parse::(); - assert!(bad_parse.is_err()); - if let Err(err) = bad_parse { - assert_eq!( - format!("{}", err), - "invalid `ChargeId`, expected id to start with \"ch_\" or \"py_\"" - ); - } - } -} diff --git a/ft-stripe/src/lib.rs b/ft-stripe/src/lib.rs deleted file mode 100644 index cbc6fc5..0000000 --- a/ft-stripe/src/lib.rs +++ /dev/null @@ -1,91 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -extern crate self as ft_stripe; - -mod resources; -pub use ft_stripe::resources::*; -mod ids; -mod params; -pub use crate::ids::*; -pub use crate::params::{ - Expandable, Headers, IdOrCreate, List, Metadata, Object, RangeBounds, RangeQuery, Timestamp, -}; - - -mod client; -mod config { - pub type Client = crate::client::Client; - pub type Response = Result; -} - -pub use self::config::Client; -pub use self::config::Response; - - - - -pub struct CustomerID(pub String); - -pub fn create_customer( - secret_key: &str, -) -> Response { - let client = Client::new(secret_key); - let create_customer = CreateCustomer::new(); - Customer::create(&client, create_customer) -} - -fn call_create_customer_api( - token: &str, - body: &serde_json::Value, -) -> Result { - let authorization_header = format!("Bearer {}", token); - - // Serialize the struct to URL-encoded format - let body = serde_urlencoded::to_string(body).unwrap(); - - let client = http::Request::builder(); - let request = client - .method("POST") - .uri("https://api.stripe.com/v1/customers") - .header("Authorization", authorization_header) - .header("Content-Type", "application/x-www-form-urlencoded") - .body(bytes::Bytes::from(body))?; - - let response = ft_sdk::http::send(request).unwrap(); //todo: remove unwrap() - - #[derive(Debug, serde::Deserialize)] - struct Response { - id: String, - } - - let response_body = String::from_utf8_lossy(response.body()).to_string(); - - if response.status().is_success() { - let api_response: Response = serde_json::from_str(response_body.as_str()).unwrap(); - - ft_sdk::println!("Create customer API Response: {:?}", api_response); - - Ok(CustomerID(api_response.id)) - } else { - ft_sdk::println!("Request failed with status: {}", response.status()); - Err(CreateCustomerError::CannotCreateCustomer(response_body)) - } -} - -#[derive(thiserror::Error, Debug)] -pub enum CreateCustomerError { - #[error("user data error: {0:?}")] - UserData(#[from] ft_sdk::auth::UserDataError), - #[error("user not found")] - UserNotFound, - #[error("http error: {0:?}")] - HttpError(#[from] http::Error), - #[error("Cannot create customer: {0}")] - CannotCreateCustomer(String), -} - -// This is hack to keep mobile number as email. We need to soon remove this. -fn mobile_from_email(email: &str) -> Option { - email - .strip_suffix("@mobile.fifthtry.com") - .map(|s| s.to_string()) -} \ No newline at end of file diff --git a/ft-stripe/src/params.rs b/ft-stripe/src/params.rs deleted file mode 100644 index 44a070a..0000000 --- a/ft-stripe/src/params.rs +++ /dev/null @@ -1,254 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::resources::ApiVersion; -use serde::de::DeserializeOwned; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -#[derive(Clone, Default)] -pub struct AppInfo { - pub name: String, - pub url: Option, - pub version: Option, -} - -#[derive(Clone, Default)] -pub struct Headers { - pub client_id: Option, - pub stripe_version: Option, - pub stripe_account: Option, - pub user_agent: Option, -} - -/// Implemented by types which represent stripe objects. -pub trait Object { - /// The canonical id type for this object. - type Id; - /// The id of the object. - fn id(&self) -> Self::Id; - /// The object's type, typically represented in wire format as the `object` property. - fn object(&self) -> &'static str; -} - -/// A deleted object. -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Deleted { - /// Unique identifier for the object. - pub id: T, - /// Always true for a deleted object. - pub deleted: bool, -} - -/// The `Expand` struct is used to serialize `expand` arguments in retrieve and list apis. -#[doc(hidden)] -#[derive(Serialize)] -pub struct Expand<'a> { - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], -} - -impl Expand<'_> { - pub(crate) fn is_empty(expand: &[&str]) -> bool { - expand.is_empty() - } -} - -/// An id or object. -/// -/// By default stripe will return an id for most fields, but if more detail is -/// necessary the `expand` parameter can be provided to ask for the id to be -/// loaded as an object instead: -/// -/// ```rust,ignore -/// Charge::retrieve(&client, &charge_id, &["invoice.customer"]) -/// ``` -/// -/// See [https://stripe.com/docs/api/expanding_objects](https://stripe.com/docs/api/expanding_objects). -#[derive(Clone, Debug, Serialize, Deserialize)] // TODO: Implement deserialize by hand for better error messages -#[serde(untagged)] -pub enum Expandable { - Id(T::Id), - Object(Box), -} - -impl Expandable -where - T: Object, - T::Id: Clone, -{ - pub fn id(&self) -> T::Id { - match self { - Expandable::Id(id) => id.clone(), - Expandable::Object(obj) => obj.id(), - } - } -} - -impl Expandable { - pub fn is_object(&self) -> bool { - match self { - Expandable::Id(_) => false, - Expandable::Object(_) => true, - } - } - - pub fn as_object(&self) -> Option<&T> { - match self { - Expandable::Id(_) => None, - Expandable::Object(obj) => Some(&obj), - } - } - - #[deprecated( - note = "Renamed `into_object` per rust api design guidelines (may be removed in v0.12)" - )] - #[allow(clippy::wrong_self_convention)] - pub fn to_object(self) -> Option { - match self { - Expandable::Id(_) => None, - Expandable::Object(obj) => Some(*obj), - } - } - - pub fn into_object(self) -> Option { - match self { - Expandable::Id(_) => None, - Expandable::Object(obj) => Some(*obj), - } - } -} - -pub trait AsCursor: AsRef {} - -impl<'a> AsCursor for &'a str {} -impl AsCursor for String {} - -/// A single page of a cursor-paginated list of an object. -#[derive(Debug, Deserialize, Serialize)] -pub struct List { - pub data: Vec, - pub has_more: bool, - pub total_count: Option, - pub url: String, -} - -impl Default for List { - fn default() -> Self { - List { data: Vec::new(), has_more: false, total_count: None, url: String::new() } - } -} - -impl Clone for List { - fn clone(&self) -> Self { - List { - data: self.data.clone(), - has_more: self.has_more, - total_count: self.total_count, - url: self.url.clone(), - } - } -} - -pub type Metadata = HashMap; -pub type Timestamp = i64; - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(rename_all = "lowercase")] -pub struct RangeBounds { - pub gt: Option, - pub gte: Option, - pub lt: Option, - pub lte: Option, -} - -impl Default for RangeBounds { - fn default() -> Self { - RangeBounds { gt: None, gte: None, lt: None, lte: None } - } -} - -/// A set of generic request parameters that can be used on -/// list endpoints to filter their results by some timestamp. -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(untagged)] -pub enum RangeQuery { - Exact(T), - Bounds(RangeBounds), -} - -impl RangeQuery { - /// Filter results to exactly match a given value - pub fn eq(value: T) -> RangeQuery { - RangeQuery::Exact(value) - } - - /// Filter results to be after a given value - pub fn gt(value: T) -> RangeQuery { - let mut bounds = RangeBounds::default(); - bounds.gt = Some(value); - RangeQuery::Bounds(bounds) - } - - /// Filter results to be after or equal to a given value - pub fn gte(value: T) -> RangeQuery { - let mut bounds = RangeBounds::default(); - bounds.gte = Some(value); - RangeQuery::Bounds(bounds) - } - - /// Filter results to be before to a given value - pub fn lt(value: T) -> RangeQuery { - let mut bounds = RangeBounds::default(); - bounds.lt = Some(value); - RangeQuery::Bounds(bounds) - } - - /// Filter results to be before or equal to a given value - pub fn lte(value: T) -> RangeQuery { - let mut bounds = RangeBounds::default(); - bounds.lte = Some(value); - RangeQuery::Bounds(bounds) - } -} - -#[derive(Clone, Debug, Serialize)] -#[serde(untagged)] -pub enum IdOrCreate<'a, T> { - Id(&'a str), - Create(&'a T), -} - -// NOTE: Only intended to handle conversion from ASCII CamelCase to SnakeCase -// This function is used to convert static Rust identifiers to snakecase -// TODO: pub(crate) fn -pub fn to_snakecase(camel: &str) -> String { - let mut i = 0; - let mut snake = String::new(); - let mut chars = camel.chars().peekable(); - while let Some(ch) = chars.next() { - if ch.is_uppercase() { - if i > 0 && !chars.peek().unwrap_or(&'A').is_uppercase() { - snake.push('_'); - } - snake.push(ch.to_lowercase().next().unwrap_or(ch)); - } else { - snake.push(ch); - } - i += 1; - } - - snake -} - -#[cfg(test)] -mod tests { - #[test] - fn to_snakecase() { - use super::to_snakecase; - - assert_eq!(to_snakecase("snake_case").as_str(), "snake_case"); - assert_eq!(to_snakecase("CamelCase").as_str(), "camel_case"); - assert_eq!(to_snakecase("XMLHttpRequest").as_str(), "xml_http_request"); - assert_eq!(to_snakecase("UPPER").as_str(), "upper"); - assert_eq!(to_snakecase("lower").as_str(), "lower"); - } -} diff --git a/ft-stripe/src/resources.rs b/ft-stripe/src/resources.rs deleted file mode 100644 index bb43330..0000000 --- a/ft-stripe/src/resources.rs +++ /dev/null @@ -1,305 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// Builtin types -mod currency; -mod types; -pub use self::currency::*; -pub use self::types::*; - -// Core Resources -mod balance; -mod balance_transaction; -mod balance_transaction_ext; -mod charge; -mod charge_ext; -mod customer; -mod customer_ext; -mod dispute; -mod file; -mod file_link; -mod mandate; -mod payment_intent; -mod payment_source; -mod payout; -mod payout_ext; -mod platform_tax_fee; -mod product; -mod refund; -mod reserve_transaction; -mod setup_intent; -mod tax_deducted_at_source; -mod token; -mod token_ext; -pub use self::balance::*; -pub use self::balance_transaction::*; -pub use self::balance_transaction_ext::*; -pub use self::charge::*; -pub use self::charge_ext::*; -pub use self::customer::*; -pub use self::customer_ext::*; -pub use self::dispute::*; -pub use self::file::*; -pub use self::file_link::*; -pub use self::mandate::*; -pub use self::payment_intent::*; -pub use self::payment_source::*; -pub use self::payout::*; -pub use self::payout_ext::*; -pub use self::platform_tax_fee::*; -pub use self::product::*; -pub use self::refund::*; -pub use self::reserve_transaction::*; -pub use self::setup_intent::*; -pub use self::tax_deducted_at_source::*; -pub use self::token::*; -pub use self::token_ext::*; - -// Payment Methods -mod alipay_account; -mod bank_account; -mod bank_account_ext; -mod card; -mod payment_method; -mod payment_method_ext; -mod source; -mod source_ext; -pub use self::alipay_account::*; -pub use self::bank_account::*; -pub use self::bank_account_ext::*; -pub use self::card::*; -pub use self::payment_method::*; -pub use self::payment_method_ext::*; -pub use self::source::*; -pub use self::source_ext::*; - -// Events -#[cfg(feature = "events")] -mod event; -#[cfg(feature = "events")] -pub use self::event::*; - -// Checkout -#[cfg(feature = "checkout")] -mod checkout_session; -#[cfg(feature = "checkout")] -mod item; -#[cfg(feature = "checkout")] -pub use self::checkout_session::*; -#[cfg(feature = "checkout")] -pub use self::item::*; - -// Billing -#[cfg(feature = "billing")] -mod coupon; -#[cfg(feature = "billing")] -mod discount; -#[cfg(feature = "billing")] -mod invoice; -#[cfg(feature = "billing")] -mod invoice_ext; -#[cfg(feature = "billing")] -mod invoiceitem; -#[cfg(feature = "billing")] -mod line_item; -#[cfg(feature = "billing")] -mod line_item_ext; -#[cfg(feature = "billing")] -mod plan; -#[cfg(feature = "billing")] -mod price; -#[cfg(feature = "billing")] -mod subscription; -#[cfg(feature = "billing")] -mod subscription_ext; -#[cfg(feature = "billing")] -mod subscription_item; -#[cfg(feature = "billing")] -mod subscription_item_ext; -#[cfg(feature = "billing")] -mod subscription_schedule; -#[cfg(feature = "billing")] -mod tax_id; -#[cfg(feature = "billing")] -mod tax_rate; -#[cfg(feature = "billing")] -pub use self::coupon::*; -#[cfg(feature = "billing")] -pub use self::discount::*; -#[cfg(feature = "billing")] -pub use self::invoice::*; -#[cfg(feature = "billing")] -pub use self::invoice_ext::*; -#[cfg(feature = "billing")] -pub use self::invoiceitem::*; -#[cfg(feature = "billing")] -pub use self::line_item::*; -#[cfg(feature = "billing")] -pub use self::line_item_ext::*; -#[cfg(feature = "billing")] -pub use self::plan::*; -#[cfg(feature = "billing")] -pub use self::price::*; -#[cfg(feature = "billing")] -pub use self::subscription::*; -#[cfg(feature = "billing")] -pub use self::subscription_ext::*; -#[cfg(feature = "billing")] -pub use self::subscription_item::*; -#[cfg(feature = "billing")] -pub use self::subscription_item_ext::*; -#[cfg(feature = "billing")] -pub use self::subscription_schedule::*; -#[cfg(feature = "billing")] -pub use self::tax_id::*; -#[cfg(feature = "billing")] -pub use self::tax_rate::*; - -// Connect -#[cfg(feature = "connect")] -mod account; -#[cfg(feature = "connect")] -mod application; -#[cfg(feature = "connect")] -mod application_fee; -#[cfg(feature = "connect")] -mod connect_collection_transfer; -#[cfg(feature = "connect")] -mod fee_refund; -#[cfg(feature = "connect")] -mod person; -#[cfg(feature = "connect")] -mod recipient; -#[cfg(feature = "connect")] -mod topup; -#[cfg(feature = "connect")] -mod transfer; -#[cfg(feature = "connect")] -mod transfer_reversal; -#[cfg(feature = "connect")] -pub use self::account::*; -#[cfg(feature = "connect")] -pub use self::application::*; -#[cfg(feature = "connect")] -pub use self::application_fee::*; -#[cfg(feature = "connect")] -pub use self::connect_collection_transfer::*; -#[cfg(feature = "connect")] -pub use self::fee_refund::*; -#[cfg(feature = "connect")] -pub use self::person::*; -#[cfg(feature = "connect")] -pub use self::recipient::*; -#[cfg(feature = "connect")] -pub use self::topup::*; -#[cfg(feature = "connect")] -pub use self::transfer::*; -#[cfg(feature = "connect")] -pub use self::transfer_reversal::*; - -// Fraud -#[cfg(feature = "fraud")] -mod review; -#[cfg(feature = "fraud")] -mod review_ext; -#[cfg(feature = "fraud")] -pub use self::review::*; -#[cfg(feature = "fraud")] -pub use self::review_ext::*; - -// Issuing -#[cfg(feature = "issuing")] -mod issuing_authorization; -#[cfg(feature = "issuing")] -mod issuing_authorization_ext; -#[cfg(feature = "issuing")] -mod issuing_card; -#[cfg(feature = "issuing")] -mod issuing_card_ext; -#[cfg(feature = "issuing")] -mod issuing_cardholder; -#[cfg(feature = "issuing")] -mod issuing_dispute; -#[cfg(feature = "issuing")] -mod issuing_dispute_ext; -#[cfg(feature = "issuing")] -mod issuing_merchant_data; -#[cfg(feature = "issuing")] -mod issuing_transaction; -#[cfg(feature = "issuing")] -mod issuing_transaction_ext; -#[cfg(feature = "issuing")] -pub use self::issuing_authorization::*; -#[cfg(feature = "issuing")] -pub use self::issuing_authorization_ext::*; -#[cfg(feature = "issuing")] -pub use self::issuing_card::*; -#[cfg(feature = "issuing")] -pub use self::issuing_card_ext::*; -#[cfg(feature = "issuing")] -pub use self::issuing_cardholder::*; -#[cfg(feature = "issuing")] -pub use self::issuing_dispute::*; -#[cfg(feature = "issuing")] -pub use self::issuing_dispute_ext::*; -#[cfg(feature = "issuing")] -pub use self::issuing_merchant_data::*; -#[cfg(feature = "issuing")] -pub use self::issuing_transaction::*; -#[cfg(feature = "issuing")] -pub use self::issuing_transaction_ext::*; - -// Orders -#[cfg(feature = "orders")] -mod order; -#[cfg(feature = "orders")] -mod order_ext; -#[cfg(feature = "orders")] -mod order_item; -#[cfg(feature = "orders")] -mod order_return; -#[cfg(feature = "orders")] -mod sku; -#[cfg(feature = "orders")] -pub use self::order::*; -#[cfg(feature = "orders")] -pub use self::order_ext::*; -#[cfg(feature = "orders")] -pub use self::order_item::*; -#[cfg(feature = "orders")] -pub use self::order_return::*; -#[cfg(feature = "orders")] -pub use self::sku::*; - -#[cfg(feature = "sigma")] -mod scheduled_query_run; -#[cfg(feature = "sigma")] -pub use self::scheduled_query_run::*; - -// Not-yet-implemented feature flags -#[cfg(feature = "webhook-endpoints")] -mod webhook_endpoint; -#[cfg(feature = "webhook-endpoints")] -mod webhook_endpoint_ext; -#[cfg(feature = "webhook-endpoints")] -pub use self::webhook_endpoint::*; -#[cfg(feature = "webhook-endpoints")] -pub use self::webhook_endpoint_ext::*; - -// Fallback types -#[cfg(not(feature = "full"))] -mod placeholders; -#[cfg(not(feature = "full"))] -pub use self::placeholders::*; - -#[cfg(not(feature = "account"))] -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct CompanyParams { - #[serde(default)] - pub metadata: crate::params::Metadata, -} - -#[cfg(not(feature = "account"))] -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -pub struct PersonParams { - #[serde(default)] - pub metadata: crate::params::Metadata, -} diff --git a/ft-stripe/src/resources/account.rs b/ft-stripe/src/resources/account.rs deleted file mode 100644 index d77ba19..0000000 --- a/ft-stripe/src/resources/account.rs +++ /dev/null @@ -1,1421 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::AccountId; -use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Address, BankAccount, BusinessType, Card, Currency, DelayDays, Dob, File, Person, - PersonVerificationParams, VerificationDocumentParams, Weekday, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Account". -/// -/// For more details see [https://stripe.com/docs/api/accounts/object](https://stripe.com/docs/api/accounts/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Account { - /// Unique identifier for the object. - pub id: AccountId, - - /// Business information about the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_profile: Option, - - /// The business type. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub capabilities: Option, - - /// Whether the account can create live charges. - #[serde(skip_serializing_if = "Option::is_none")] - pub charges_enabled: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub company: Option, - - /// The account's country. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter ISO currency code representing the default currency for the account. - /// - /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). - #[serde(skip_serializing_if = "Option::is_none")] - pub default_currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Whether account details have been submitted. - /// - /// Standard accounts cannot receive payouts before this is true. - #[serde(skip_serializing_if = "Option::is_none")] - pub details_submitted: Option, - - /// The primary user's email address. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// External accounts (bank accounts and debit cards) currently attached to this account. - #[serde(default)] - pub external_accounts: List, - - #[serde(skip_serializing_if = "Option::is_none")] - pub individual: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// Whether Stripe can send payouts to this account. - #[serde(skip_serializing_if = "Option::is_none")] - pub payouts_enabled: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub requirements: Option, - - /// Options for customizing how the account functions within Stripe. - #[serde(skip_serializing_if = "Option::is_none")] - pub settings: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tos_acceptance: Option, - - /// The Stripe account type. - /// - /// Can be `standard`, `express`, or `custom`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -impl Account { - /// Returns a list of accounts connected to your platform via [Connect](https://stripe.com/docs/connect). - /// - /// If you’re not a platform, the list is empty. - pub fn list(client: &Client, params: ListAccounts<'_>) -> Response> { - client.get_query("/accounts", ¶ms) - } - - /// With [Connect](https://stripe.com/docs/connect), you can create Stripe accounts for your users. - /// To do this, you’ll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings). - pub fn create(client: &Client, params: CreateAccount<'_>) -> Response { - client.post_form("/accounts", ¶ms) - } - - /// Retrieves the details of an account. - pub fn retrieve(client: &Client, id: &AccountId, expand: &[&str]) -> Response { - client.get_query(&format!("/accounts/{}", id), &Expand { expand }) - } - - /// Updates a connected [Express or Custom account](https://stripe.com/docs/connect/accounts) by setting the values of the parameters passed. - /// - /// Any parameters not provided are left unchanged. - /// Most parameters can be changed only for Custom accounts. - /// (These are marked **Custom Only** below.) Parameters marked **Custom and Express** are supported by both account types. To update your own account, use the [Dashboard](https://dashboard.stripe.com/account). - /// Refer to our [Connect](https://stripe.com/docs/connect/updating-accounts) documentation to learn more about updating accounts. - pub fn update(client: &Client, id: &AccountId, params: UpdateAccount<'_>) -> Response { - client.post_form(&format!("/accounts/{}", id), ¶ms) - } - - /// With [Connect](https://stripe.com/docs/connect), you can delete Custom or Express accounts you manage. - /// - /// Accounts created using test-mode keys can be deleted at any time. - /// - /// Accounts created using live-mode keys can only be deleted once all balances are zero. If you want to delete your own account, use the [account information tab in your account settings](https://dashboard.stripe.com/account) instead. - pub fn delete(client: &Client, id: &AccountId) -> Response> { - client.delete(&format!("/accounts/{}", id)) - } -} - -impl Object for Account { - type Id = AccountId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "account" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BusinessProfile { - /// [The merchant category code for the account](https://stripe.com/docs/connect/setting-mcc). - /// - /// MCCs are used to classify businesses based on the goods or services they provide. - #[serde(skip_serializing_if = "Option::is_none")] - pub mcc: Option, - - /// The customer-facing business name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Internal-only description of the product sold or service provided by the business. - /// - /// It's used by Stripe for risk and underwriting purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub product_description: Option, - - /// A publicly available mailing address for sending support issues to. - #[serde(skip_serializing_if = "Option::is_none")] - pub support_address: Option
, - - /// A publicly available email address for sending support issues to. - #[serde(skip_serializing_if = "Option::is_none")] - pub support_email: Option, - - /// A publicly available phone number to call with support issues. - #[serde(skip_serializing_if = "Option::is_none")] - pub support_phone: Option, - - /// A publicly available website for handling support issues. - #[serde(skip_serializing_if = "Option::is_none")] - pub support_url: Option, - - /// The business's publicly available website. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountCapabilities { - /// The status of the BECS Direct Debit (AU) payments capability of the account, or whether the account can directly process BECS Direct Debit (AU) charges. - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit_payments: Option, - - /// The status of the card issuing capability of the account, or whether you can use Issuing to distribute funds on cards. - #[serde(skip_serializing_if = "Option::is_none")] - pub card_issuing: Option, - - /// The status of the card payments capability of the account, or whether the account can directly process credit and debit card charges. - #[serde(skip_serializing_if = "Option::is_none")] - pub card_payments: Option, - - /// The status of the JCB payments capability of the account, or whether the account (Japan only) can directly process JCB credit card charges in JPY currency. - #[serde(skip_serializing_if = "Option::is_none")] - pub jcb_payments: Option, - - /// The status of the legacy payments capability of the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub legacy_payments: Option, - - /// The status of the tax reporting 1099-K (US) capability of the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_reporting_us_1099_k: Option, - - /// The status of the tax reporting 1099-MISC (US) capability of the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_reporting_us_1099_misc: Option, - - /// The status of the transfers capability of the account, or whether your platform can transfer funds to the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfers: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountRequirements { - /// The date the fields in `currently_due` must be collected by to keep payouts enabled for the account. - /// - /// These fields might block payouts sooner if the next threshold is reached before these fields are collected. - #[serde(skip_serializing_if = "Option::is_none")] - pub current_deadline: Option, - - /// The fields that need to be collected to keep the account enabled. - /// - /// If not collected by the `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. - #[serde(skip_serializing_if = "Option::is_none")] - pub currently_due: Option>, - - /// If the account is disabled, this string describes why the account can’t create charges or receive payouts. - /// - /// Can be `requirements.past_due`, `requirements.pending_verification`, `rejected.fraud`, `rejected.terms_of_service`, `rejected.listed`, `rejected.other`, `listed`, `under_review`, or `other`. - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_reason: Option, - - /// The fields that need to be collected again because validation or verification failed for some reason. - #[serde(skip_serializing_if = "Option::is_none")] - pub errors: Option>, - - /// The fields that need to be collected assuming all volume thresholds are reached. - /// - /// As they become required, these fields appear in `currently_due` as well, and the `current_deadline` is set. - #[serde(skip_serializing_if = "Option::is_none")] - pub eventually_due: Option>, - - /// The fields that weren't collected by the `current_deadline`. - /// - /// These fields need to be collected to re-enable the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub past_due: Option>, - - /// Fields that may become required depending on the results of verification or review. - /// - /// An empty array unless an asynchronous verification is pending. - /// If verification fails, the fields in this array become required and move to `currently_due` or `past_due`. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_verification: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountRequirementsError { - /// The code for the type of error. - pub code: AccountRequirementsErrorCode, - - /// An informative message that indicates the error type and provides additional details about the error. - pub reason: String, - - /// The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. - pub requirement: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountSettings { - pub branding: BrandingSettings, - - pub card_payments: CardPaymentsSettings, - - pub dashboard: DashboardSettings, - - pub payments: PaymentsSettings, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payouts: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BrandingSettings { - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) An icon for the account. - /// - /// Must be square and at least 128px x 128px. - #[serde(skip_serializing_if = "Option::is_none")] - pub icon: Option>, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A logo for the account that will be used in Checkout instead of the icon and without the account's name next to it if provided. - /// - /// Must be at least 128px x 128px. - #[serde(skip_serializing_if = "Option::is_none")] - pub logo: Option>, - - /// A CSS hex color value representing the primary branding color for this account. - #[serde(skip_serializing_if = "Option::is_none")] - pub primary_color: Option, - - /// A CSS hex color value representing the secondary branding color for this account. - #[serde(skip_serializing_if = "Option::is_none")] - pub secondary_color: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CardPaymentsSettings { - #[serde(skip_serializing_if = "Option::is_none")] - pub decline_on: Option, - - /// The default text that appears on credit card statements when a charge is made. - /// - /// This field prefixes any dynamic `statement_descriptor` specified on the charge. - /// `statement_descriptor_prefix` is useful for maximizing descriptor space for the dynamic portion. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_prefix: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DashboardSettings { - /// The display name for this account. - /// - /// This is used on the Stripe Dashboard to differentiate between accounts. - #[serde(skip_serializing_if = "Option::is_none")] - pub display_name: Option, - - /// The timezone used in the Stripe Dashboard for this account. - /// - /// A list of possible time zone values is maintained at the [IANA Time Zone Database](http://www.iana.org/time-zones). - #[serde(skip_serializing_if = "Option::is_none")] - pub timezone: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DeclineChargeOn { - /// Whether Stripe automatically declines charges with an incorrect ZIP or postal code. - /// - /// This setting only applies when a ZIP or postal code is provided and they fail bank verification. - pub avs_failure: bool, - - /// Whether Stripe automatically declines charges with an incorrect CVC. - /// - /// This setting only applies when a CVC is provided and it fails bank verification. - pub cvc_failure: bool, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentsSettings { - /// The default text that appears on credit card statements when a charge is made. - /// - /// This field prefixes any dynamic `statement_descriptor` specified on the charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// The Kana variation of the default text that appears on credit card statements when a charge is made (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_kana: Option, - - /// The Kanji variation of the default text that appears on credit card statements when a charge is made (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_kanji: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PayoutSettings { - /// A Boolean indicating if Stripe should try to reclaim negative balances from an attached bank account. - /// - /// See our [Understanding Connect Account Balances](https://stripe.com/docs/connect/account-balances) documentation for details. - /// Default value is `true` for Express accounts and `false` for Custom accounts. - pub debit_negative_balances: bool, - - pub schedule: TransferSchedule, - - /// The text that appears on the bank account statement for payouts. - /// - /// If not set, this defaults to the platform's bank descriptor as set in the Dashboard. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TosAcceptance { - /// The Unix timestamp marking when the Stripe Services Agreement was accepted by the account representative. - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - /// The IP address from which the Stripe Services Agreement was accepted by the account representative. - #[serde(skip_serializing_if = "Option::is_none")] - pub ip: Option, - - /// The user agent of the browser from which the Stripe Services Agreement was accepted by the account representative. - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Company { - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - /// The Kana variation of the company's primary address (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kana: Option
, - - /// The Kanji variation of the company's primary address (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kanji: Option
, - - /// Whether the company's directors have been provided. - /// - /// This Boolean will be `true` if you've manually indicated that all directors are provided via [the `directors_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-directors_provided). - #[serde(skip_serializing_if = "Option::is_none")] - pub directors_provided: Option, - - /// Whether the company's executives have been provided. - /// - /// This Boolean will be `true` if you've manually indicated that all executives are provided via [the `executives_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-executives_provided), or if Stripe determined that sufficient executives were provided. - #[serde(skip_serializing_if = "Option::is_none")] - pub executives_provided: Option, - - /// The company's legal name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// The Kana variation of the company's legal name (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub name_kana: Option, - - /// The Kanji variation of the company's legal name (Japan only). - #[serde(skip_serializing_if = "Option::is_none")] - pub name_kanji: Option, - - /// Whether the company's owners have been provided. - /// - /// This Boolean will be `true` if you've manually indicated that all owners are provided via [the `owners_provided` parameter](https://stripe.com/docs/api/accounts/update#update_account-company-owners_provided), or if Stripe determined that sufficient owners were provided. - /// Stripe determines ownership requirements using both the number of owners provided and their total percent ownership (calculated by adding the `percent_ownership` of each owner together). - #[serde(skip_serializing_if = "Option::is_none")] - pub owners_provided: Option, - - /// The company's phone number (used for verification). - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - /// The category identifying the legal structure of the company or legal entity. - /// - /// See [Business structure](https://stripe.com/docs/connect/identity-verification#business-structure) for more details. - #[serde(skip_serializing_if = "Option::is_none")] - pub structure: Option, - - /// Whether the company's business ID number was provided. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id_provided: Option, - - /// The jurisdiction in which the `tax_id` is registered (Germany-based companies only). - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id_registrar: Option, - - /// Whether the company's business VAT number was provided. - #[serde(skip_serializing_if = "Option::is_none")] - pub vat_id_provided: Option, - - /// Information on the verification state of the company. - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CompanyVerification { - pub document: CompanyVerificationDocument, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CompanyVerificationDocument { - /// The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. - #[serde(skip_serializing_if = "Option::is_none")] - pub back: Option>, - - /// A user-displayable string describing the verification state of this document. - #[serde(skip_serializing_if = "Option::is_none")] - pub details: Option, - - /// One of `document_corrupt`, `document_expired`, `document_failed_copy`, `document_failed_greyscale`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_not_readable`, `document_not_uploaded`, `document_type_not_supported`, or `document_too_large`. - /// - /// A machine-readable code specifying the verification state for this document. - #[serde(skip_serializing_if = "Option::is_none")] - pub details_code: Option, - - /// The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `additional_verification`. - #[serde(skip_serializing_if = "Option::is_none")] - pub front: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferSchedule { - /// The number of days charges for the account will be held before being paid out. - pub delay_days: u32, - - /// How frequently funds will be paid out. - /// - /// One of `manual` (payouts only created via API call), `daily`, `weekly`, or `monthly`. - pub interval: String, - - /// The day of the month funds will be paid out. - /// - /// Only shown if `interval` is monthly. - /// Payouts scheduled between the 29th and 31st of the month are sent on the last day of shorter months. - #[serde(skip_serializing_if = "Option::is_none")] - pub monthly_anchor: Option, - - /// The day of the week funds will be paid out, of the style 'monday', 'tuesday', etc. - /// - /// Only shown if `interval` is weekly. - #[serde(skip_serializing_if = "Option::is_none")] - pub weekly_anchor: Option, -} - -/// The parameters for `Account::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateAccount<'a> { - /// An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_token: Option<&'a str>, - - /// Business information about the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_profile: Option, - - /// The business type. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_type: Option, - - /// Information about the company or business. - /// - /// This field is null unless `business_type` is set to `company`, `government_entity`, or `non_profit`. - #[serde(skip_serializing_if = "Option::is_none")] - pub company: Option, - - /// The country in which the account holder resides, or in which the business is legally established. - /// - /// This should be an ISO 3166-1 alpha-2 country code. - /// For example, if you are in the United States and the business for which you're creating an account is legally represented in Canada, you would use `CA` as the country for the account being created. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option<&'a str>, - - /// Three-letter ISO currency code representing the default currency for the account. - /// - /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). - #[serde(skip_serializing_if = "Option::is_none")] - pub default_currency: Option, - - /// The email address of the account holder. - /// - /// For Custom accounts, this is only to make the account easier to identify to you: Stripe will never directly email your users. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A card or bank account to attach to the account. - /// - /// You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe.js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. - /// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. - /// To add additional external accounts without replacing the existing default for the currency, use the bank account or card creation API. - #[serde(skip_serializing_if = "Option::is_none")] - pub external_account: Option<&'a str>, - - /// Information about the person represented by the account. - /// - /// This field is null unless `business_type` is set to `individual`. - #[serde(skip_serializing_if = "Option::is_none")] - pub individual: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The set of capabilities you want to unlock for this account. - /// - /// Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. - /// An account may have some of its requested capabilities be active and some be inactive. - #[serde(skip_serializing_if = "Option::is_none")] - pub requested_capabilities: Option>, - - /// Options for customizing how the account functions within Stripe. - #[serde(skip_serializing_if = "Option::is_none")] - pub settings: Option, - - /// Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance). - #[serde(skip_serializing_if = "Option::is_none")] - pub tos_acceptance: Option, - - /// The type of Stripe account to create. - /// - /// Currently must be `custom`, as only [Custom accounts](https://stripe.com/docs/connect/custom-accounts) may be created via the API. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -impl<'a> CreateAccount<'a> { - pub fn new() -> Self { - CreateAccount { - account_token: Default::default(), - business_profile: Default::default(), - business_type: Default::default(), - company: Default::default(), - country: Default::default(), - default_currency: Default::default(), - email: Default::default(), - expand: Default::default(), - external_account: Default::default(), - individual: Default::default(), - metadata: Default::default(), - requested_capabilities: Default::default(), - settings: Default::default(), - tos_acceptance: Default::default(), - type_: Default::default(), - } - } -} - -/// The parameters for `Account::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListAccounts<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListAccounts<'a> { - pub fn new() -> Self { - ListAccounts { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Account::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateAccount<'a> { - /// An [account token](https://stripe.com/docs/api#create_account_token), used to securely provide details to the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_token: Option<&'a str>, - - /// Business information about the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_profile: Option, - - /// The business type. - #[serde(skip_serializing_if = "Option::is_none")] - pub business_type: Option, - - /// Information about the company or business. - /// - /// This field is null unless `business_type` is set to `company`, `government_entity`, or `non_profit`. - #[serde(skip_serializing_if = "Option::is_none")] - pub company: Option, - - /// Three-letter ISO currency code representing the default currency for the account. - /// - /// This must be a currency that [Stripe supports in the account's country](https://stripe.com/docs/payouts). - #[serde(skip_serializing_if = "Option::is_none")] - pub default_currency: Option, - - /// Email address of the account representative. - /// - /// For Standard accounts, this is used to ask them to claim their Stripe account. - /// For Custom accounts, this only makes the account easier to identify to platforms; Stripe does not email the account representative. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A card or bank account to attach to the account. - /// - /// You can provide either a token, like the ones returned by [Stripe.js](https://stripe.com/docs/stripe.js), or a dictionary, as documented in the `external_account` parameter for [bank account](https://stripe.com/docs/api#account_create_bank_account) creation. - /// By default, providing an external account sets it as the new default external account for its currency, and deletes the old default if one exists. - /// To add additional external accounts without replacing the existing default for the currency, use the bank account or card creation API. - #[serde(skip_serializing_if = "Option::is_none")] - pub external_account: Option<&'a str>, - - /// Information about the person represented by the account. - /// - /// This field is null unless `business_type` is set to `individual`. - #[serde(skip_serializing_if = "Option::is_none")] - pub individual: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The set of capabilities you want to unlock for this account. - /// - /// Each capability will be inactive until you have provided its specific requirements and Stripe has verified them. - /// An account may have some of its requested capabilities be active and some be inactive. - #[serde(skip_serializing_if = "Option::is_none")] - pub requested_capabilities: Option>, - - /// Options for customizing how the account functions within Stripe. - #[serde(skip_serializing_if = "Option::is_none")] - pub settings: Option, - - /// Details on the account's acceptance of the [Stripe Services Agreement](https://stripe.com/docs/connect/updating-accounts#tos-acceptance). - #[serde(skip_serializing_if = "Option::is_none")] - pub tos_acceptance: Option, -} - -impl<'a> UpdateAccount<'a> { - pub fn new() -> Self { - UpdateAccount { - account_token: Default::default(), - business_profile: Default::default(), - business_type: Default::default(), - company: Default::default(), - default_currency: Default::default(), - email: Default::default(), - expand: Default::default(), - external_account: Default::default(), - individual: Default::default(), - metadata: Default::default(), - requested_capabilities: Default::default(), - settings: Default::default(), - tos_acceptance: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AcceptTos { - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ip: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub branding: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card_payments: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payments: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payouts: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CompanyParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kana: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kanji: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub directors_provided: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub executives_provided: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub owners_provided: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub structure: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id_registrar: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub vat_id: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kana: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kanji: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dob: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub gender: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub id_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub maiden_name: Option, - - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ssn_last_4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BrandingSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub icon: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub logo: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub primary_color: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub secondary_color: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CardPaymentsSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub decline_on: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_prefix: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CompanyVerificationParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub document: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentsSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_kanji: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PayoutSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub debit_negative_balances: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub schedule: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DeclineChargeOnParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub avs_failure: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc_failure: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferScheduleParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub delay_days: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub monthly_anchor: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub weekly_anchor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum ExternalAccount { - BankAccount(BankAccount), - Card(Card), -} - -/// An enum representing the possible values of an `AccountRequirementsError`'s `code` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum AccountRequirementsErrorCode { - InvalidAddressCityStatePostalCode, - InvalidStreetAddress, - InvalidValueOther, - VerificationDocumentAddressMismatch, - VerificationDocumentAddressMissing, - VerificationDocumentCorrupt, - VerificationDocumentCountryNotSupported, - VerificationDocumentDobMismatch, - VerificationDocumentDuplicateType, - VerificationDocumentExpired, - VerificationDocumentFailedCopy, - VerificationDocumentFailedGreyscale, - VerificationDocumentFailedOther, - VerificationDocumentFailedTestMode, - VerificationDocumentFraudulent, - VerificationDocumentIdNumberMismatch, - VerificationDocumentIdNumberMissing, - VerificationDocumentIncomplete, - VerificationDocumentInvalid, - VerificationDocumentManipulated, - VerificationDocumentMissingBack, - VerificationDocumentMissingFront, - VerificationDocumentNameMismatch, - VerificationDocumentNameMissing, - VerificationDocumentNationalityMismatch, - VerificationDocumentNotReadable, - VerificationDocumentNotUploaded, - VerificationDocumentPhotoMismatch, - VerificationDocumentTooLarge, - VerificationDocumentTypeNotSupported, - VerificationFailedAddressMatch, - VerificationFailedBusinessIecNumber, - VerificationFailedDocumentMatch, - VerificationFailedIdNumberMatch, - VerificationFailedKeyedIdentity, - VerificationFailedKeyedMatch, - VerificationFailedNameMatch, - VerificationFailedOther, -} - -impl AccountRequirementsErrorCode { - pub fn as_str(self) -> &'static str { - match self { - AccountRequirementsErrorCode::InvalidAddressCityStatePostalCode => { - "invalid_address_city_state_postal_code" - } - AccountRequirementsErrorCode::InvalidStreetAddress => "invalid_street_address", - AccountRequirementsErrorCode::InvalidValueOther => "invalid_value_other", - AccountRequirementsErrorCode::VerificationDocumentAddressMismatch => { - "verification_document_address_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentAddressMissing => { - "verification_document_address_missing" - } - AccountRequirementsErrorCode::VerificationDocumentCorrupt => { - "verification_document_corrupt" - } - AccountRequirementsErrorCode::VerificationDocumentCountryNotSupported => { - "verification_document_country_not_supported" - } - AccountRequirementsErrorCode::VerificationDocumentDobMismatch => { - "verification_document_dob_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentDuplicateType => { - "verification_document_duplicate_type" - } - AccountRequirementsErrorCode::VerificationDocumentExpired => { - "verification_document_expired" - } - AccountRequirementsErrorCode::VerificationDocumentFailedCopy => { - "verification_document_failed_copy" - } - AccountRequirementsErrorCode::VerificationDocumentFailedGreyscale => { - "verification_document_failed_greyscale" - } - AccountRequirementsErrorCode::VerificationDocumentFailedOther => { - "verification_document_failed_other" - } - AccountRequirementsErrorCode::VerificationDocumentFailedTestMode => { - "verification_document_failed_test_mode" - } - AccountRequirementsErrorCode::VerificationDocumentFraudulent => { - "verification_document_fraudulent" - } - AccountRequirementsErrorCode::VerificationDocumentIdNumberMismatch => { - "verification_document_id_number_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentIdNumberMissing => { - "verification_document_id_number_missing" - } - AccountRequirementsErrorCode::VerificationDocumentIncomplete => { - "verification_document_incomplete" - } - AccountRequirementsErrorCode::VerificationDocumentInvalid => { - "verification_document_invalid" - } - AccountRequirementsErrorCode::VerificationDocumentManipulated => { - "verification_document_manipulated" - } - AccountRequirementsErrorCode::VerificationDocumentMissingBack => { - "verification_document_missing_back" - } - AccountRequirementsErrorCode::VerificationDocumentMissingFront => { - "verification_document_missing_front" - } - AccountRequirementsErrorCode::VerificationDocumentNameMismatch => { - "verification_document_name_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentNameMissing => { - "verification_document_name_missing" - } - AccountRequirementsErrorCode::VerificationDocumentNationalityMismatch => { - "verification_document_nationality_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentNotReadable => { - "verification_document_not_readable" - } - AccountRequirementsErrorCode::VerificationDocumentNotUploaded => { - "verification_document_not_uploaded" - } - AccountRequirementsErrorCode::VerificationDocumentPhotoMismatch => { - "verification_document_photo_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentTooLarge => { - "verification_document_too_large" - } - AccountRequirementsErrorCode::VerificationDocumentTypeNotSupported => { - "verification_document_type_not_supported" - } - AccountRequirementsErrorCode::VerificationFailedAddressMatch => { - "verification_failed_address_match" - } - AccountRequirementsErrorCode::VerificationFailedBusinessIecNumber => { - "verification_failed_business_iec_number" - } - AccountRequirementsErrorCode::VerificationFailedDocumentMatch => { - "verification_failed_document_match" - } - AccountRequirementsErrorCode::VerificationFailedIdNumberMatch => { - "verification_failed_id_number_match" - } - AccountRequirementsErrorCode::VerificationFailedKeyedIdentity => { - "verification_failed_keyed_identity" - } - AccountRequirementsErrorCode::VerificationFailedKeyedMatch => { - "verification_failed_keyed_match" - } - AccountRequirementsErrorCode::VerificationFailedNameMatch => { - "verification_failed_name_match" - } - AccountRequirementsErrorCode::VerificationFailedOther => "verification_failed_other", - } - } -} - -impl AsRef for AccountRequirementsErrorCode { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for AccountRequirementsErrorCode { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateAccount`'s `type_` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum AccountType { - Custom, - Express, - Standard, -} - -impl AccountType { - pub fn as_str(self) -> &'static str { - match self { - AccountType::Custom => "custom", - AccountType::Express => "express", - AccountType::Standard => "standard", - } - } -} - -impl AsRef for AccountType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for AccountType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `AccountCapabilities`'s `au_becs_debit_payments` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CapabilityStatus { - Active, - Inactive, - Pending, -} - -impl CapabilityStatus { - pub fn as_str(self) -> &'static str { - match self { - CapabilityStatus::Active => "active", - CapabilityStatus::Inactive => "inactive", - CapabilityStatus::Pending => "pending", - } - } -} - -impl AsRef for CapabilityStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CapabilityStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CompanyParams`'s `structure` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CompanyParamsStructure { - GovernmentInstrumentality, - GovernmentalUnit, - IncorporatedNonProfit, - LimitedLiabilityPartnership, - MultiMemberLlc, - PrivateCompany, - PrivateCorporation, - PrivatePartnership, - PublicCompany, - PublicCorporation, - PublicPartnership, - SoleProprietorship, - TaxExemptGovernmentInstrumentality, - UnincorporatedAssociation, - UnincorporatedNonProfit, -} - -impl CompanyParamsStructure { - pub fn as_str(self) -> &'static str { - match self { - CompanyParamsStructure::GovernmentInstrumentality => "government_instrumentality", - CompanyParamsStructure::GovernmentalUnit => "governmental_unit", - CompanyParamsStructure::IncorporatedNonProfit => "incorporated_non_profit", - CompanyParamsStructure::LimitedLiabilityPartnership => "limited_liability_partnership", - CompanyParamsStructure::MultiMemberLlc => "multi_member_llc", - CompanyParamsStructure::PrivateCompany => "private_company", - CompanyParamsStructure::PrivateCorporation => "private_corporation", - CompanyParamsStructure::PrivatePartnership => "private_partnership", - CompanyParamsStructure::PublicCompany => "public_company", - CompanyParamsStructure::PublicCorporation => "public_corporation", - CompanyParamsStructure::PublicPartnership => "public_partnership", - CompanyParamsStructure::SoleProprietorship => "sole_proprietorship", - CompanyParamsStructure::TaxExemptGovernmentInstrumentality => { - "tax_exempt_government_instrumentality" - } - CompanyParamsStructure::UnincorporatedAssociation => "unincorporated_association", - CompanyParamsStructure::UnincorporatedNonProfit => "unincorporated_non_profit", - } - } -} - -impl AsRef for CompanyParamsStructure { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CompanyParamsStructure { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Company`'s `structure` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CompanyStructure { - GovernmentInstrumentality, - GovernmentalUnit, - IncorporatedNonProfit, - LimitedLiabilityPartnership, - MultiMemberLlc, - PrivateCompany, - PrivateCorporation, - PrivatePartnership, - PublicCompany, - PublicCorporation, - PublicPartnership, - SoleProprietorship, - TaxExemptGovernmentInstrumentality, - UnincorporatedAssociation, - UnincorporatedNonProfit, -} - -impl CompanyStructure { - pub fn as_str(self) -> &'static str { - match self { - CompanyStructure::GovernmentInstrumentality => "government_instrumentality", - CompanyStructure::GovernmentalUnit => "governmental_unit", - CompanyStructure::IncorporatedNonProfit => "incorporated_non_profit", - CompanyStructure::LimitedLiabilityPartnership => "limited_liability_partnership", - CompanyStructure::MultiMemberLlc => "multi_member_llc", - CompanyStructure::PrivateCompany => "private_company", - CompanyStructure::PrivateCorporation => "private_corporation", - CompanyStructure::PrivatePartnership => "private_partnership", - CompanyStructure::PublicCompany => "public_company", - CompanyStructure::PublicCorporation => "public_corporation", - CompanyStructure::PublicPartnership => "public_partnership", - CompanyStructure::SoleProprietorship => "sole_proprietorship", - CompanyStructure::TaxExemptGovernmentInstrumentality => { - "tax_exempt_government_instrumentality" - } - CompanyStructure::UnincorporatedAssociation => "unincorporated_association", - CompanyStructure::UnincorporatedNonProfit => "unincorporated_non_profit", - } - } -} - -impl AsRef for CompanyStructure { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CompanyStructure { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateAccount`'s `requested_capabilities` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RequestedCapability { - AuBecsDebitPayments, - CardIssuing, - CardPayments, - JcbPayments, - LegacyPayments, - #[serde(rename = "tax_reporting_us_1099_k")] - TaxReportingUs1099K, - #[serde(rename = "tax_reporting_us_1099_misc")] - TaxReportingUs1099Misc, - Transfers, -} - -impl RequestedCapability { - pub fn as_str(self) -> &'static str { - match self { - RequestedCapability::AuBecsDebitPayments => "au_becs_debit_payments", - RequestedCapability::CardIssuing => "card_issuing", - RequestedCapability::CardPayments => "card_payments", - RequestedCapability::JcbPayments => "jcb_payments", - RequestedCapability::LegacyPayments => "legacy_payments", - RequestedCapability::TaxReportingUs1099K => "tax_reporting_us_1099_k", - RequestedCapability::TaxReportingUs1099Misc => "tax_reporting_us_1099_misc", - RequestedCapability::Transfers => "transfers", - } - } -} - -impl AsRef for RequestedCapability { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RequestedCapability { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `TransferScheduleParams`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TransferScheduleInterval { - Daily, - Manual, - Monthly, - Weekly, -} - -impl TransferScheduleInterval { - pub fn as_str(self) -> &'static str { - match self { - TransferScheduleInterval::Daily => "daily", - TransferScheduleInterval::Manual => "manual", - TransferScheduleInterval::Monthly => "monthly", - TransferScheduleInterval::Weekly => "weekly", - } - } -} - -impl AsRef for TransferScheduleInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TransferScheduleInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/alipay_account.rs b/ft-stripe/src/resources/alipay_account.rs deleted file mode 100644 index 65a8cb4..0000000 --- a/ft-stripe/src/resources/alipay_account.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::AlipayAccountId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{Currency, Customer}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "AlipayAccount". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AlipayAccount { - /// Unique identifier for the object. - pub id: AlipayAccountId, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// The ID of the customer associated with this Alipay Account. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Uniquely identifies the account and will be the same across all Alipay account objects that are linked to the same Alipay account. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// If the Alipay account object is not reusable, the exact amount that you can create a charge for. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_amount: Option, - - /// If the Alipay account object is not reusable, the exact currency that you can create a charge for. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_currency: Option, - - /// True if you can create multiple payments using this account. - /// - /// If the account is reusable, then you can freely choose the amount of each payment. - #[serde(skip_serializing_if = "Option::is_none")] - pub reusable: Option, - - /// Whether this Alipay account object has ever been used for a payment. - #[serde(skip_serializing_if = "Option::is_none")] - pub used: Option, - - /// The username for the Alipay account. - #[serde(skip_serializing_if = "Option::is_none")] - pub username: Option, -} - -impl Object for AlipayAccount { - type Id = AlipayAccountId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "alipay_account" - } -} diff --git a/ft-stripe/src/resources/application.rs b/ft-stripe/src/resources/application.rs deleted file mode 100644 index d601ff4..0000000 --- a/ft-stripe/src/resources/application.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::ApplicationId; -use crate::params::Object; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Application". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Application { - /// Unique identifier for the object. - pub id: ApplicationId, - - /// The name of the application. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, -} - -impl Object for Application { - type Id = ApplicationId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "application" - } -} diff --git a/ft-stripe/src/resources/application_fee.rs b/ft-stripe/src/resources/application_fee.rs deleted file mode 100644 index c88fe35..0000000 --- a/ft-stripe/src/resources/application_fee.rs +++ /dev/null @@ -1,146 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ApplicationFeeId, ChargeId}; -use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Account, Application, ApplicationFeeRefund, BalanceTransaction, Charge, Currency, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "PlatformFee". -/// -/// For more details see [https://stripe.com/docs/api/application_fees/object](https://stripe.com/docs/api/application_fees/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ApplicationFee { - /// Unique identifier for the object. - pub id: ApplicationFeeId, - - /// ID of the Stripe account this fee was taken from. - pub account: Expandable, - - /// Amount earned, in %s. - pub amount: i64, - - /// Amount in %s refunded (can be less than the amount attribute on the fee if a partial refund was issued). - pub amount_refunded: i64, - - /// ID of the Connect application that earned the fee. - pub application: Expandable, - - /// Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds). - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// ID of the charge that the application fee was taken from. - pub charge: Expandable, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// ID of the corresponding charge on the platform account, if this fee was the result of a charge using the `destination` parameter. - #[serde(skip_serializing_if = "Option::is_none")] - pub originating_transaction: Option>, - - /// Whether the fee has been fully refunded. - /// - /// If the fee is only partially refunded, this attribute will still be false. - pub refunded: bool, - - /// A list of refunds that have been applied to the fee. - pub refunds: List, -} - -impl ApplicationFee { - /// Returns a list of application fees you’ve previously collected. - /// - /// The application fees are returned in sorted order, with the most recent fees appearing first. - pub fn list( - client: &Client, - params: ListApplicationFees<'_>, - ) -> Response> { - client.get_query("/application_fees", ¶ms) - } - - /// Retrieves the details of an application fee that your account has collected. - /// - /// The same information is returned when refunding the application fee. - pub fn retrieve( - client: &Client, - id: &ApplicationFeeId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/application_fees/{}", id), &Expand { expand }) - } -} - -impl Object for ApplicationFee { - type Id = ApplicationFeeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "application_fee" - } -} - -/// The parameters for `ApplicationFee::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListApplicationFees<'a> { - /// Only return application fees for the charge specified by this charge ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListApplicationFees<'a> { - pub fn new() -> Self { - ListApplicationFees { - charge: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/balance.rs b/ft-stripe/src/resources/balance.rs deleted file mode 100644 index d37a959..0000000 --- a/ft-stripe/src/resources/balance.rs +++ /dev/null @@ -1,77 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::Object; -use crate::resources::Currency; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Balance". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Balance { - /// Funds that are available to be transferred or paid out, whether automatically by Stripe or explicitly via the [Transfers API](https://stripe.com/docs/api#transfers) or [Payouts API](https://stripe.com/docs/api#payouts). - /// - /// The available balance for each currency and payment type can be found in the `source_types` property. - pub available: Vec, - - /// Funds held due to negative balances on connected Custom accounts. - /// - /// The connect reserve balance for each currency and payment type can be found in the `source_types` property. - #[serde(skip_serializing_if = "Option::is_none")] - pub connect_reserved: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub issuing: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Funds that are not yet available in the balance, due to the 7-day rolling pay cycle. - /// - /// The pending balance for each currency, and for each payment type, can be found in the `source_types` property. - pub pending: Vec, -} - -impl Object for Balance { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "balance" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BalanceAmount { - /// Balance amount. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - #[serde(skip_serializing_if = "Option::is_none")] - pub source_types: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BalanceAmountBySourceType { - /// Amount for bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_account: Option, - - /// Amount for card. - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - /// Amount for FPX. - #[serde(skip_serializing_if = "Option::is_none")] - pub fpx: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BalanceDetail { - /// Funds that are available for use. - pub available: Vec, -} diff --git a/ft-stripe/src/resources/balance_transaction.rs b/ft-stripe/src/resources/balance_transaction.rs deleted file mode 100644 index f8407ab..0000000 --- a/ft-stripe/src/resources/balance_transaction.rs +++ /dev/null @@ -1,321 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{BalanceTransactionId, PayoutId, SourceId}; -use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; -use crate::resources::{ - ApplicationFee, ApplicationFeeRefund, BalanceTransactionStatus, Charge, - ConnectCollectionTransfer, Currency, Dispute, FeeType, IssuingAuthorization, - IssuingTransaction, Payout, PlatformTaxFee, Refund, ReserveTransaction, TaxDeductedAtSource, - Topup, Transfer, TransferReversal, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "BalanceTransaction". -/// -/// For more details see [https://stripe.com/docs/api/balance_transactions/object](https://stripe.com/docs/api/balance_transactions/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BalanceTransaction { - /// Unique identifier for the object. - pub id: BalanceTransactionId, - - /// Gross amount of the transaction, in %s. - pub amount: i64, - - /// The date the transaction's net funds will become available in the Stripe balance. - pub available_on: Timestamp, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The exchange rate used, if applicable, for this transaction. - /// - /// Specifically, if money was converted from currency A to currency B, then the `amount` in currency A, times `exchange_rate`, would be the `amount` in currency B. - /// For example, suppose you charged a customer 10.00 EUR. - /// Then the PaymentIntent's `amount` would be `1000` and `currency` would be `eur`. - /// Suppose this was converted into 12.34 USD in your Stripe account. - /// Then the BalanceTransaction's `amount` would be `1234`, `currency` would be `usd`, and `exchange_rate` would be `1.234`. - #[serde(skip_serializing_if = "Option::is_none")] - pub exchange_rate: Option, - - /// Fees (in %s) paid for this transaction. - pub fee: i64, - - /// Detailed breakdown of fees (in %s) paid for this transaction. - pub fee_details: Vec, - - /// Net amount of the transaction, in %s. - pub net: i64, - - /// [Learn more](https://stripe.com/docs/reports/reporting-categories) about how reporting categories can help you understand balance transactions from an accounting perspective. - pub reporting_category: String, - - /// The Stripe object to which this transaction is related. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option>, - - /// If the transaction's net funds are available in the Stripe balance yet. - /// - /// Either `available` or `pending`. - pub status: BalanceTransactionStatus, - - /// Transaction type: `adjustment`, `advance`, `advance_funding`, `application_fee`, `application_fee_refund`, `charge`, `connect_collection_transfer`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_transaction`, `payment`, `payment_failure_refund`, `payment_refund`, `payout`, `payout_cancel`, `payout_failure`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. - /// - /// [Learn more](https://stripe.com/docs/reports/balance-transaction-types) about balance transaction types and what they represent. - /// If you are looking to classify transactions for accounting purposes, you might want to consider `reporting_category` instead. - #[serde(rename = "type")] - pub type_: BalanceTransactionType, -} - -impl BalanceTransaction { - /// Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). - /// - /// The transactions are returned in sorted order, with the most recent transactions appearing first. Note that this endpoint was previously called “Balance history” and used the path `/v1/balance/history`. - pub fn list( - client: &Client, - params: ListBalanceTransactions<'_>, - ) -> Response> { - client.get_query("/balance_transactions", ¶ms) - } - - /// Retrieves the balance transaction with the given ID. - /// - /// Note that this endpoint previously used the path `/v1/balance/history/:id`. - pub fn retrieve( - client: &Client, - id: &BalanceTransactionId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/balance_transactions/{}", id), &Expand { expand }) - } -} - -impl Object for BalanceTransaction { - type Id = BalanceTransactionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "balance_transaction" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Fee { - /// Amount of the fee, in cents. - pub amount: i64, - - /// ID of the Connect application that earned the fee. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Type of the fee, one of: `application_fee`, `stripe_fee` or `tax`. - #[serde(rename = "type")] - pub type_: FeeType, -} - -/// The parameters for `BalanceTransaction::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListBalanceTransactions<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub available_on: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return transactions in a certain currency. - /// - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// For automatic Stripe payouts only, only returns transactions that were paid out on the specified payout ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub payout: Option, - - /// Only returns the original transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only returns transactions of the given type. - /// - /// One of: `charge`, `refund`, `adjustment`, `application_fee`, `application_fee_refund`, `transfer`, `payment`, `payout`, `payout_failure`, `stripe_fee`, or `network_cost`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option<&'a str>, -} - -impl<'a> ListBalanceTransactions<'a> { - pub fn new() -> Self { - ListBalanceTransactions { - available_on: Default::default(), - created: Default::default(), - currency: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - payout: Default::default(), - source: Default::default(), - starting_after: Default::default(), - type_: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum BalanceTransactionSource { - ApplicationFee(ApplicationFee), - Charge(Charge), - ConnectCollectionTransfer(ConnectCollectionTransfer), - Dispute(Dispute), - #[serde(rename = "fee_refund")] - ApplicationFeeRefund(ApplicationFeeRefund), - #[serde(rename = "issuing.authorization")] - IssuingAuthorization(IssuingAuthorization), - #[serde(rename = "issuing.transaction")] - IssuingTransaction(IssuingTransaction), - Payout(Payout), - PlatformTaxFee(PlatformTaxFee), - Refund(Refund), - ReserveTransaction(ReserveTransaction), - TaxDeductedAtSource(TaxDeductedAtSource), - Topup(Topup), - Transfer(Transfer), - TransferReversal(TransferReversal), -} - -/// An enum representing the possible values of an `BalanceTransaction`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum BalanceTransactionType { - Adjustment, - Advance, - AdvanceFunding, - ApplicationFee, - ApplicationFeeRefund, - Charge, - ConnectCollectionTransfer, - IssuingAuthorizationHold, - IssuingAuthorizationRelease, - IssuingTransaction, - Payment, - PaymentFailureRefund, - PaymentRefund, - Payout, - PayoutCancel, - PayoutFailure, - Refund, - RefundFailure, - ReserveTransaction, - ReservedFunds, - StripeFee, - StripeFxFee, - TaxFee, - Topup, - TopupReversal, - Transfer, - TransferCancel, - TransferFailure, - TransferRefund, -} - -impl BalanceTransactionType { - pub fn as_str(self) -> &'static str { - match self { - BalanceTransactionType::Adjustment => "adjustment", - BalanceTransactionType::Advance => "advance", - BalanceTransactionType::AdvanceFunding => "advance_funding", - BalanceTransactionType::ApplicationFee => "application_fee", - BalanceTransactionType::ApplicationFeeRefund => "application_fee_refund", - BalanceTransactionType::Charge => "charge", - BalanceTransactionType::ConnectCollectionTransfer => "connect_collection_transfer", - BalanceTransactionType::IssuingAuthorizationHold => "issuing_authorization_hold", - BalanceTransactionType::IssuingAuthorizationRelease => "issuing_authorization_release", - BalanceTransactionType::IssuingTransaction => "issuing_transaction", - BalanceTransactionType::Payment => "payment", - BalanceTransactionType::PaymentFailureRefund => "payment_failure_refund", - BalanceTransactionType::PaymentRefund => "payment_refund", - BalanceTransactionType::Payout => "payout", - BalanceTransactionType::PayoutCancel => "payout_cancel", - BalanceTransactionType::PayoutFailure => "payout_failure", - BalanceTransactionType::Refund => "refund", - BalanceTransactionType::RefundFailure => "refund_failure", - BalanceTransactionType::ReserveTransaction => "reserve_transaction", - BalanceTransactionType::ReservedFunds => "reserved_funds", - BalanceTransactionType::StripeFee => "stripe_fee", - BalanceTransactionType::StripeFxFee => "stripe_fx_fee", - BalanceTransactionType::TaxFee => "tax_fee", - BalanceTransactionType::Topup => "topup", - BalanceTransactionType::TopupReversal => "topup_reversal", - BalanceTransactionType::Transfer => "transfer", - BalanceTransactionType::TransferCancel => "transfer_cancel", - BalanceTransactionType::TransferFailure => "transfer_failure", - BalanceTransactionType::TransferRefund => "transfer_refund", - } - } -} - -impl AsRef for BalanceTransactionType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for BalanceTransactionType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/balance_transaction_ext.rs b/ft-stripe/src/resources/balance_transaction_ext.rs deleted file mode 100644 index 726918e..0000000 --- a/ft-stripe/src/resources/balance_transaction_ext.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::ids::BalanceTransactionSourceId; -use crate::params::Object; -use crate::resources::BalanceTransactionSource; -use serde::{Deserialize, Serialize}; - -impl Object for BalanceTransactionSource { - type Id = BalanceTransactionSourceId; - fn id(&self) -> Self::Id { - use BalanceTransactionSource as Source; - use BalanceTransactionSourceId as Id; - - match self { - Source::ApplicationFee(x) => Id::ApplicationFee(x.id()), - Source::ApplicationFeeRefund(x) => Id::ApplicationFeeRefund(x.id()), - Source::Charge(x) => Id::Charge(x.id()), - Source::ConnectCollectionTransfer(_) => Id::None, - Source::Dispute(x) => Id::Dispute(x.id()), - Source::IssuingAuthorization(x) => Id::IssuingAuthorization(x.id()), - Source::IssuingTransaction(x) => Id::IssuingTransaction(x.id()), - Source::PlatformTaxFee(_) => Id::None, - Source::Payout(x) => Id::Payout(x.id()), - Source::Refund(x) => Id::Refund(x.id()), - Source::ReserveTransaction(_) => Id::None, - Source::TaxDeductedAtSource(_) => Id::None, - Source::Topup(x) => Id::Topup(x.id()), - Source::Transfer(x) => Id::Transfer(x.id()), - Source::TransferReversal(x) => Id::TransferReversal(x.id()), - } - } - fn object(&self) -> &'static str { - use BalanceTransactionSource as Source; - - match self { - Source::ApplicationFee(x) => x.object(), - Source::ApplicationFeeRefund(x) => x.object(), - Source::Charge(x) => x.object(), - Source::ConnectCollectionTransfer(x) => x.object(), - Source::Dispute(x) => x.object(), - Source::IssuingAuthorization(x) => x.object(), - Source::IssuingTransaction(x) => x.object(), - Source::PlatformTaxFee(x) => x.object(), - Source::Payout(x) => x.object(), - Source::Refund(x) => x.object(), - Source::ReserveTransaction(x) => x.object(), - Source::TaxDeductedAtSource(x) => x.object(), - Source::Topup(x) => x.object(), - Source::Transfer(x) => x.object(), - Source::TransferReversal(x) => x.object(), - } - } -} - -/// An enum representing the possible values of an `BalanceTransaction`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum BalanceTransactionStatus { - Available, - Pending, -} - -impl BalanceTransactionStatus { - pub fn as_str(self) -> &'static str { - match self { - BalanceTransactionStatus::Available => "available", - BalanceTransactionStatus::Pending => "pending", - } - } -} - -impl AsRef for BalanceTransactionStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for BalanceTransactionStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Fee`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum FeeType { - ApplicationFee, - StripeFee, - Tax, -} - -impl FeeType { - pub fn as_str(self) -> &'static str { - match self { - FeeType::ApplicationFee => "application_fee", - FeeType::StripeFee => "stripe_fee", - FeeType::Tax => "tax", - } - } -} - -impl AsRef for FeeType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for FeeType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/bank_account.rs b/ft-stripe/src/resources/bank_account.rs deleted file mode 100644 index 422183b..0000000 --- a/ft-stripe/src/resources/bank_account.rs +++ /dev/null @@ -1,97 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::BankAccountId; -use crate::params::{Expandable, Metadata, Object}; -use crate::resources::{Account, AccountHolderType, BankAccountStatus, Currency, Customer}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "BankAccount". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BankAccount { - /// Unique identifier for the object. - pub id: BankAccountId, - - /// The ID of the account that the bank account is associated with. - #[serde(skip_serializing_if = "Option::is_none")] - pub account: Option>, - - /// The name of the person or business that owns the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_holder_name: Option, - - /// The type of entity that holds the account. - /// - /// This can be either `individual` or `company`. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_holder_type: Option, - - /// Name of the bank associated with the routing number (e.g., `WELLS FARGO`). - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - /// Two-letter ISO code representing the country the bank account is located in. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) paid out to the bank account. - pub currency: Currency, - - /// The ID of the customer that the bank account is associated with. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// Whether this bank account is the default external account for its currency. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_for_currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Uniquely identifies this particular bank account. - /// - /// You can use this attribute to check whether two bank accounts are the same. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// The last four digits of the bank account number. - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The routing transit number for the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub routing_number: Option, - - /// For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. - /// - /// A bank account that hasn't had any activity or validation performed is `new`. - /// If Stripe can determine that the bank account exists, its status will be `validated`. - /// Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. - /// If customer bank account verification has succeeded, the bank account status will be `verified`. - /// If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. - /// If a transfer sent to this bank account fails, we'll set the status to `errored` and will not continue to send transfers until the bank details are updated. For external accounts, possible values are `new` and `errored`. - /// Validations aren't run against external accounts because they're only used for payouts. - /// This means the other statuses don't apply. - /// If a transfer fails, the status is set to `errored` and transfers are stopped until account details are updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, -} - -impl Object for BankAccount { - type Id = BankAccountId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "bank_account" - } -} diff --git a/ft-stripe/src/resources/bank_account_ext.rs b/ft-stripe/src/resources/bank_account_ext.rs deleted file mode 100644 index 9b0afa4..0000000 --- a/ft-stripe/src/resources/bank_account_ext.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `BankAccount`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum BankAccountStatus { - Errored, - New, - Validated, - VerificationFailed, - Verified, -} - -impl BankAccountStatus { - pub fn as_str(self) -> &'static str { - match self { - BankAccountStatus::Errored => "errored", - BankAccountStatus::New => "new", - BankAccountStatus::Validated => "validated", - BankAccountStatus::VerificationFailed => "verification_failed", - BankAccountStatus::Verified => "verified", - } - } -} - -impl AsRef for BankAccountStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for BankAccountStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/card.rs b/ft-stripe/src/resources/card.rs deleted file mode 100644 index 7b98cc6..0000000 --- a/ft-stripe/src/resources/card.rs +++ /dev/null @@ -1,218 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::ids::CardId; -use crate::params::{Expandable, Metadata, Object}; -use crate::resources::{Account, Currency, Customer, Recipient}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Card". -/// -/// For more details see [https://stripe.com/docs/api/cards/object](https://stripe.com/docs/api/cards/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Card { - /// Unique identifier for the object. - pub id: CardId, - - /// The account this card belongs to. - /// - /// This attribute will not be in the card object if the card belongs to a customer or recipient instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub account: Option>, - - /// City/District/Suburb/Town/Village. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_city: Option, - - /// Billing address country, if provided when creating card. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_country: Option, - - /// Address line 1 (Street address/PO Box/Company name). - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line1: Option, - - /// If `address_line1` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line1_check: Option, - - /// Address line 2 (Apartment/Suite/Unit/Building). - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line2: Option, - - /// State/County/Province/Region. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_state: Option, - - /// ZIP or postal code. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_zip: Option, - - /// If `address_zip` was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_zip_check: Option, - - /// A set of available payout methods for this card. - /// - /// Will be either `["standard"]` or `["standard", "instant"]`. - /// Only values from this set should be passed as the `method` when creating a transfer. - #[serde(skip_serializing_if = "Option::is_none")] - pub available_payout_methods: Option>, - - /// Card brand. - /// - /// Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option, - - /// Two-letter ISO code representing the country of the card. - /// - /// You could use this attribute to get a sense of the international breakdown of cards you've collected. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The customer that this card belongs to. - /// - /// This attribute will not be in the card object if the card belongs to an account or recipient instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// If a CVC was provided, results of the check: `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc_check: Option, - - /// Whether this card is the default external account for its currency. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_for_currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// (For tokenized numbers only.) The last four digits of the device account number. - #[serde(skip_serializing_if = "Option::is_none")] - pub dynamic_last4: Option, - - /// Two-digit number representing the card's expiration month. - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_month: Option, - - /// Four-digit number representing the card's expiration year. - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_year: Option, - - /// Uniquely identifies this particular card number. - /// - /// You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Card funding type. - /// - /// Can be `credit`, `debit`, `prepaid`, or `unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub funding: Option, - - /// The last four digits of the card. - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// Cardholder name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// The recipient that this card belongs to. - /// - /// This attribute will not be in the card object if the card belongs to a customer or account instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub recipient: Option>, - - /// If the card number is tokenized, this is the method that was used. - /// - /// Can be `apple_pay` or `google_pay`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tokenization_method: Option, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -pub enum CheckResult { - #[serde(rename = "pass")] - Pass, - #[serde(rename = "fail")] - Failed, - #[serde(rename = "unavailable")] - Unavailable, - #[serde(rename = "unchecked")] - Unchecked, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -pub enum CardBrand { - #[serde(rename = "American Express")] - AmericanExpress, - #[serde(rename = "Diners Club")] - DinersClub, - #[serde(rename = "Discover")] - Discover, - #[serde(rename = "JCB")] - JCB, - #[serde(rename = "Visa")] - Visa, - #[serde(rename = "MasterCard")] - MasterCard, - #[serde(rename = "UnionPay")] - UnionPay, - - /// An unknown card brand. - /// - /// May also be a variant not yet supported by the library. - #[serde(other)] - #[serde(rename = "Unknown")] - Unknown, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -pub enum CardType { - #[serde(rename = "credit")] - Credit, - #[serde(rename = "debit")] - Debit, - #[serde(rename = "prepaid")] - Prepaid, - - /// An unknown card type. - /// - /// May also be a variant not yet supported by the library. - #[serde(other)] - #[serde(rename = "unknown")] - Unknown, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TokenizationMethod { - ApplePay, - AndroidPay, - - /// A variant not yet supported by the library. - /// It is an error to send `Other` as part of a request. - #[serde(other, skip_serializing)] - Other, -} - -impl Object for Card { - type Id = CardId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "card" - } -} diff --git a/ft-stripe/src/resources/charge.rs b/ft-stripe/src/resources/charge.rs deleted file mode 100644 index b622bfa..0000000 --- a/ft-stripe/src/resources/charge.rs +++ /dev/null @@ -1,627 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ChargeId, CustomerId, PaymentIntentId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Account, Application, ApplicationFee, BalanceTransaction, BillingDetails, ChargeSourceParams, - Currency, Customer, FraudDetailsReport, Invoice, Order, PaymentIntent, PaymentMethodDetails, - PaymentSource, Refund, Review, Shipping, Transfer, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Charge". -/// -/// For more details see [https://stripe.com/docs/api/charges/object](https://stripe.com/docs/api/charges/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Charge { - /// Unique identifier for the object. - pub id: ChargeId, - - /// Amount intended to be collected by this payment. - /// - /// A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). - /// The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). - /// The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). - pub amount: i64, - - /// Amount in %s refunded (can be less than the amount attribute on the charge if a partial refund was issued). - pub amount_refunded: i64, - - /// ID of the Connect application that created the charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option>, - - /// The application fee (if any) for the charge. - /// - /// [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee: Option>, - - /// The amount of the application fee (if any) for the charge. - /// - /// [See the Connect documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - - /// ID of the balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes). - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - pub billing_details: BillingDetails, - - /// The full statement descriptor that is passed to card networks, and that is displayed on your customers' credit card and bank statements. - /// - /// Allows you to see what the statement descriptor looks like after the static and dynamic portions are combined. - #[serde(skip_serializing_if = "Option::is_none")] - pub calculated_statement_descriptor: Option, - - /// If the charge was created without capturing, this Boolean represents whether it is still uncaptured or has since been captured. - pub captured: bool, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// ID of the customer this charge is for if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Whether the charge has been disputed. - pub disputed: bool, - - /// Error code explaining reason for charge failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_code: Option, - - /// Message to user further explaining reason for charge failure if available. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_message: Option, - - /// Information on fraud assessments for the charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub fraud_details: Option, - - /// ID of the invoice this charge is for if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The account (if any) the charge was made on behalf of without triggering an automatic transfer. - /// - /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option>, - - /// ID of the order this charge is for if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub order: Option>, - - /// Details about whether the payment was accepted, and why. - /// - /// See [understanding declines](https://stripe.com/docs/declines) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub outcome: Option, - - /// `true` if the charge succeeded, or was successfully authorized for later capture. - pub paid: bool, - - /// ID of the PaymentIntent associated with this charge, if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// ID of the payment method used in this charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// Details about the payment method at the time of the transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_details: Option, - - /// This is the email address that the receipt for this charge was sent to. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option, - - /// This is the transaction number that appears on email receipts sent for this charge. - /// - /// This attribute will be `null` until a receipt has been sent. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_number: Option, - - /// This is the URL to view the receipt for this charge. - /// - /// The receipt is kept up-to-date to the latest state of the charge, including any refunds. - /// If the charge is for an Invoice, the receipt will be stylized as an Invoice receipt. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_url: Option, - - /// Whether the charge has been fully refunded. - /// - /// If the charge is only partially refunded, this attribute will still be false. - pub refunded: bool, - - /// A list of refunds that have been applied to the charge. - pub refunds: List, - - /// ID of the review associated with this charge if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub review: Option>, - - /// Shipping information for the charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// Source information for the charge. - pub source: Option, - - /// The transfer ID which created this charge. - /// - /// Only present if the charge came from another Stripe account. - /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_transfer: Option>, - - /// For card charges, use `statement_descriptor_suffix` instead. - /// - /// Otherwise, you can use this value as the complete description of a charge on your customers’ statements. - /// Must contain at least one letter, maximum 22 characters. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// Provides information about the charge that customers see on their statements. - /// - /// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. - /// Maximum 22 characters for the concatenated descriptor. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_suffix: Option, - - /// The status of the payment is either `succeeded`, `pending`, or `failed`. - pub status: String, - - /// ID of the transfer to the `destination` account (only applicable if the charge was created using the `destination` parameter). - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer: Option>, - - /// An optional dictionary including the account to automatically transfer to as part of a destination charge. - /// - /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_data: Option, - - /// A string that identifies this transaction as part of a group. - /// - /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option, -} - -impl Charge { - /// Returns a list of charges you’ve previously created. - /// - /// The charges are returned in sorted order, with the most recent charges appearing first. - pub fn list(client: &Client, params: ListCharges<'_>) -> Response> { - client.get_query("/charges", ¶ms) - } - - /// To charge a credit card or other payment source, you create a `Charge` object. - /// - /// If your API key is in test mode, the supplied payment source (e.g., card) won’t actually be charged, although everything else will occur as if in live mode. - /// (Stripe assumes that the charge would have completed successfully). - pub fn create(client: &Client, params: CreateCharge<'_>) -> Response { - client.post_form("/charges", ¶ms) - } - - /// Retrieves the details of a charge that has previously been created. - /// - /// Supply the unique charge ID that was returned from your previous request, and Stripe will return the corresponding charge information. - /// The same information is returned when creating or refunding the charge. - pub fn retrieve(client: &Client, id: &ChargeId, expand: &[&str]) -> Response { - client.get_query(&format!("/charges/{}", id), &Expand { expand }) - } - - /// Updates the specified charge by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. - pub fn update(client: &Client, id: &ChargeId, params: UpdateCharge<'_>) -> Response { - client.post_form(&format!("/charges/{}", id), ¶ms) - } -} - -impl Object for Charge { - type Id = ChargeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "charge" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct FraudDetails { - /// Assessments from Stripe. - /// - /// If set, the value is `fraudulent`. - #[serde(skip_serializing_if = "Option::is_none")] - pub stripe_report: Option, - - /// Assessments reported by you. - /// - /// If set, possible values of are `safe` and `fraudulent`. - #[serde(skip_serializing_if = "Option::is_none")] - pub user_report: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ChargeOutcome { - /// Possible values are `approved_by_network`, `declined_by_network`, `not_sent_to_network`, and `reversed_after_approval`. - /// - /// The value `reversed_after_approval` indicates the payment was [blocked by Stripe](https://stripe.com/docs/declines#blocked-payments) after bank authorization, and may temporarily appear as "pending" on a cardholder's statement. - #[serde(skip_serializing_if = "Option::is_none")] - pub network_status: Option, - - /// An enumerated value providing a more detailed explanation of the outcome's `type`. - /// - /// Charges blocked by Radar's default block rule have the value `highest_risk_level`. - /// Charges placed in review by Radar's default review rule have the value `elevated_risk_level`. - /// Charges authorized, blocked, or placed in review by custom rules have the value `rule`. - /// See [understanding declines](https://stripe.com/docs/declines) for more details. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - - /// Stripe's evaluation of the riskiness of the payment. - /// - /// Possible values for evaluated payments are `normal`, `elevated`, `highest`. - /// For non-card payments, and card-based payments predating the public assignment of risk levels, this field will have the value `not_assessed`. - /// In the event of an error in the evaluation, this field will have the value `unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub risk_level: Option, - - /// Stripe's evaluation of the riskiness of the payment. - /// - /// Possible values for evaluated payments are between 0 and 100. - /// For non-card payments, card-based payments predating the public assignment of risk scores, or in the event of an error during evaluation, this field will not be present. - /// This field is only available with Radar for Fraud Teams. - #[serde(skip_serializing_if = "Option::is_none")] - pub risk_score: Option, - - /// The ID of the Radar rule that matched the payment, if applicable. - #[serde(skip_serializing_if = "Option::is_none")] - pub rule: Option>, - - /// A human-readable description of the outcome type and reason, designed for you (the recipient of the payment), not your customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub seller_message: Option, - - /// Possible values are `authorized`, `manual_review`, `issuer_declined`, `blocked`, and `invalid`. - /// - /// See [understanding declines](https://stripe.com/docs/declines) and [Radar reviews](https://stripe.com/docs/radar/reviews) for details. - #[serde(rename = "type")] - pub type_: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferData { - /// The amount transferred to the destination account, if specified. - /// - /// By default, the entire charge amount is transferred to the destination account. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// ID of an existing, connected Stripe account to transfer funds to if `transfer_data` was specified in the charge request. - pub destination: Expandable, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Rule { - /// The action taken on the payment. - pub action: String, - - /// Unique identifier for the object. - pub id: String, - - /// The predicate to evaluate the payment against. - pub predicate: String, -} - -/// The parameters for `Charge::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateCharge<'a> { - /// Amount intended to be collected by this payment. - /// - /// A positive integer representing how much to charge in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal) (e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal currency). - /// The minimum amount is $0.50 US or [equivalent in charge currency](https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts). - /// The amount value supports up to eight digits (e.g., a value of 99999999 for a USD charge of $999,999.99). - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee: Option, - - /// A fee in %s that will be applied to the charge and transferred to the application owner's Stripe account. - /// - /// The request must be made with an OAuth key or the `Stripe-Account` header in order to take an application fee. - /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/direct-charges#collecting-fees). - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - - /// Whether to immediately capture the charge. - /// - /// Defaults to `true`. - /// When `false`, the charge issues an authorization (or pre-authorization), and will need to be [captured](https://stripe.com/docs/api#capture_charge) later. - /// Uncaptured charges expire in _seven days_. - /// For more information, see the [authorizing charges and settling later](https://stripe.com/docs/charges/placing-a-hold) documentation. - #[serde(skip_serializing_if = "Option::is_none")] - pub capture: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The ID of an existing customer that will be charged in this request. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// An arbitrary string which you can attach to a `Charge` object. - /// - /// It is displayed when in the web interface alongside the charge. - /// Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The Stripe account ID for which these funds are intended. - /// - /// Automatically set if you use the `destination` parameter. - /// For details, see [Creating Separate Charges and Transfers](https://stripe.com/docs/connect/charges-transfers#on-behalf-of). - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option<&'a str>, - - /// The email address to which this charge's [receipt](https://stripe.com/docs/dashboard/receipts) will be sent. - /// - /// The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. - /// If this charge is for a [Customer](https://stripe.com/docs/api/customers/object), the email address specified here will override the customer's email address. - /// If `receipt_email` is specified for a charge in live mode, a receipt will be sent regardless of your [email settings](https://dashboard.stripe.com/account/emails). - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - - /// Shipping information for the charge. - /// - /// Helps prevent fraud on charges for physical goods. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// A payment source to be charged. - /// - /// This can be the ID of a [card](https://stripe.com/docs/api#cards) (i.e., credit or debit card), a [bank account](https://stripe.com/docs/api#bank_accounts), a [source](https://stripe.com/docs/api#sources), a [token](https://stripe.com/docs/api#tokens), or a [connected account](https://stripe.com/docs/connect/account-debits#charging-a-connected-account). - /// For certain sources---namely, [cards](https://stripe.com/docs/api#cards), [bank accounts](https://stripe.com/docs/api#bank_accounts), and attached [sources](https://stripe.com/docs/api#sources)---you must also pass the ID of the associated customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - - /// For card charges, use `statement_descriptor_suffix` instead. - /// - /// Otherwise, you can use this value as the complete description of a charge on your customers’ statements. - /// Must contain at least one letter, maximum 22 characters. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - - /// Provides information about the charge that customers see on their statements. - /// - /// Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. - /// Maximum 22 characters for the concatenated descriptor. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor_suffix: Option<&'a str>, - - /// An optional dictionary including the account to automatically transfer to as part of a destination charge. - /// - /// [See the Connect documentation](https://stripe.com/docs/connect/destination-charges) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_data: Option, - - /// A string that identifies this transaction as part of a group. - /// - /// For details, see [Grouping transactions](https://stripe.com/docs/connect/charges-transfers#transfer-options). - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> CreateCharge<'a> { - pub fn new() -> Self { - CreateCharge { - amount: Default::default(), - application_fee: Default::default(), - application_fee_amount: Default::default(), - capture: Default::default(), - currency: Default::default(), - customer: Default::default(), - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - on_behalf_of: Default::default(), - receipt_email: Default::default(), - shipping: Default::default(), - source: Default::default(), - statement_descriptor: Default::default(), - statement_descriptor_suffix: Default::default(), - transfer_data: Default::default(), - transfer_group: Default::default(), - } - } -} - -/// The parameters for `Charge::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListCharges<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return charges for the customer specified by this customer ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return charges that were created by the PaymentIntent specified by this PaymentIntent ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return charges for this transfer group. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> ListCharges<'a> { - pub fn new() -> Self { - ListCharges { - created: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - payment_intent: Default::default(), - starting_after: Default::default(), - transfer_group: Default::default(), - } - } -} - -/// The parameters for `Charge::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateCharge<'a> { - /// The ID of an existing customer that will be associated with this request. - /// - /// This field may only be updated if there is no existing associated customer with this charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// An arbitrary string which you can attach to a charge object. - /// - /// It is displayed when in the web interface alongside the charge. - /// Note that if you use Stripe to send automatic email receipts to your customers, your receipt emails will include the `description` of the charge(s) that they are describing. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A set of key-value pairs you can attach to a charge giving information about its riskiness. - /// - /// If you believe a charge is fraudulent, include a `user_report` key with a value of `fraudulent`. - /// If you believe a charge is safe, include a `user_report` key with a value of `safe`. - /// Stripe will use the information you send to improve our fraud detection algorithms. - #[serde(skip_serializing_if = "Option::is_none")] - pub fraud_details: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// This is the email address that the receipt for this charge will be sent to. - /// - /// If this field is updated, then a new email receipt will be sent to the updated address. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - - /// Shipping information for the charge. - /// - /// Helps prevent fraud on charges for physical goods. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// A string that identifies this transaction as part of a group. - /// - /// `transfer_group` may only be provided if it has not been set. - /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> UpdateCharge<'a> { - pub fn new() -> Self { - UpdateCharge { - customer: Default::default(), - description: Default::default(), - expand: Default::default(), - fraud_details: Default::default(), - metadata: Default::default(), - receipt_email: Default::default(), - shipping: Default::default(), - transfer_group: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct FraudDetailsParams { - pub user_report: FraudDetailsReport, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferDataParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - pub destination: String, -} diff --git a/ft-stripe/src/resources/charge_ext.rs b/ft-stripe/src/resources/charge_ext.rs deleted file mode 100644 index 1e06ac1..0000000 --- a/ft-stripe/src/resources/charge_ext.rs +++ /dev/null @@ -1,56 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{BankAccountId, CardId, ChargeId, SourceId, TokenId}; -use crate::params::Object; -use crate::resources::{Charge, Rule}; -use serde::{Deserialize, Serialize}; - -/// The set of PaymentSource parameters that can be used to create a charge. -/// -/// For more details see [https://stripe.com/docs/api/charges/create#create_charge-source](https://stripe.com/docs/api/charges/create#create_charge-source). -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(untagged)] -pub enum ChargeSourceParams { - Token(TokenId), - Source(SourceId), - Card(CardId), - BankAccount(BankAccountId), -} - -/// The set of parameters that can be used when capturing a charge object. -/// -/// For more details see [https://stripe.com/docs/api#charge_capture](https://stripe.com/docs/api#charge_capture). -#[derive(Clone, Debug, Default, Deserialize, Serialize)] -pub struct CaptureCharge<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, -} - -impl Charge { - /// Capture captures a previously created charge with capture set to false. - /// - /// For more details see [https://stripe.com/docs/api#charge_capture](https://stripe.com/docs/api#charge_capture). - pub fn capture( - client: &Client, - charge_id: &ChargeId, - params: CaptureCharge<'_>, - ) -> Response { - client.post_form(&format!("/charges/{}/capture", charge_id), params) - } -} - -impl Object for Rule { - type Id = String; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "" - } -} diff --git a/ft-stripe/src/resources/checkout_session.rs b/ft-stripe/src/resources/checkout_session.rs deleted file mode 100644 index 01598b0..0000000 --- a/ft-stripe/src/resources/checkout_session.rs +++ /dev/null @@ -1,1043 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::CheckoutSessionId; -use crate::params::{Expandable, List, Metadata, Object}; -use crate::resources::{ - CheckoutSessionItem, Currency, Customer, PaymentIntent, Plan, SetupIntent, Shipping, Sku, - Subscription, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Session". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CheckoutSession { - /// Unique identifier for the object. - /// - /// Used to pass to `redirectToCheckout` in Stripe.js. - pub id: CheckoutSessionId, - - /// The value (`auto` or `required`) for whether Checkout collected the - /// customer's billing address. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_address_collection: Option, - - /// The URL the customer will be directed to if they decide to cancel payment and return to your website. - pub cancel_url: String, - - /// A unique string to reference the Checkout Session. - /// - /// This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_reference_id: Option, - - /// The ID of the customer for this session. - /// For Checkout Sessions in `payment` or `subscription` mode, Checkout - /// will create a new customer object based on information provided - /// during the session unless an existing customer was provided when - /// the session was created. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// If provided, this value will be used when the Customer object is created. - /// If not provided, customers will be asked to enter their email address. - /// Use this parameter to prefill customer data if you already have an email - /// on file. - /// - /// To access information about the customer once a session is complete, use the `customer` field. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_email: Option, - - /// The line items, plans, or SKUs purchased by the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub display_items: Option>, - - /// The line items purchased by the customer. - /// - /// [Expand](https://stripe.com/docs/api/expanding_objects) this field to include it in the response. - #[serde(default)] - pub line_items: List, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// The IETF language tag of the locale Checkout is displayed in. - /// - /// If blank or `auto`, the browser's locale is used. - #[serde(skip_serializing_if = "Option::is_none")] - pub locale: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The mode of the Checkout Session, one of `payment`, `setup`, or `subscription`. - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - - /// The ID of the PaymentIntent for Checkout Sessions in `payment` mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// A list of the types of payment methods (e.g. - /// - /// card) this Checkout Session is allowed to accept. - pub payment_method_types: Vec, - - /// The ID of the SetupIntent for Checkout Sessions in `setup` mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub setup_intent: Option>, - - /// Shipping information for this Checkout Session. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// When set, provides configuration for Checkout to collect a shipping address from a customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_address_collection: Option, - - /// Describes the type of transaction being performed by Checkout in order to customize - /// relevant text on the page, such as the submit button. - /// - /// `submit_type` can only be specified on Checkout Sessions in `payment` mode, but not Checkout Sessions in `subscription` or `setup` mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub submit_type: Option, - - /// The ID of the subscription for Checkout Sessions in `subscription` mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option>, - - /// The URL the customer will be directed to after the payment or - /// subscription creation is successful. - pub success_url: String, -} - -impl Object for CheckoutSession { - type Id = CheckoutSessionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "checkout.session" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CheckoutSessionDisplayItem { - /// Amount for the display item. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub custom: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// Quantity of the display item being purchased. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub sku: Option, - - /// The type of display item. - /// - /// One of `custom`, `plan` or `sku`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CheckoutSessionCustomDisplayItemDescription { - /// The description of the line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The images of the line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub images: Option>, - - /// The name of the line item. - pub name: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ShippingAddressCollection { - /// An array of two-letter ISO country codes representing which countries Checkout should provide as options for - /// shipping locations. - /// - /// Unsupported country codes: `AS, CX, CC, CU, HM, IR, KP, MH, FM, NF, MP, PW, SD, SY, UM, VI`. - pub allowed_countries: Vec, -} - -/// An enum representing the possible values of an `CheckoutSession`'s `locale` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CheckoutSessionLocale { - Auto, - Da, - De, - En, - Es, - Fi, - Fr, - It, - Ja, - Ms, - Nb, - Nl, - Pl, - Pt, - #[serde(rename = "pt-BR")] - PtBr, - Sv, - Zh, -} - -impl CheckoutSessionLocale { - pub fn as_str(self) -> &'static str { - match self { - CheckoutSessionLocale::Auto => "auto", - CheckoutSessionLocale::Da => "da", - CheckoutSessionLocale::De => "de", - CheckoutSessionLocale::En => "en", - CheckoutSessionLocale::Es => "es", - CheckoutSessionLocale::Fi => "fi", - CheckoutSessionLocale::Fr => "fr", - CheckoutSessionLocale::It => "it", - CheckoutSessionLocale::Ja => "ja", - CheckoutSessionLocale::Ms => "ms", - CheckoutSessionLocale::Nb => "nb", - CheckoutSessionLocale::Nl => "nl", - CheckoutSessionLocale::Pl => "pl", - CheckoutSessionLocale::Pt => "pt", - CheckoutSessionLocale::PtBr => "pt-BR", - CheckoutSessionLocale::Sv => "sv", - CheckoutSessionLocale::Zh => "zh", - } - } -} - -impl AsRef for CheckoutSessionLocale { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CheckoutSessionLocale { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CheckoutSession`'s `mode` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CheckoutSessionMode { - Payment, - Setup, - Subscription, -} - -impl CheckoutSessionMode { - pub fn as_str(self) -> &'static str { - match self { - CheckoutSessionMode::Payment => "payment", - CheckoutSessionMode::Setup => "setup", - CheckoutSessionMode::Subscription => "subscription", - } - } -} - -impl AsRef for CheckoutSessionMode { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CheckoutSessionMode { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CheckoutSession`'s `submit_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CheckoutSessionSubmitType { - Auto, - Book, - Donate, - Pay, -} - -impl CheckoutSessionSubmitType { - pub fn as_str(self) -> &'static str { - match self { - CheckoutSessionSubmitType::Auto => "auto", - CheckoutSessionSubmitType::Book => "book", - CheckoutSessionSubmitType::Donate => "donate", - CheckoutSessionSubmitType::Pay => "pay", - } - } -} - -impl AsRef for CheckoutSessionSubmitType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CheckoutSessionSubmitType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ShippingAddressCollection`'s `allowed_countries` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ShippingAddressCollectionAllowedCountries { - #[serde(rename = "AC")] - Ac, - #[serde(rename = "AD")] - Ad, - #[serde(rename = "AE")] - Ae, - #[serde(rename = "AF")] - Af, - #[serde(rename = "AG")] - Ag, - #[serde(rename = "AI")] - Ai, - #[serde(rename = "AL")] - Al, - #[serde(rename = "AM")] - Am, - #[serde(rename = "AO")] - Ao, - #[serde(rename = "AQ")] - Aq, - #[serde(rename = "AR")] - Ar, - #[serde(rename = "AT")] - At, - #[serde(rename = "AU")] - Au, - #[serde(rename = "AW")] - Aw, - #[serde(rename = "AX")] - Ax, - #[serde(rename = "AZ")] - Az, - #[serde(rename = "BA")] - Ba, - #[serde(rename = "BB")] - Bb, - #[serde(rename = "BD")] - Bd, - #[serde(rename = "BE")] - Be, - #[serde(rename = "BF")] - Bf, - #[serde(rename = "BG")] - Bg, - #[serde(rename = "BH")] - Bh, - #[serde(rename = "BI")] - Bi, - #[serde(rename = "BJ")] - Bj, - #[serde(rename = "BL")] - Bl, - #[serde(rename = "BM")] - Bm, - #[serde(rename = "BN")] - Bn, - #[serde(rename = "BO")] - Bo, - #[serde(rename = "BQ")] - Bq, - #[serde(rename = "BR")] - Br, - #[serde(rename = "BS")] - Bs, - #[serde(rename = "BT")] - Bt, - #[serde(rename = "BV")] - Bv, - #[serde(rename = "BW")] - Bw, - #[serde(rename = "BY")] - By, - #[serde(rename = "BZ")] - Bz, - #[serde(rename = "CA")] - Ca, - #[serde(rename = "CD")] - Cd, - #[serde(rename = "CF")] - Cf, - #[serde(rename = "CG")] - Cg, - #[serde(rename = "CH")] - Ch, - #[serde(rename = "CI")] - Ci, - #[serde(rename = "CK")] - Ck, - #[serde(rename = "CL")] - Cl, - #[serde(rename = "CM")] - Cm, - #[serde(rename = "CN")] - Cn, - #[serde(rename = "CO")] - Co, - #[serde(rename = "CR")] - Cr, - #[serde(rename = "CV")] - Cv, - #[serde(rename = "CW")] - Cw, - #[serde(rename = "CY")] - Cy, - #[serde(rename = "CZ")] - Cz, - #[serde(rename = "DE")] - De, - #[serde(rename = "DJ")] - Dj, - #[serde(rename = "DK")] - Dk, - #[serde(rename = "DM")] - Dm, - #[serde(rename = "DO")] - Do, - #[serde(rename = "DZ")] - Dz, - #[serde(rename = "EC")] - Ec, - #[serde(rename = "EE")] - Ee, - #[serde(rename = "EG")] - Eg, - #[serde(rename = "EH")] - Eh, - #[serde(rename = "ER")] - Er, - #[serde(rename = "ES")] - Es, - #[serde(rename = "ET")] - Et, - #[serde(rename = "FI")] - Fi, - #[serde(rename = "FJ")] - Fj, - #[serde(rename = "FK")] - Fk, - #[serde(rename = "FO")] - Fo, - #[serde(rename = "FR")] - Fr, - #[serde(rename = "GA")] - Ga, - #[serde(rename = "GB")] - Gb, - #[serde(rename = "GD")] - Gd, - #[serde(rename = "GE")] - Ge, - #[serde(rename = "GF")] - Gf, - #[serde(rename = "GG")] - Gg, - #[serde(rename = "GH")] - Gh, - #[serde(rename = "GI")] - Gi, - #[serde(rename = "GL")] - Gl, - #[serde(rename = "GM")] - Gm, - #[serde(rename = "GN")] - Gn, - #[serde(rename = "GP")] - Gp, - #[serde(rename = "GQ")] - Gq, - #[serde(rename = "GR")] - Gr, - #[serde(rename = "GS")] - Gs, - #[serde(rename = "GT")] - Gt, - #[serde(rename = "GU")] - Gu, - #[serde(rename = "GW")] - Gw, - #[serde(rename = "GY")] - Gy, - #[serde(rename = "HK")] - Hk, - #[serde(rename = "HN")] - Hn, - #[serde(rename = "HR")] - Hr, - #[serde(rename = "HT")] - Ht, - #[serde(rename = "HU")] - Hu, - #[serde(rename = "ID")] - Id, - #[serde(rename = "IE")] - Ie, - #[serde(rename = "IL")] - Il, - #[serde(rename = "IM")] - Im, - #[serde(rename = "IN")] - In, - #[serde(rename = "IO")] - Io, - #[serde(rename = "IQ")] - Iq, - #[serde(rename = "IS")] - Is, - #[serde(rename = "IT")] - It, - #[serde(rename = "JE")] - Je, - #[serde(rename = "JM")] - Jm, - #[serde(rename = "JO")] - Jo, - #[serde(rename = "JP")] - Jp, - #[serde(rename = "KE")] - Ke, - #[serde(rename = "KG")] - Kg, - #[serde(rename = "KH")] - Kh, - #[serde(rename = "KI")] - Ki, - #[serde(rename = "KM")] - Km, - #[serde(rename = "KN")] - Kn, - #[serde(rename = "KR")] - Kr, - #[serde(rename = "KW")] - Kw, - #[serde(rename = "KY")] - Ky, - #[serde(rename = "KZ")] - Kz, - #[serde(rename = "LA")] - La, - #[serde(rename = "LB")] - Lb, - #[serde(rename = "LC")] - Lc, - #[serde(rename = "LI")] - Li, - #[serde(rename = "LK")] - Lk, - #[serde(rename = "LR")] - Lr, - #[serde(rename = "LS")] - Ls, - #[serde(rename = "LT")] - Lt, - #[serde(rename = "LU")] - Lu, - #[serde(rename = "LV")] - Lv, - #[serde(rename = "LY")] - Ly, - #[serde(rename = "MA")] - Ma, - #[serde(rename = "MC")] - Mc, - #[serde(rename = "MD")] - Md, - #[serde(rename = "ME")] - Me, - #[serde(rename = "MF")] - Mf, - #[serde(rename = "MG")] - Mg, - #[serde(rename = "MK")] - Mk, - #[serde(rename = "ML")] - Ml, - #[serde(rename = "MM")] - Mm, - #[serde(rename = "MN")] - Mn, - #[serde(rename = "MO")] - Mo, - #[serde(rename = "MQ")] - Mq, - #[serde(rename = "MR")] - Mr, - #[serde(rename = "MS")] - Ms, - #[serde(rename = "MT")] - Mt, - #[serde(rename = "MU")] - Mu, - #[serde(rename = "MV")] - Mv, - #[serde(rename = "MW")] - Mw, - #[serde(rename = "MX")] - Mx, - #[serde(rename = "MY")] - My, - #[serde(rename = "MZ")] - Mz, - #[serde(rename = "NA")] - Na, - #[serde(rename = "NC")] - Nc, - #[serde(rename = "NE")] - Ne, - #[serde(rename = "NG")] - Ng, - #[serde(rename = "NI")] - Ni, - #[serde(rename = "NL")] - Nl, - #[serde(rename = "NO")] - No, - #[serde(rename = "NP")] - Np, - #[serde(rename = "NR")] - Nr, - #[serde(rename = "NU")] - Nu, - #[serde(rename = "NZ")] - Nz, - #[serde(rename = "OM")] - Om, - #[serde(rename = "PA")] - Pa, - #[serde(rename = "PE")] - Pe, - #[serde(rename = "PF")] - Pf, - #[serde(rename = "PG")] - Pg, - #[serde(rename = "PH")] - Ph, - #[serde(rename = "PK")] - Pk, - #[serde(rename = "PL")] - Pl, - #[serde(rename = "PM")] - Pm, - #[serde(rename = "PN")] - Pn, - #[serde(rename = "PR")] - Pr, - #[serde(rename = "PS")] - Ps, - #[serde(rename = "PT")] - Pt, - #[serde(rename = "PY")] - Py, - #[serde(rename = "QA")] - Qa, - #[serde(rename = "RE")] - Re, - #[serde(rename = "RO")] - Ro, - #[serde(rename = "RS")] - Rs, - #[serde(rename = "RU")] - Ru, - #[serde(rename = "RW")] - Rw, - #[serde(rename = "SA")] - Sa, - #[serde(rename = "SB")] - Sb, - #[serde(rename = "SC")] - Sc, - #[serde(rename = "SE")] - Se, - #[serde(rename = "SG")] - Sg, - #[serde(rename = "SH")] - Sh, - #[serde(rename = "SI")] - Si, - #[serde(rename = "SJ")] - Sj, - #[serde(rename = "SK")] - Sk, - #[serde(rename = "SL")] - Sl, - #[serde(rename = "SM")] - Sm, - #[serde(rename = "SN")] - Sn, - #[serde(rename = "SO")] - So, - #[serde(rename = "SR")] - Sr, - #[serde(rename = "SS")] - Ss, - #[serde(rename = "ST")] - St, - #[serde(rename = "SV")] - Sv, - #[serde(rename = "SX")] - Sx, - #[serde(rename = "SZ")] - Sz, - #[serde(rename = "TA")] - Ta, - #[serde(rename = "TC")] - Tc, - #[serde(rename = "TD")] - Td, - #[serde(rename = "TF")] - Tf, - #[serde(rename = "TG")] - Tg, - #[serde(rename = "TH")] - Th, - #[serde(rename = "TJ")] - Tj, - #[serde(rename = "TK")] - Tk, - #[serde(rename = "TL")] - Tl, - #[serde(rename = "TM")] - Tm, - #[serde(rename = "TN")] - Tn, - #[serde(rename = "TO")] - To, - #[serde(rename = "TR")] - Tr, - #[serde(rename = "TT")] - Tt, - #[serde(rename = "TV")] - Tv, - #[serde(rename = "TW")] - Tw, - #[serde(rename = "TZ")] - Tz, - #[serde(rename = "UA")] - Ua, - #[serde(rename = "UG")] - Ug, - #[serde(rename = "US")] - Us, - #[serde(rename = "UY")] - Uy, - #[serde(rename = "UZ")] - Uz, - #[serde(rename = "VA")] - Va, - #[serde(rename = "VC")] - Vc, - #[serde(rename = "VE")] - Ve, - #[serde(rename = "VG")] - Vg, - #[serde(rename = "VN")] - Vn, - #[serde(rename = "VU")] - Vu, - #[serde(rename = "WF")] - Wf, - #[serde(rename = "WS")] - Ws, - #[serde(rename = "XK")] - Xk, - #[serde(rename = "YE")] - Ye, - #[serde(rename = "YT")] - Yt, - #[serde(rename = "ZA")] - Za, - #[serde(rename = "ZM")] - Zm, - #[serde(rename = "ZW")] - Zw, - #[serde(rename = "ZZ")] - Zz, -} - -impl ShippingAddressCollectionAllowedCountries { - pub fn as_str(self) -> &'static str { - match self { - ShippingAddressCollectionAllowedCountries::Ac => "AC", - ShippingAddressCollectionAllowedCountries::Ad => "AD", - ShippingAddressCollectionAllowedCountries::Ae => "AE", - ShippingAddressCollectionAllowedCountries::Af => "AF", - ShippingAddressCollectionAllowedCountries::Ag => "AG", - ShippingAddressCollectionAllowedCountries::Ai => "AI", - ShippingAddressCollectionAllowedCountries::Al => "AL", - ShippingAddressCollectionAllowedCountries::Am => "AM", - ShippingAddressCollectionAllowedCountries::Ao => "AO", - ShippingAddressCollectionAllowedCountries::Aq => "AQ", - ShippingAddressCollectionAllowedCountries::Ar => "AR", - ShippingAddressCollectionAllowedCountries::At => "AT", - ShippingAddressCollectionAllowedCountries::Au => "AU", - ShippingAddressCollectionAllowedCountries::Aw => "AW", - ShippingAddressCollectionAllowedCountries::Ax => "AX", - ShippingAddressCollectionAllowedCountries::Az => "AZ", - ShippingAddressCollectionAllowedCountries::Ba => "BA", - ShippingAddressCollectionAllowedCountries::Bb => "BB", - ShippingAddressCollectionAllowedCountries::Bd => "BD", - ShippingAddressCollectionAllowedCountries::Be => "BE", - ShippingAddressCollectionAllowedCountries::Bf => "BF", - ShippingAddressCollectionAllowedCountries::Bg => "BG", - ShippingAddressCollectionAllowedCountries::Bh => "BH", - ShippingAddressCollectionAllowedCountries::Bi => "BI", - ShippingAddressCollectionAllowedCountries::Bj => "BJ", - ShippingAddressCollectionAllowedCountries::Bl => "BL", - ShippingAddressCollectionAllowedCountries::Bm => "BM", - ShippingAddressCollectionAllowedCountries::Bn => "BN", - ShippingAddressCollectionAllowedCountries::Bo => "BO", - ShippingAddressCollectionAllowedCountries::Bq => "BQ", - ShippingAddressCollectionAllowedCountries::Br => "BR", - ShippingAddressCollectionAllowedCountries::Bs => "BS", - ShippingAddressCollectionAllowedCountries::Bt => "BT", - ShippingAddressCollectionAllowedCountries::Bv => "BV", - ShippingAddressCollectionAllowedCountries::Bw => "BW", - ShippingAddressCollectionAllowedCountries::By => "BY", - ShippingAddressCollectionAllowedCountries::Bz => "BZ", - ShippingAddressCollectionAllowedCountries::Ca => "CA", - ShippingAddressCollectionAllowedCountries::Cd => "CD", - ShippingAddressCollectionAllowedCountries::Cf => "CF", - ShippingAddressCollectionAllowedCountries::Cg => "CG", - ShippingAddressCollectionAllowedCountries::Ch => "CH", - ShippingAddressCollectionAllowedCountries::Ci => "CI", - ShippingAddressCollectionAllowedCountries::Ck => "CK", - ShippingAddressCollectionAllowedCountries::Cl => "CL", - ShippingAddressCollectionAllowedCountries::Cm => "CM", - ShippingAddressCollectionAllowedCountries::Cn => "CN", - ShippingAddressCollectionAllowedCountries::Co => "CO", - ShippingAddressCollectionAllowedCountries::Cr => "CR", - ShippingAddressCollectionAllowedCountries::Cv => "CV", - ShippingAddressCollectionAllowedCountries::Cw => "CW", - ShippingAddressCollectionAllowedCountries::Cy => "CY", - ShippingAddressCollectionAllowedCountries::Cz => "CZ", - ShippingAddressCollectionAllowedCountries::De => "DE", - ShippingAddressCollectionAllowedCountries::Dj => "DJ", - ShippingAddressCollectionAllowedCountries::Dk => "DK", - ShippingAddressCollectionAllowedCountries::Dm => "DM", - ShippingAddressCollectionAllowedCountries::Do => "DO", - ShippingAddressCollectionAllowedCountries::Dz => "DZ", - ShippingAddressCollectionAllowedCountries::Ec => "EC", - ShippingAddressCollectionAllowedCountries::Ee => "EE", - ShippingAddressCollectionAllowedCountries::Eg => "EG", - ShippingAddressCollectionAllowedCountries::Eh => "EH", - ShippingAddressCollectionAllowedCountries::Er => "ER", - ShippingAddressCollectionAllowedCountries::Es => "ES", - ShippingAddressCollectionAllowedCountries::Et => "ET", - ShippingAddressCollectionAllowedCountries::Fi => "FI", - ShippingAddressCollectionAllowedCountries::Fj => "FJ", - ShippingAddressCollectionAllowedCountries::Fk => "FK", - ShippingAddressCollectionAllowedCountries::Fo => "FO", - ShippingAddressCollectionAllowedCountries::Fr => "FR", - ShippingAddressCollectionAllowedCountries::Ga => "GA", - ShippingAddressCollectionAllowedCountries::Gb => "GB", - ShippingAddressCollectionAllowedCountries::Gd => "GD", - ShippingAddressCollectionAllowedCountries::Ge => "GE", - ShippingAddressCollectionAllowedCountries::Gf => "GF", - ShippingAddressCollectionAllowedCountries::Gg => "GG", - ShippingAddressCollectionAllowedCountries::Gh => "GH", - ShippingAddressCollectionAllowedCountries::Gi => "GI", - ShippingAddressCollectionAllowedCountries::Gl => "GL", - ShippingAddressCollectionAllowedCountries::Gm => "GM", - ShippingAddressCollectionAllowedCountries::Gn => "GN", - ShippingAddressCollectionAllowedCountries::Gp => "GP", - ShippingAddressCollectionAllowedCountries::Gq => "GQ", - ShippingAddressCollectionAllowedCountries::Gr => "GR", - ShippingAddressCollectionAllowedCountries::Gs => "GS", - ShippingAddressCollectionAllowedCountries::Gt => "GT", - ShippingAddressCollectionAllowedCountries::Gu => "GU", - ShippingAddressCollectionAllowedCountries::Gw => "GW", - ShippingAddressCollectionAllowedCountries::Gy => "GY", - ShippingAddressCollectionAllowedCountries::Hk => "HK", - ShippingAddressCollectionAllowedCountries::Hn => "HN", - ShippingAddressCollectionAllowedCountries::Hr => "HR", - ShippingAddressCollectionAllowedCountries::Ht => "HT", - ShippingAddressCollectionAllowedCountries::Hu => "HU", - ShippingAddressCollectionAllowedCountries::Id => "ID", - ShippingAddressCollectionAllowedCountries::Ie => "IE", - ShippingAddressCollectionAllowedCountries::Il => "IL", - ShippingAddressCollectionAllowedCountries::Im => "IM", - ShippingAddressCollectionAllowedCountries::In => "IN", - ShippingAddressCollectionAllowedCountries::Io => "IO", - ShippingAddressCollectionAllowedCountries::Iq => "IQ", - ShippingAddressCollectionAllowedCountries::Is => "IS", - ShippingAddressCollectionAllowedCountries::It => "IT", - ShippingAddressCollectionAllowedCountries::Je => "JE", - ShippingAddressCollectionAllowedCountries::Jm => "JM", - ShippingAddressCollectionAllowedCountries::Jo => "JO", - ShippingAddressCollectionAllowedCountries::Jp => "JP", - ShippingAddressCollectionAllowedCountries::Ke => "KE", - ShippingAddressCollectionAllowedCountries::Kg => "KG", - ShippingAddressCollectionAllowedCountries::Kh => "KH", - ShippingAddressCollectionAllowedCountries::Ki => "KI", - ShippingAddressCollectionAllowedCountries::Km => "KM", - ShippingAddressCollectionAllowedCountries::Kn => "KN", - ShippingAddressCollectionAllowedCountries::Kr => "KR", - ShippingAddressCollectionAllowedCountries::Kw => "KW", - ShippingAddressCollectionAllowedCountries::Ky => "KY", - ShippingAddressCollectionAllowedCountries::Kz => "KZ", - ShippingAddressCollectionAllowedCountries::La => "LA", - ShippingAddressCollectionAllowedCountries::Lb => "LB", - ShippingAddressCollectionAllowedCountries::Lc => "LC", - ShippingAddressCollectionAllowedCountries::Li => "LI", - ShippingAddressCollectionAllowedCountries::Lk => "LK", - ShippingAddressCollectionAllowedCountries::Lr => "LR", - ShippingAddressCollectionAllowedCountries::Ls => "LS", - ShippingAddressCollectionAllowedCountries::Lt => "LT", - ShippingAddressCollectionAllowedCountries::Lu => "LU", - ShippingAddressCollectionAllowedCountries::Lv => "LV", - ShippingAddressCollectionAllowedCountries::Ly => "LY", - ShippingAddressCollectionAllowedCountries::Ma => "MA", - ShippingAddressCollectionAllowedCountries::Mc => "MC", - ShippingAddressCollectionAllowedCountries::Md => "MD", - ShippingAddressCollectionAllowedCountries::Me => "ME", - ShippingAddressCollectionAllowedCountries::Mf => "MF", - ShippingAddressCollectionAllowedCountries::Mg => "MG", - ShippingAddressCollectionAllowedCountries::Mk => "MK", - ShippingAddressCollectionAllowedCountries::Ml => "ML", - ShippingAddressCollectionAllowedCountries::Mm => "MM", - ShippingAddressCollectionAllowedCountries::Mn => "MN", - ShippingAddressCollectionAllowedCountries::Mo => "MO", - ShippingAddressCollectionAllowedCountries::Mq => "MQ", - ShippingAddressCollectionAllowedCountries::Mr => "MR", - ShippingAddressCollectionAllowedCountries::Ms => "MS", - ShippingAddressCollectionAllowedCountries::Mt => "MT", - ShippingAddressCollectionAllowedCountries::Mu => "MU", - ShippingAddressCollectionAllowedCountries::Mv => "MV", - ShippingAddressCollectionAllowedCountries::Mw => "MW", - ShippingAddressCollectionAllowedCountries::Mx => "MX", - ShippingAddressCollectionAllowedCountries::My => "MY", - ShippingAddressCollectionAllowedCountries::Mz => "MZ", - ShippingAddressCollectionAllowedCountries::Na => "NA", - ShippingAddressCollectionAllowedCountries::Nc => "NC", - ShippingAddressCollectionAllowedCountries::Ne => "NE", - ShippingAddressCollectionAllowedCountries::Ng => "NG", - ShippingAddressCollectionAllowedCountries::Ni => "NI", - ShippingAddressCollectionAllowedCountries::Nl => "NL", - ShippingAddressCollectionAllowedCountries::No => "NO", - ShippingAddressCollectionAllowedCountries::Np => "NP", - ShippingAddressCollectionAllowedCountries::Nr => "NR", - ShippingAddressCollectionAllowedCountries::Nu => "NU", - ShippingAddressCollectionAllowedCountries::Nz => "NZ", - ShippingAddressCollectionAllowedCountries::Om => "OM", - ShippingAddressCollectionAllowedCountries::Pa => "PA", - ShippingAddressCollectionAllowedCountries::Pe => "PE", - ShippingAddressCollectionAllowedCountries::Pf => "PF", - ShippingAddressCollectionAllowedCountries::Pg => "PG", - ShippingAddressCollectionAllowedCountries::Ph => "PH", - ShippingAddressCollectionAllowedCountries::Pk => "PK", - ShippingAddressCollectionAllowedCountries::Pl => "PL", - ShippingAddressCollectionAllowedCountries::Pm => "PM", - ShippingAddressCollectionAllowedCountries::Pn => "PN", - ShippingAddressCollectionAllowedCountries::Pr => "PR", - ShippingAddressCollectionAllowedCountries::Ps => "PS", - ShippingAddressCollectionAllowedCountries::Pt => "PT", - ShippingAddressCollectionAllowedCountries::Py => "PY", - ShippingAddressCollectionAllowedCountries::Qa => "QA", - ShippingAddressCollectionAllowedCountries::Re => "RE", - ShippingAddressCollectionAllowedCountries::Ro => "RO", - ShippingAddressCollectionAllowedCountries::Rs => "RS", - ShippingAddressCollectionAllowedCountries::Ru => "RU", - ShippingAddressCollectionAllowedCountries::Rw => "RW", - ShippingAddressCollectionAllowedCountries::Sa => "SA", - ShippingAddressCollectionAllowedCountries::Sb => "SB", - ShippingAddressCollectionAllowedCountries::Sc => "SC", - ShippingAddressCollectionAllowedCountries::Se => "SE", - ShippingAddressCollectionAllowedCountries::Sg => "SG", - ShippingAddressCollectionAllowedCountries::Sh => "SH", - ShippingAddressCollectionAllowedCountries::Si => "SI", - ShippingAddressCollectionAllowedCountries::Sj => "SJ", - ShippingAddressCollectionAllowedCountries::Sk => "SK", - ShippingAddressCollectionAllowedCountries::Sl => "SL", - ShippingAddressCollectionAllowedCountries::Sm => "SM", - ShippingAddressCollectionAllowedCountries::Sn => "SN", - ShippingAddressCollectionAllowedCountries::So => "SO", - ShippingAddressCollectionAllowedCountries::Sr => "SR", - ShippingAddressCollectionAllowedCountries::Ss => "SS", - ShippingAddressCollectionAllowedCountries::St => "ST", - ShippingAddressCollectionAllowedCountries::Sv => "SV", - ShippingAddressCollectionAllowedCountries::Sx => "SX", - ShippingAddressCollectionAllowedCountries::Sz => "SZ", - ShippingAddressCollectionAllowedCountries::Ta => "TA", - ShippingAddressCollectionAllowedCountries::Tc => "TC", - ShippingAddressCollectionAllowedCountries::Td => "TD", - ShippingAddressCollectionAllowedCountries::Tf => "TF", - ShippingAddressCollectionAllowedCountries::Tg => "TG", - ShippingAddressCollectionAllowedCountries::Th => "TH", - ShippingAddressCollectionAllowedCountries::Tj => "TJ", - ShippingAddressCollectionAllowedCountries::Tk => "TK", - ShippingAddressCollectionAllowedCountries::Tl => "TL", - ShippingAddressCollectionAllowedCountries::Tm => "TM", - ShippingAddressCollectionAllowedCountries::Tn => "TN", - ShippingAddressCollectionAllowedCountries::To => "TO", - ShippingAddressCollectionAllowedCountries::Tr => "TR", - ShippingAddressCollectionAllowedCountries::Tt => "TT", - ShippingAddressCollectionAllowedCountries::Tv => "TV", - ShippingAddressCollectionAllowedCountries::Tw => "TW", - ShippingAddressCollectionAllowedCountries::Tz => "TZ", - ShippingAddressCollectionAllowedCountries::Ua => "UA", - ShippingAddressCollectionAllowedCountries::Ug => "UG", - ShippingAddressCollectionAllowedCountries::Us => "US", - ShippingAddressCollectionAllowedCountries::Uy => "UY", - ShippingAddressCollectionAllowedCountries::Uz => "UZ", - ShippingAddressCollectionAllowedCountries::Va => "VA", - ShippingAddressCollectionAllowedCountries::Vc => "VC", - ShippingAddressCollectionAllowedCountries::Ve => "VE", - ShippingAddressCollectionAllowedCountries::Vg => "VG", - ShippingAddressCollectionAllowedCountries::Vn => "VN", - ShippingAddressCollectionAllowedCountries::Vu => "VU", - ShippingAddressCollectionAllowedCountries::Wf => "WF", - ShippingAddressCollectionAllowedCountries::Ws => "WS", - ShippingAddressCollectionAllowedCountries::Xk => "XK", - ShippingAddressCollectionAllowedCountries::Ye => "YE", - ShippingAddressCollectionAllowedCountries::Yt => "YT", - ShippingAddressCollectionAllowedCountries::Za => "ZA", - ShippingAddressCollectionAllowedCountries::Zm => "ZM", - ShippingAddressCollectionAllowedCountries::Zw => "ZW", - ShippingAddressCollectionAllowedCountries::Zz => "ZZ", - } - } -} - -impl AsRef for ShippingAddressCollectionAllowedCountries { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ShippingAddressCollectionAllowedCountries { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/connect_collection_transfer.rs b/ft-stripe/src/resources/connect_collection_transfer.rs deleted file mode 100644 index e9b1494..0000000 --- a/ft-stripe/src/resources/connect_collection_transfer.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::{Expandable, Object}; -use crate::resources::{Account, Currency}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "ConnectCollectionTransfer". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ConnectCollectionTransfer { - /// Amount transferred, in %s. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// ID of the account that funds are being collected for. - pub destination: Expandable, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, -} - -impl Object for ConnectCollectionTransfer { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "connect_collection_transfer" - } -} diff --git a/ft-stripe/src/resources/coupon.rs b/ft-stripe/src/resources/coupon.rs deleted file mode 100644 index 2606d21..0000000 --- a/ft-stripe/src/resources/coupon.rs +++ /dev/null @@ -1,319 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::CouponId; -use crate::params::{Deleted, Expand, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::Currency; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Coupon". -/// -/// For more details see [https://stripe.com/docs/api/coupons/object](https://stripe.com/docs/api/coupons/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Coupon { - /// Unique identifier for the object. - pub id: CouponId, - - /// Amount (in the `currency` specified) that will be taken off the subtotal of any invoices for this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_off: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// If `amount_off` has been set, the three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the amount to take off. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// One of `forever`, `once`, and `repeating`. - /// - /// Describes how long a customer who applies this coupon will get the discount. - #[serde(skip_serializing_if = "Option::is_none")] - pub duration: Option, - - /// If `duration` is `repeating`, the number of months the coupon applies. - /// - /// Null if coupon `duration` is `forever` or `once`. - #[serde(skip_serializing_if = "Option::is_none")] - pub duration_in_months: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Maximum number of times this coupon can be redeemed, in total, across all customers, before it is no longer valid. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_redemptions: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// Name of the coupon displayed to customers on for instance invoices or receipts. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon. - /// - /// For example, a coupon with percent_off of 50 will make a %s100 invoice %s50 instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub percent_off: Option, - - /// Date after which the coupon can no longer be redeemed. - #[serde(skip_serializing_if = "Option::is_none")] - pub redeem_by: Option, - - /// Number of times this coupon has been applied to a customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub times_redeemed: Option, - - /// Taking account of the above properties, whether this coupon can still be applied to a customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub valid: Option, -} - -impl Coupon { - /// Returns a list of your coupons. - pub fn list(client: &Client, params: ListCoupons<'_>) -> Response> { - client.get_query("/coupons", ¶ms) - } - - /// You can create coupons easily via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. - /// - /// Coupon creation is also accessible via the API if you need to create coupons on the fly. A coupon has either a `percent_off` or an `amount_off` and `currency`. - /// If you set an `amount_off`, that amount will be subtracted from any invoice’s subtotal. - /// For example, an invoice with a subtotal of $100 will have a final total of $0 if a coupon with an `amount_off` of 20000 is applied to it and an invoice with a subtotal of $300 will have a final total of $100 if a coupon with an `amount_off` of 20000 is applied to it. - pub fn create(client: &Client, params: CreateCoupon<'_>) -> Response { - client.post_form("/coupons", ¶ms) - } - - /// Retrieves the coupon with the given ID. - pub fn retrieve(client: &Client, id: &CouponId, expand: &[&str]) -> Response { - client.get_query(&format!("/coupons/{}", id), &Expand { expand }) - } - - /// Updates the metadata of a coupon. - /// - /// Other coupon details (currency, duration, amount_off) are, by design, not editable. - pub fn update(client: &Client, id: &CouponId, params: UpdateCoupon<'_>) -> Response { - client.post_form(&format!("/coupons/{}", id), ¶ms) - } - - /// You can delete coupons via the [coupon management](https://dashboard.stripe.com/coupons) page of the Stripe dashboard. - /// - /// However, deleting a coupon does not affect any customers who have already applied the coupon; it means that new customers can’t redeem the coupon. - /// You can also delete coupons via the API. - pub fn delete(client: &Client, id: &CouponId) -> Response> { - client.delete(&format!("/coupons/{}", id)) - } -} - -impl Object for Coupon { - type Id = CouponId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "coupon" - } -} - -/// The parameters for `Coupon::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateCoupon<'a> { - /// A positive integer representing the amount to subtract from an invoice total (required if `percent_off` is not passed). - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_off: Option, - - /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) of the `amount_off` parameter (required if `amount_off` is passed). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// Specifies how long the discount will be in effect. - /// - /// Can be `forever`, `once`, or `repeating`. - pub duration: CouponDuration, - - /// Required only if `duration` is `repeating`, in which case it must be a positive integer that specifies the number of months the discount will be in effect. - #[serde(skip_serializing_if = "Option::is_none")] - pub duration_in_months: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Unique string of your choice that will be used to identify this coupon when applying it to a customer. - /// - /// If you don't want to specify a particular code, you can leave the ID blank and we'll generate a random code for you. - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option<&'a str>, - - /// A positive integer specifying the number of times the coupon can be redeemed before it's no longer valid. - /// - /// For example, you might have a 50% off coupon that the first 20 readers of your blog can use. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_redemptions: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Name of the coupon displayed to customers on, for instance invoices, or receipts. - /// - /// By default the `id` is shown if `name` is not set. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, - - /// A positive float larger than 0, and smaller or equal to 100, that represents the discount the coupon will apply (required if `amount_off` is not passed). - #[serde(skip_serializing_if = "Option::is_none")] - pub percent_off: Option, - - /// Unix timestamp specifying the last time at which the coupon can be redeemed. - /// - /// After the redeem_by date, the coupon can no longer be applied to new customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub redeem_by: Option, -} - -impl<'a> CreateCoupon<'a> { - pub fn new(duration: CouponDuration) -> Self { - CreateCoupon { - amount_off: Default::default(), - currency: Default::default(), - duration, - duration_in_months: Default::default(), - expand: Default::default(), - id: Default::default(), - max_redemptions: Default::default(), - metadata: Default::default(), - name: Default::default(), - percent_off: Default::default(), - redeem_by: Default::default(), - } - } -} - -/// The parameters for `Coupon::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListCoupons<'a> { - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListCoupons<'a> { - pub fn new() -> Self { - ListCoupons { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Coupon::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateCoupon<'a> { - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Name of the coupon displayed to customers on, for instance invoices, or receipts. - /// - /// By default the `id` is shown if `name` is not set. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, -} - -impl<'a> UpdateCoupon<'a> { - pub fn new() -> Self { - UpdateCoupon { - expand: Default::default(), - metadata: Default::default(), - name: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Coupon`'s `duration` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CouponDuration { - Forever, - Once, - Repeating, -} - -impl CouponDuration { - pub fn as_str(self) -> &'static str { - match self { - CouponDuration::Forever => "forever", - CouponDuration::Once => "once", - CouponDuration::Repeating => "repeating", - } - } -} - -impl AsRef for CouponDuration { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CouponDuration { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/currency.rs b/ft-stripe/src/resources/currency.rs deleted file mode 100644 index 48b76d3..0000000 --- a/ft-stripe/src/resources/currency.rs +++ /dev/null @@ -1,464 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::params::to_snakecase; -use serde::{Deserialize, Serialize}; - -/// Currency is the list of supported currencies. -/// -/// For more details see https://support.stripe.com/questions/which-currencies-does-stripe-support. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] -pub enum Currency { - #[serde(rename = "aed")] - AED, // United Arab Emirates Dirham - #[serde(rename = "afn")] - AFN, // Afghan Afghani - #[serde(rename = "all")] - ALL, // Albanian Lek - #[serde(rename = "amd")] - AMD, // Armenian Dram - #[serde(rename = "ang")] - ANG, // Netherlands Antillean Gulden - #[serde(rename = "aoa")] - AOA, // Angolan Kwanza - #[serde(rename = "ars")] - ARS, // Argentine Peso - #[serde(rename = "aud")] - AUD, // Australian Dollar - #[serde(rename = "awg")] - AWG, // Aruban Florin - #[serde(rename = "azn")] - AZN, // Azerbaijani Manat - #[serde(rename = "bam")] - BAM, // Bosnia & Herzegovina Convertible Mark - #[serde(rename = "bbd")] - BBD, // Barbadian Dollar - #[serde(rename = "bdt")] - BDT, // Bangladeshi Taka - #[serde(rename = "bgn")] - BGN, // Bulgarian Lev - #[serde(rename = "bif")] - BIF, // Burundian Franc - #[serde(rename = "bmd")] - BMD, // Bermudian Dollar - #[serde(rename = "bnd")] - BND, // Brunei Dollar - #[serde(rename = "bob")] - BOB, // Bolivian Boliviano - #[serde(rename = "brl")] - BRL, // Brazilian Real - #[serde(rename = "bsd")] - BSD, // Bahamian Dollar - #[serde(rename = "bwp")] - BWP, // Botswana Pula - #[serde(rename = "bzd")] - BZD, // Belize Dollar - #[serde(rename = "cad")] - CAD, // Canadian Dollar - #[serde(rename = "cdf")] - CDF, // Congolese Franc - #[serde(rename = "chf")] - CHF, // Swiss Franc - #[serde(rename = "clp")] - CLP, // Chilean Peso - #[serde(rename = "cny")] - CNY, // Chinese Renminbi Yuan - #[serde(rename = "cop")] - COP, // Colombian Peso - #[serde(rename = "crc")] - CRC, // Costa Rican Colón - #[serde(rename = "cve")] - CVE, // Cape Verdean Escudo - #[serde(rename = "czk")] - CZK, // Czech Koruna - #[serde(rename = "djf")] - DJF, // Djiboutian Franc - #[serde(rename = "dkk")] - DKK, // Danish Krone - #[serde(rename = "dop")] - DOP, // Dominican Peso - #[serde(rename = "dzd")] - DZD, // Algerian Dinar - #[serde(rename = "eek")] - EEK, // Estonian Kroon - #[serde(rename = "egp")] - EGP, // Egyptian Pound - #[serde(rename = "etb")] - ETB, // Ethiopian Birr - #[serde(rename = "eur")] - EUR, // Euro - #[serde(rename = "fjd")] - FJD, // Fijian Dollar - #[serde(rename = "fkp")] - FKP, // Falkland Islands Pound - #[serde(rename = "gbp")] - GBP, // British Pound - #[serde(rename = "gel")] - GEL, // Georgian Lari - #[serde(rename = "gip")] - GIP, // Gibraltar Pound - #[serde(rename = "gmd")] - GMD, // Gambian Dalasi - #[serde(rename = "gnf")] - GNF, // Guinean Franc - #[serde(rename = "gtq")] - GTQ, // Guatemalan Quetzal - #[serde(rename = "gyd")] - GYD, // Guyanese Dollar - #[serde(rename = "hkd")] - HKD, // Hong Kong Dollar - #[serde(rename = "hnl")] - HNL, // Honduran Lempira - #[serde(rename = "hrk")] - HRK, // Croatian Kuna - #[serde(rename = "htg")] - HTG, // Haitian Gourde - #[serde(rename = "huf")] - HUF, // Hungarian Forint - #[serde(rename = "idr")] - IDR, // Indonesian Rupiah - #[serde(rename = "ils")] - ILS, // Israeli New Sheqel - #[serde(rename = "inr")] - INR, // Indian Rupee - #[serde(rename = "isk")] - ISK, // Icelandic Króna - #[serde(rename = "jmd")] - JMD, // Jamaican Dollar - #[serde(rename = "jpy")] - JPY, // Japanese Yen - #[serde(rename = "kes")] - KES, // Kenyan Shilling - #[serde(rename = "kgs")] - KGS, // Kyrgyzstani Som - #[serde(rename = "khr")] - KHR, // Cambodian Riel - #[serde(rename = "kmf")] - KMF, // Comorian Franc - #[serde(rename = "krw")] - KRW, // South Korean Won - #[serde(rename = "kyd")] - KYD, // Cayman Islands Dollar - #[serde(rename = "kzt")] - KZT, // Kazakhstani Tenge - #[serde(rename = "lak")] - LAK, // Lao Kip - #[serde(rename = "lbp")] - LBP, // Lebanese Pound - #[serde(rename = "lkr")] - LKR, // Sri Lankan Rupee - #[serde(rename = "lrd")] - LRD, // Liberian Dollar - #[serde(rename = "lsl")] - LSL, // Lesotho Loti - #[serde(rename = "ltl")] - LTL, // Lithuanian Litas - #[serde(rename = "lvl")] - LVL, // Latvian Lats - #[serde(rename = "mad")] - MAD, // Moroccan Dirham - #[serde(rename = "mdl")] - MDL, // Moldovan Leu - #[serde(rename = "mga")] - MGA, // Malagasy Ariary - #[serde(rename = "mkd")] - MKD, // Macedonian Denar - #[serde(rename = "mnt")] - MNT, // Mongolian Tögrög - #[serde(rename = "mop")] - MOP, // Macanese Pataca - #[serde(rename = "mro")] - MRO, // Mauritanian Ouguiya - #[serde(rename = "mur")] - MUR, // Mauritian Rupee - #[serde(rename = "mvr")] - MVR, // Maldivian Rufiyaa - #[serde(rename = "mwk")] - MWK, // Malawian Kwacha - #[serde(rename = "mxn")] - MXN, // Mexican Peso - #[serde(rename = "myr")] - MYR, // Malaysian Ringgit - #[serde(rename = "mzn")] - MZN, // Mozambican Metical - #[serde(rename = "nad")] - NAD, // Namibian Dollar - #[serde(rename = "ngn")] - NGN, // Nigerian Naira - #[serde(rename = "nio")] - NIO, // Nicaraguan Córdoba - #[serde(rename = "nok")] - NOK, // Norwegian Krone - #[serde(rename = "npr")] - NPR, // Nepalese Rupee - #[serde(rename = "nzd")] - NZD, // New Zealand Dollar - #[serde(rename = "pab")] - PAB, // Panamanian Balboa - #[serde(rename = "pen")] - PEN, // Peruvian Nuevo Sol - #[serde(rename = "pgk")] - PGK, // Papua New Guinean Kina - #[serde(rename = "php")] - PHP, // Philippine Peso - #[serde(rename = "pkr")] - PKR, // Pakistani Rupee - #[serde(rename = "pln")] - PLN, // Polish Złoty - #[serde(rename = "pyg")] - PYG, // Paraguayan Guaraní - #[serde(rename = "qar")] - QAR, // Qatari Riyal - #[serde(rename = "ron")] - RON, // Romanian Leu - #[serde(rename = "rsd")] - RSD, // Serbian Dinar - #[serde(rename = "rub")] - RUB, // Russian Ruble - #[serde(rename = "rwf")] - RWF, // Rwandan Franc - #[serde(rename = "sar")] - SAR, // Saudi Riyal - #[serde(rename = "sbd")] - SBD, // Solomon Islands Dollar - #[serde(rename = "scr")] - SCR, // Seychellois Rupee - #[serde(rename = "sek")] - SEK, // Swedish Krona - #[serde(rename = "sgd")] - SGD, // Singapore Dollar - #[serde(rename = "shp")] - SHP, // Saint Helenian Pound - #[serde(rename = "sll")] - SLL, // Sierra Leonean Leone - #[serde(rename = "sos")] - SOS, // Somali Shilling - #[serde(rename = "srd")] - SRD, // Surinamese Dollar - #[serde(rename = "std")] - STD, // São Tomé and Príncipe Dobra - #[serde(rename = "svc")] - SVC, // Salvadoran Colón - #[serde(rename = "szl")] - SZL, // Swazi Lilangeni - #[serde(rename = "thb")] - THB, // Thai Baht - #[serde(rename = "tjs")] - TJS, // Tajikistani Somoni - #[serde(rename = "top")] - TOP, // Tongan Paʻanga - #[serde(rename = "try")] - TRY, // Turkish Lira - #[serde(rename = "ttd")] - TTD, // Trinidad and Tobago Dollar - #[serde(rename = "twd")] - TWD, // New Taiwan Dollar - #[serde(rename = "tzs")] - TZS, // Tanzanian Shilling - #[serde(rename = "uah")] - UAH, // Ukrainian Hryvnia - #[serde(rename = "ugx")] - UGX, // Ugandan Shilling - #[serde(rename = "usd")] - USD, // United States Dollar - #[serde(rename = "uyu")] - UYU, // Uruguayan Peso - #[serde(rename = "uzs")] - UZS, // Uzbekistani Som - #[serde(rename = "vef")] - VEF, // Venezuelan Bolívar - #[serde(rename = "vnd")] - VND, // Vietnamese Đồng - #[serde(rename = "vuv")] - VUV, // Vanuatu Vatu - #[serde(rename = "wst")] - WST, // Samoan Tala - #[serde(rename = "xaf")] - XAF, // Central African Cfa Franc - #[serde(rename = "xcd")] - XCD, // East Caribbean Dollar - #[serde(rename = "xof")] - XOF, // West African Cfa Franc - #[serde(rename = "xpf")] - XPF, // Cfp Franc - #[serde(rename = "yer")] - YER, // Yemeni Rial - #[serde(rename = "zar")] - ZAR, // South African Rand - #[serde(rename = "zmw")] - ZMW, // Zambian Kwacha -} - -impl Default for Currency { - fn default() -> Self { - Currency::USD - } -} - -impl std::fmt::Display for Currency { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", to_snakecase(&format!("{:?}", self))) - } -} - -impl std::str::FromStr for Currency { - type Err = ParseCurrencyError; - fn from_str(s: &str) -> Result { - match s { - "aed" => Ok(Currency::AED), - "afn" => Ok(Currency::AFN), - "all" => Ok(Currency::ALL), - "amd" => Ok(Currency::AMD), - "ang" => Ok(Currency::ANG), - "aoa" => Ok(Currency::AOA), - "ars" => Ok(Currency::ARS), - "aud" => Ok(Currency::AUD), - "awg" => Ok(Currency::AWG), - "azn" => Ok(Currency::AZN), - "bam" => Ok(Currency::BAM), - "bbd" => Ok(Currency::BBD), - "bdt" => Ok(Currency::BDT), - "bgn" => Ok(Currency::BGN), - "bif" => Ok(Currency::BIF), - "bmd" => Ok(Currency::BMD), - "bnd" => Ok(Currency::BND), - "bob" => Ok(Currency::BOB), - "brl" => Ok(Currency::BRL), - "bsd" => Ok(Currency::BSD), - "bwp" => Ok(Currency::BWP), - "bzd" => Ok(Currency::BZD), - "cad" => Ok(Currency::CAD), - "cdf" => Ok(Currency::CDF), - "chf" => Ok(Currency::CHF), - "clp" => Ok(Currency::CLP), - "cny" => Ok(Currency::CNY), - "cop" => Ok(Currency::COP), - "crc" => Ok(Currency::CRC), - "cve" => Ok(Currency::CVE), - "czk" => Ok(Currency::CZK), - "djf" => Ok(Currency::DJF), - "dkk" => Ok(Currency::DKK), - "dop" => Ok(Currency::DOP), - "dzd" => Ok(Currency::DZD), - "eek" => Ok(Currency::EEK), - "egp" => Ok(Currency::EGP), - "etb" => Ok(Currency::ETB), - "eur" => Ok(Currency::EUR), - "fjd" => Ok(Currency::FJD), - "fkp" => Ok(Currency::FKP), - "gbp" => Ok(Currency::GBP), - "gel" => Ok(Currency::GEL), - "gip" => Ok(Currency::GIP), - "gmd" => Ok(Currency::GMD), - "gnf" => Ok(Currency::GNF), - "gtq" => Ok(Currency::GTQ), - "gyd" => Ok(Currency::GYD), - "hkd" => Ok(Currency::HKD), - "hnl" => Ok(Currency::HNL), - "hrk" => Ok(Currency::HRK), - "htg" => Ok(Currency::HTG), - "huf" => Ok(Currency::HUF), - "idr" => Ok(Currency::IDR), - "ils" => Ok(Currency::ILS), - "inr" => Ok(Currency::INR), - "isk" => Ok(Currency::ISK), - "jmd" => Ok(Currency::JMD), - "jpy" => Ok(Currency::JPY), - "kes" => Ok(Currency::KES), - "kgs" => Ok(Currency::KGS), - "khr" => Ok(Currency::KHR), - "kmf" => Ok(Currency::KMF), - "krw" => Ok(Currency::KRW), - "kyd" => Ok(Currency::KYD), - "kzt" => Ok(Currency::KZT), - "lak" => Ok(Currency::LAK), - "lbp" => Ok(Currency::LBP), - "lkr" => Ok(Currency::LKR), - "lrd" => Ok(Currency::LRD), - "lsl" => Ok(Currency::LSL), - "ltl" => Ok(Currency::LTL), - "lvl" => Ok(Currency::LVL), - "mad" => Ok(Currency::MAD), - "mdl" => Ok(Currency::MDL), - "mga" => Ok(Currency::MGA), - "mkd" => Ok(Currency::MKD), - "mnt" => Ok(Currency::MNT), - "mop" => Ok(Currency::MOP), - "mro" => Ok(Currency::MRO), - "mur" => Ok(Currency::MUR), - "mvr" => Ok(Currency::MVR), - "mwk" => Ok(Currency::MWK), - "mxn" => Ok(Currency::MXN), - "myr" => Ok(Currency::MYR), - "mzn" => Ok(Currency::MZN), - "nad" => Ok(Currency::NAD), - "ngn" => Ok(Currency::NGN), - "nio" => Ok(Currency::NIO), - "nok" => Ok(Currency::NOK), - "npr" => Ok(Currency::NPR), - "nzd" => Ok(Currency::NZD), - "pab" => Ok(Currency::PAB), - "pen" => Ok(Currency::PEN), - "pgk" => Ok(Currency::PGK), - "php" => Ok(Currency::PHP), - "pkr" => Ok(Currency::PKR), - "pln" => Ok(Currency::PLN), - "pyg" => Ok(Currency::PYG), - "qar" => Ok(Currency::QAR), - "ron" => Ok(Currency::RON), - "rsd" => Ok(Currency::RSD), - "rub" => Ok(Currency::RUB), - "rwf" => Ok(Currency::RWF), - "sar" => Ok(Currency::SAR), - "sbd" => Ok(Currency::SBD), - "scr" => Ok(Currency::SCR), - "sek" => Ok(Currency::SEK), - "sgd" => Ok(Currency::SGD), - "shp" => Ok(Currency::SHP), - "sll" => Ok(Currency::SLL), - "sos" => Ok(Currency::SOS), - "srd" => Ok(Currency::SRD), - "std" => Ok(Currency::STD), - "svc" => Ok(Currency::SVC), - "szl" => Ok(Currency::SZL), - "thb" => Ok(Currency::THB), - "tjs" => Ok(Currency::TJS), - "top" => Ok(Currency::TOP), - "try" => Ok(Currency::TRY), - "ttd" => Ok(Currency::TTD), - "twd" => Ok(Currency::TWD), - "tzs" => Ok(Currency::TZS), - "uah" => Ok(Currency::UAH), - "ugx" => Ok(Currency::UGX), - "usd" => Ok(Currency::USD), - "uyu" => Ok(Currency::UYU), - "uzs" => Ok(Currency::UZS), - "vef" => Ok(Currency::VEF), - "vnd" => Ok(Currency::VND), - "vuv" => Ok(Currency::VUV), - "wst" => Ok(Currency::WST), - "xaf" => Ok(Currency::XAF), - "xcd" => Ok(Currency::XCD), - "xof" => Ok(Currency::XOF), - "xpf" => Ok(Currency::XPF), - "yer" => Ok(Currency::YER), - "zar" => Ok(Currency::ZAR), - "zmw" => Ok(Currency::ZMW), - _ => Err(ParseCurrencyError(())), - } - } -} - -#[derive(Debug)] -pub struct ParseCurrencyError(/* private */ ()); - -impl std::fmt::Display for ParseCurrencyError { - fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - #[allow(deprecated)] - fmt.write_str(::std::error::Error::description(self)) - } -} - -impl std::error::Error for ParseCurrencyError { - fn description(&self) -> &str { - "unknown currency code" - } -} diff --git a/ft-stripe/src/resources/customer.rs b/ft-stripe/src/resources/customer.rs deleted file mode 100644 index dcbe0fb..0000000 --- a/ft-stripe/src/resources/customer.rs +++ /dev/null @@ -1,679 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ - AlipayAccountId, BankAccountId, CardId, CouponId, CustomerId, PaymentMethodId, PaymentSourceId, -}; -use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Address, Currency, CustomField, Discount, PaymentMethod, PaymentSource, PaymentSourceParams, - Scheduled, Shipping, ShippingParams, Subscription, TaxId, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Customer". -/// -/// For more details see [https://stripe.com/docs/api/customers/object](https://stripe.com/docs/api/customers/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Customer { - /// Unique identifier for the object. - pub id: CustomerId, - - /// The customer's address. - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - /// Current balance, if any, being stored on the customer. - /// - /// If negative, the customer has credit to apply to their next invoice. - /// If positive, the customer has an amount owed that will be added to their next invoice. - /// The balance does not refer to any unpaid invoices; it solely takes into account amounts that have yet to be successfully applied to any invoice. - /// This balance is only taken into account as invoices are finalized. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) the customer can be charged in for recurring billing purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// ID of the default payment source for the customer. - /// - /// If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method) field instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// When the customer's latest invoice is billed by charging automatically, delinquent is true if the invoice's latest charge is failed. - /// - /// When the customer's latest invoice is billed by sending an invoice, delinquent is true if the invoice is not paid by its due date. - #[serde(skip_serializing_if = "Option::is_none")] - pub delinquent: Option, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Describes the current discount active on the customer, if there is one. - #[serde(skip_serializing_if = "Option::is_none")] - pub discount: Option, - - /// The customer's email address. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// The prefix for the customer used to generate unique invoice numbers. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_prefix: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The customer's full name or business name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// The suffix of the customer's next invoice number, e.g., 0001. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_invoice_sequence: Option, - - /// The customer's phone number. - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - /// The customer's preferred locales (languages), ordered by preference. - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_locales: Option>, - - /// Mailing and shipping address for the customer. - /// - /// Appears on invoices emailed to this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// The customer's payment sources, if any. - #[serde(default)] - pub sources: List, - - /// The customer's current subscriptions, if any. - #[serde(default)] - pub subscriptions: List, - - /// Describes the customer's tax exemption status. - /// - /// One of `none`, `exempt`, or `reverse`. - /// When set to `reverse`, invoice and receipt PDFs include the text **"Reverse charge"**. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_exempt: Option, - - /// The customer's tax IDs. - #[serde(default)] - pub tax_ids: List, -} - -impl Customer { - /// Returns a list of your customers. - /// - /// The customers are returned sorted by creation date, with the most recent customers appearing first. - pub fn list(client: &Client, params: ListCustomers<'_>) -> Response> { - client.get_query("/customers", ¶ms) - } - - /// Creates a new customer object. - pub fn create(client: &Client, params: CreateCustomer<'_>) -> Response { - client.post_form("/customers", ¶ms) - } - - /// Retrieves the details of an existing customer. - /// - /// You need only supply the unique customer identifier that was returned upon customer creation. - pub fn retrieve(client: &Client, id: &CustomerId, expand: &[&str]) -> Response { - client.get_query(&format!("/customers/{}", id), &Expand { expand }) - } - - /// Updates the specified customer by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. - /// For example, if you pass the **source** parameter, that becomes the customer’s active source (e.g., a card) to be used for all charges in the future. - /// When you update a customer to a new valid card source by passing the **source** parameter: for each of the customer’s current subscriptions, if the subscription bills automatically and is in the `past_due` state, then the latest open invoice for the subscription with automatic collection enabled will be retried. - /// This retry will not count as an automatic retry, and will not affect the next regularly scheduled payment for the invoice. - /// Changing the **default_source** for a customer will not trigger this behavior. This request accepts mostly the same arguments as the customer creation call. - pub fn update( - client: &Client, - id: &CustomerId, - params: UpdateCustomer<'_>, - ) -> Response { - client.post_form(&format!("/customers/{}", id), ¶ms) - } - - /// Permanently deletes a customer. - /// - /// It cannot be undone. - /// Also immediately cancels any active subscriptions on the customer. - pub fn delete(client: &Client, id: &CustomerId) -> Response> { - client.delete(&format!("/customers/{}", id)) - } -} - -impl Object for Customer { - type Id = CustomerId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "customer" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceSettingCustomerSetting { - /// Default custom fields to be displayed on invoices for this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub custom_fields: Option>, - - /// ID of a payment method that's attached to the customer, to be used as the customer's default payment method for subscriptions and invoices. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option>, - - /// Default footer to be displayed on invoices for this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub footer: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceSettingCustomField { - /// The name of the custom field. - pub name: String, - - /// The value of the custom field. - pub value: String, -} - -/// The parameters for `Customer::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateCustomer<'a> { - /// The customer's address. - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - /// An integer amount in %s that represents the customer's current balance, which affect the customer's future invoices. - /// - /// A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// An arbitrary string that you can attach to a customer object. - /// - /// It is displayed alongside the customer in the dashboard. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Customer's email address. - /// - /// It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. - /// This may be up to *512 characters*. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The prefix for the customer used to generate unique invoice numbers. - /// - /// Must be 3–12 uppercase letters or numbers. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_prefix: Option<&'a str>, - - /// Default invoice settings for this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The customer's full name or business name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, - - /// The sequence to be used on the customer's next invoice. - /// - /// Defaults to 1. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_invoice_sequence: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// The customer's phone number. - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option<&'a str>, - - /// Customer's preferred languages, ordered by preference. - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_locales: Option>, - - /// The customer's shipping information. - /// - /// Appears on invoices emailed to this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - - /// The customer's tax exemption. - /// - /// One of `none`, `exempt`, or `reverse`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_exempt: Option, - - /// The customer's tax IDs. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id_data: Option>, -} - -impl<'a> CreateCustomer<'a> { - pub fn new() -> Self { - CreateCustomer { - address: Default::default(), - balance: Default::default(), - coupon: Default::default(), - description: Default::default(), - email: Default::default(), - expand: Default::default(), - invoice_prefix: Default::default(), - invoice_settings: Default::default(), - metadata: Default::default(), - name: Default::default(), - next_invoice_sequence: Default::default(), - payment_method: Default::default(), - phone: Default::default(), - preferred_locales: Default::default(), - shipping: Default::default(), - source: Default::default(), - tax_exempt: Default::default(), - tax_id_data: Default::default(), - } - } -} - -/// The parameters for `Customer::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListCustomers<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A filter on the list based on the customer's `email` field. - /// - /// The value must be a string. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListCustomers<'a> { - pub fn new() -> Self { - ListCustomers { - created: Default::default(), - email: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Customer::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateCustomer<'a> { - /// The customer's address. - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - /// An integer amount in %s that represents the customer's current balance, which affect the customer's future invoices. - /// - /// A negative amount represents a credit that decreases the amount due on an invoice; a positive amount increases the amount due on an invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// ID of Alipay account to make the customer's new default for invoice payments. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_alipay_account: Option, - - /// ID of bank account to make the customer's new default for invoice payments. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_bank_account: Option, - - /// ID of card to make the customer's new default for invoice payments. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_card: Option, - - /// If you are using payment methods created via the PaymentMethods API, see the [invoice_settings.default_payment_method](https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method) parameter. - /// - /// Provide the ID of a payment source already attached to this customer to make it this customer's default payment source. - /// - /// If you want to add a new payment source and make it the default, see the [source](https://stripe.com/docs/api/customers/update#update_customer-source) property. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option, - - /// An arbitrary string that you can attach to a customer object. - /// - /// It is displayed alongside the customer in the dashboard. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Customer's email address. - /// - /// It's displayed alongside the customer in your dashboard and can be useful for searching and tracking. - /// This may be up to *512 characters*. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The prefix for the customer used to generate unique invoice numbers. - /// - /// Must be 3–12 uppercase letters or numbers. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_prefix: Option<&'a str>, - - /// Default invoice settings for this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The customer's full name or business name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, - - /// The sequence to be used on the customer's next invoice. - /// - /// Defaults to 1. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_invoice_sequence: Option, - - /// The customer's phone number. - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option<&'a str>, - - /// Customer's preferred languages, ordered by preference. - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_locales: Option>, - - /// The customer's shipping information. - /// - /// Appears on invoices emailed to this customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - - /// The customer's tax exemption. - /// - /// One of `none`, `exempt`, or `reverse`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_exempt: Option, - - /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. - /// - /// This will always overwrite any trials that might apply via a subscribed plan. - /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. - /// The special value `now` can be provided to end the customer's trial immediately. - /// Can be at most two years from `billing_cycle_anchor`. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, -} - -impl<'a> UpdateCustomer<'a> { - pub fn new() -> Self { - UpdateCustomer { - address: Default::default(), - balance: Default::default(), - coupon: Default::default(), - default_alipay_account: Default::default(), - default_bank_account: Default::default(), - default_card: Default::default(), - default_source: Default::default(), - description: Default::default(), - email: Default::default(), - expand: Default::default(), - invoice_prefix: Default::default(), - invoice_settings: Default::default(), - metadata: Default::default(), - name: Default::default(), - next_invoice_sequence: Default::default(), - phone: Default::default(), - preferred_locales: Default::default(), - shipping: Default::default(), - source: Default::default(), - tax_exempt: Default::default(), - trial_end: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CustomerInvoiceSettings { - #[serde(skip_serializing_if = "Option::is_none")] - pub custom_fields: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub footer: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxIdData { - #[serde(rename = "type")] - pub type_: TaxIdType, - - pub value: String, -} - -/// An enum representing the possible values of an `Customer`'s `tax_exempt` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CustomerTaxExempt { - Exempt, - None, - Reverse, -} - -impl CustomerTaxExempt { - pub fn as_str(self) -> &'static str { - match self { - CustomerTaxExempt::Exempt => "exempt", - CustomerTaxExempt::None => "none", - CustomerTaxExempt::Reverse => "reverse", - } - } -} - -impl AsRef for CustomerTaxExempt { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CustomerTaxExempt { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateCustomer`'s `tax_exempt` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CustomerTaxExemptFilter { - Exempt, - None, - Reverse, -} - -impl CustomerTaxExemptFilter { - pub fn as_str(self) -> &'static str { - match self { - CustomerTaxExemptFilter::Exempt => "exempt", - CustomerTaxExemptFilter::None => "none", - CustomerTaxExemptFilter::Reverse => "reverse", - } - } -} - -impl AsRef for CustomerTaxExemptFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CustomerTaxExemptFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `TaxIdData`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TaxIdType { - AuAbn, - BrCnpj, - BrCpf, - CaBn, - CaQst, - ChVat, - EsCif, - EuVat, - HkBr, - InGst, - JpCn, - KrBrn, - LiUid, - MxRfc, - MyItn, - MySst, - NoVat, - NzGst, - RuInn, - SgGst, - SgUen, - ThVat, - TwVat, - UsEin, - ZaVat, -} - -impl TaxIdType { - pub fn as_str(self) -> &'static str { - match self { - TaxIdType::AuAbn => "au_abn", - TaxIdType::BrCnpj => "br_cnpj", - TaxIdType::BrCpf => "br_cpf", - TaxIdType::CaBn => "ca_bn", - TaxIdType::CaQst => "ca_qst", - TaxIdType::ChVat => "ch_vat", - TaxIdType::EsCif => "es_cif", - TaxIdType::EuVat => "eu_vat", - TaxIdType::HkBr => "hk_br", - TaxIdType::InGst => "in_gst", - TaxIdType::JpCn => "jp_cn", - TaxIdType::KrBrn => "kr_brn", - TaxIdType::LiUid => "li_uid", - TaxIdType::MxRfc => "mx_rfc", - TaxIdType::MyItn => "my_itn", - TaxIdType::MySst => "my_sst", - TaxIdType::NoVat => "no_vat", - TaxIdType::NzGst => "nz_gst", - TaxIdType::RuInn => "ru_inn", - TaxIdType::SgGst => "sg_gst", - TaxIdType::SgUen => "sg_uen", - TaxIdType::ThVat => "th_vat", - TaxIdType::TwVat => "tw_vat", - TaxIdType::UsEin => "us_ein", - TaxIdType::ZaVat => "za_vat", - } - } -} - -impl AsRef for TaxIdType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TaxIdType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/customer_ext.rs b/ft-stripe/src/resources/customer_ext.rs deleted file mode 100644 index 981e6d6..0000000 --- a/ft-stripe/src/resources/customer_ext.rs +++ /dev/null @@ -1,84 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{BankAccountId, CardId, CustomerId, PaymentSourceId}; -use crate::params::Deleted; -use crate::resources::{BankAccount, Customer, PaymentSource, PaymentSourceParams, Source}; -use serde::{Deserialize, Serialize}; - -impl Customer { - /// Attaches a source to a customer, does not change default Source for the Customer - /// - /// For more details see [https://stripe.com/docs/api#attach_source](https://stripe.com/docs/api#attach_source). - pub fn attach_source( - client: &Client, - customer_id: &CustomerId, - source: PaymentSourceParams, - ) -> Response { - #[derive(Serialize)] - struct AttachSource { - source: PaymentSourceParams, - } - let params = AttachSource { source }; - client.post_form(&format!("/customers/{}/sources", customer_id), params) - } - - /// Detaches a source from a customer - /// - /// For more details see [https://stripe.com/docs/api#detach_source](https://stripe.com/docs/api#detach_source). - pub fn detach_source( - client: &Client, - customer_id: &CustomerId, - source_id: &PaymentSourceId, - ) -> Response { - client.delete(&format!("/customers/{}/sources/{}", customer_id, source_id)) - } - - /// Retrieves a Card, BankAccount, or Source for a Customer - pub fn retrieve_source( - client: &Client, - customer_id: &CustomerId, - source_id: &PaymentSourceId, - ) -> Response { - client.get(&format!("/customers/{}/sources/{}", customer_id, source_id)) - } - - /// Verifies a Bank Account for a Customer. - /// - /// For more details see https://stripe.com/docs/api/customer_bank_accounts/verify. - pub fn verify_bank_account( - client: &Client, - customer_id: &CustomerId, - bank_account_id: &BankAccountId, - params: VerifyBankAccount<'_>, - ) -> Response { - client.post_form( - &format!("/customers/{}/sources/{}/verify", customer_id, bank_account_id), - params, - ) - } -} - -/// The set of parameters that can be used when verifying a Bank Account. -/// -/// For more details see https://stripe.com/docs/api/customer_bank_accounts/verify?lang=curl. -#[derive(Clone, Debug, Default, Serialize)] -pub struct VerifyBankAccount<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub amounts: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub verification_method: Option<&'a str>, -} - -impl VerifyBankAccount<'_> { - pub fn new() -> Self { - VerifyBankAccount { amounts: None, verification_method: None } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum DetachedSource { - BankAccount(Deleted), - Card(Deleted), - Source(Source), -} diff --git a/ft-stripe/src/resources/discount.rs b/ft-stripe/src/resources/discount.rs deleted file mode 100644 index 73581bb..0000000 --- a/ft-stripe/src/resources/discount.rs +++ /dev/null @@ -1,47 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::{Expandable, Object, Timestamp}; -use crate::resources::{Coupon, Customer}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Discount". -/// -/// For more details see [https://stripe.com/docs/api/discounts/object](https://stripe.com/docs/api/discounts/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Discount { - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// The ID of the customer associated with this discount. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// If the coupon has a duration of `repeating`, the date that this discount will end. - /// - /// If the coupon has a duration of `once` or `forever`, this attribute will be null. - #[serde(skip_serializing_if = "Option::is_none")] - pub end: Option, - - /// Date that the coupon was applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub start: Option, - - /// The subscription that this coupon is applied to, if it is applied to a particular subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, -} - -impl Object for Discount { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "discount" - } -} diff --git a/ft-stripe/src/resources/dispute.rs b/ft-stripe/src/resources/dispute.rs deleted file mode 100644 index dfcdfc9..0000000 --- a/ft-stripe/src/resources/dispute.rs +++ /dev/null @@ -1,339 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ChargeId, DisputeId, PaymentIntentId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{BalanceTransaction, Charge, Currency, File, PaymentIntent}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Dispute". -/// -/// For more details see [https://stripe.com/docs/api/disputes/object](https://stripe.com/docs/api/disputes/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Dispute { - /// Unique identifier for the object. - pub id: DisputeId, - - /// Disputed amount. - /// - /// Usually the amount of the charge, but can differ (usually because of currency fluctuation or because only part of the order is disputed). - pub amount: i64, - - /// List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your Stripe account as a result of this dispute. - pub balance_transactions: Vec, - - /// ID of the charge that was disputed. - pub charge: Expandable, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - pub evidence: DisputeEvidence, - - pub evidence_details: DisputeEvidenceDetails, - - /// If true, it is still possible to refund the disputed payment. - /// - /// Once the payment has been fully refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute. - pub is_charge_refundable: bool, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// ID of the PaymentIntent that was disputed. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// Reason given by cardholder for dispute. - /// - /// Possible values are `bank_cannot_process`, `check_returned`, `credit_not_processed`, `customer_initiated`, `debit_not_authorized`, `duplicate`, `fraudulent`, `general`, `incorrect_account_details`, `insufficient_funds`, `product_not_received`, `product_unacceptable`, `subscription_canceled`, or `unrecognized`. - /// Read more about [dispute reasons](https://stripe.com/docs/disputes/categories). - pub reason: String, - - /// Current status of dispute. - /// - /// Possible values are `warning_needs_response`, `warning_under_review`, `warning_closed`, `needs_response`, `under_review`, `charge_refunded`, `won`, or `lost`. - pub status: DisputeStatus, -} - -impl Dispute { - /// Returns a list of your disputes. - pub fn list(client: &Client, params: ListDisputes<'_>) -> Response> { - client.get_query("/disputes", ¶ms) - } - - /// Retrieves the dispute with the given ID. - pub fn retrieve(client: &Client, id: &DisputeId, expand: &[&str]) -> Response { - client.get_query(&format!("/disputes/{}", id), &Expand { expand }) - } -} - -impl Object for Dispute { - type Id = DisputeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "dispute" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DisputeEvidence { - /// Any server or activity logs showing proof that the customer accessed or downloaded the purchased digital product. - /// - /// This information should include IP addresses, corresponding timestamps, and any detailed recorded activity. - #[serde(skip_serializing_if = "Option::is_none")] - pub access_activity_log: Option, - - /// The billing address provided by the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_address: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your subscription cancellation policy, as shown to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_policy: Option>, - - /// An explanation of how and when the customer was shown your refund policy prior to purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_policy_disclosure: Option, - - /// A justification for why the customer's subscription was not canceled. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_rebuttal: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any communication with the customer that you feel is relevant to your case. - /// - /// Examples include emails proving that the customer received the product or service, or demonstrating their use of or satisfaction with the product or service. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_communication: Option>, - - /// The email address of the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_email_address: Option, - - /// The name of the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_name: Option, - - /// The IP address that the customer used when making the purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_purchase_ip: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) A relevant document or contract showing the customer's signature. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_signature: Option>, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation for the prior charge that can uniquely identify the charge, such as a receipt, shipping label, work order, etc. - /// - /// This document should be paired with a similar document from the disputed payment that proves the two payments are separate. - #[serde(skip_serializing_if = "Option::is_none")] - pub duplicate_charge_documentation: Option>, - - /// An explanation of the difference between the disputed charge versus the prior charge that appears to be a duplicate. - #[serde(skip_serializing_if = "Option::is_none")] - pub duplicate_charge_explanation: Option, - - /// The Stripe ID for the prior charge which appears to be a duplicate of the disputed charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub duplicate_charge_id: Option, - - /// A description of the product or service that was sold. - #[serde(skip_serializing_if = "Option::is_none")] - pub product_description: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any receipt or message sent to the customer notifying them of the charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt: Option>, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Your refund policy, as shown to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_policy: Option>, - - /// Documentation demonstrating that the customer was shown your refund policy prior to purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_policy_disclosure: Option, - - /// A justification for why the customer is not entitled to a refund. - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_refusal_explanation: Option, - - /// The date on which the customer received or began receiving the purchased service, in a clear human-readable format. - #[serde(skip_serializing_if = "Option::is_none")] - pub service_date: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a service was provided to the customer. - /// - /// This could include a copy of a signed contract, work order, or other form of written agreement. - #[serde(skip_serializing_if = "Option::is_none")] - pub service_documentation: Option>, - - /// The address to which a physical product was shipped. - /// - /// You should try to include as complete address information as possible. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_address: Option, - - /// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. - /// - /// If multiple carriers were used for this purchase, please separate them with commas. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_carrier: Option, - - /// The date on which a physical product began its route to the shipping address, in a clear human-readable format. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_date: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Documentation showing proof that a product was shipped to the customer at the same address the customer provided to you. - /// - /// This could include a copy of the shipment receipt, shipping label, etc. - /// It should show the customer's full shipping address, if possible. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_documentation: Option>, - - /// The tracking number for a physical product, obtained from the delivery service. - /// - /// If multiple tracking numbers were generated for this purchase, please separate them with commas. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_tracking_number: Option, - - /// (ID of a [file upload](https://stripe.com/docs/guides/file-upload)) Any additional evidence or statements. - #[serde(skip_serializing_if = "Option::is_none")] - pub uncategorized_file: Option>, - - /// Any additional evidence or statements. - #[serde(skip_serializing_if = "Option::is_none")] - pub uncategorized_text: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DisputeEvidenceDetails { - /// Date by which evidence must be submitted in order to successfully challenge dispute. - /// - /// Will be null if the customer's bank or credit card company doesn't allow a response for this particular dispute. - #[serde(skip_serializing_if = "Option::is_none")] - pub due_by: Option, - - /// Whether evidence has been staged for this dispute. - pub has_evidence: bool, - - /// Whether the last evidence submission was submitted past the due date. - /// - /// Defaults to `false` if no evidence submissions have occurred. - /// If `true`, then delivery of the latest evidence is *not* guaranteed. - pub past_due: bool, - - /// The number of times evidence has been submitted. - /// - /// Typically, you may only submit evidence once. - pub submission_count: u64, -} - -/// The parameters for `Dispute::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListDisputes<'a> { - /// Only return disputes associated to the charge specified by this charge ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return disputes associated to the PaymentIntent specified by this PaymentIntent ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListDisputes<'a> { - pub fn new() -> Self { - ListDisputes { - charge: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - payment_intent: Default::default(), - starting_after: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Dispute`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum DisputeStatus { - ChargeRefunded, - Lost, - NeedsResponse, - UnderReview, - WarningClosed, - WarningNeedsResponse, - WarningUnderReview, - Won, -} - -impl DisputeStatus { - pub fn as_str(self) -> &'static str { - match self { - DisputeStatus::ChargeRefunded => "charge_refunded", - DisputeStatus::Lost => "lost", - DisputeStatus::NeedsResponse => "needs_response", - DisputeStatus::UnderReview => "under_review", - DisputeStatus::WarningClosed => "warning_closed", - DisputeStatus::WarningNeedsResponse => "warning_needs_response", - DisputeStatus::WarningUnderReview => "warning_under_review", - DisputeStatus::Won => "won", - } - } -} - -impl AsRef for DisputeStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for DisputeStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/event.rs b/ft-stripe/src/resources/event.rs deleted file mode 100644 index 5196bf8..0000000 --- a/ft-stripe/src/resources/event.rs +++ /dev/null @@ -1,404 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::error::WebhookError; -use crate::ids::{AccountId, EventId}; -use crate::resources::*; - -use chrono::Utc; -#[cfg(feature = "webhook-events")] -use hmac::{Hmac, Mac}; -use serde::{Deserialize, Serialize}; -#[cfg(feature = "webhook-events")] -use sha2::Sha256; - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] -pub enum EventType { - #[serde(rename = "account.updated")] - AccountUpdated, - #[serde(rename = "account.application.deauthorized")] - AccountApplicationDeauthorized, - #[serde(rename = "account.external_account.created")] - AccountExternalAccountCreated, - #[serde(rename = "account.external_account.deleted")] - AccountExternalAccountDeleted, - #[serde(rename = "account.external_account.updated")] - AccountExternalAccountUpdated, - #[serde(rename = "application_fee.created")] - ApplicationFeeCreated, - #[serde(rename = "application_fee.refunded")] - ApplicationFeeRefunded, - #[serde(rename = "application_fee.refund.updated")] - ApplicationFeeRefundUpdated, - #[serde(rename = "balance.available")] - BalanceAvailable, - #[serde(rename = "charge.captured")] - ChargeCaptured, - #[serde(rename = "charge.failed")] - ChargeFailed, - #[serde(rename = "charge.pending")] - ChargePending, - #[serde(rename = "charge.refunded")] - ChargeRefunded, - #[serde(rename = "charge.succeeded")] - ChargeSucceeded, - #[serde(rename = "charge.updated")] - ChargeUpdated, - #[serde(rename = "charge.dispute.closed")] - ChargeDisputeClosed, - #[serde(rename = "charge.dispute.created")] - ChargeDisputeCreated, - #[serde(rename = "charge.dispute.funds_reinstated")] - ChargeDisputeFundsReinstated, - #[serde(rename = "charge.dispute.funds_withdrawn")] - ChargeDisputeFundsWithdrawn, - #[serde(rename = "charge.dispute.updated")] - ChargeDisputeUpdated, - #[serde(rename = "charge.refund.updated")] - ChargeRefundUpdated, - #[serde(rename = "checkout.session.completed")] - CheckoutSessionCompleted, - #[serde(rename = "coupon.created")] - CouponCreated, - #[serde(rename = "coupon.deleted")] - CouponDeleted, - #[serde(rename = "coupon.updated")] - CouponUpdated, - #[serde(rename = "customer.created")] - CustomerCreated, - #[serde(rename = "customer.deleted")] - CustomerDeleted, - #[serde(rename = "customer.updated")] - CustomerUpdated, - #[serde(rename = "customer.discount.created")] - CustomerDiscountCreated, - #[serde(rename = "customer.discount.deleted")] - CustomerDiscountDeleted, - #[serde(rename = "customer.discount.updated")] - CustomerDiscountUpdated, - #[serde(rename = "customer.source.created")] - CustomerSourceCreated, - #[serde(rename = "customer.source.deleted")] - CustomerSourceDeleted, - #[serde(rename = "customer.source.expiring")] - CustomerSourceExpiring, - #[serde(rename = "customer.source.updated")] - CustomerSourceUpdated, - #[serde(rename = "customer.subscription.created")] - CustomerSubscriptionCreated, - #[serde(rename = "customer.subscription.deleted")] - CustomerSubscriptionDeleted, - #[serde(rename = "customer.subscription.trial_will_end")] - CustomerSubscriptionTrialWillEnd, - #[serde(rename = "customer.subscription.updated")] - CustomerSubscriptionUpdated, - #[serde(rename = "file.created")] - FileCreated, - #[serde(rename = "invoice.created")] - InvoiceCreated, - #[serde(rename = "invoice.deleted")] - InvoiceDeleted, - #[serde(rename = "invoice.finalized")] - InvoiceFinalized, - #[serde(rename = "invoice.marked_uncollectible")] - InvoiceMarkedUncollectible, - #[serde(rename = "invoice.payment_action_required")] - InvoicePaymentActionRequired, - #[serde(rename = "invoice.payment_failed")] - InvoicePaymentFailed, - #[serde(rename = "invoice.payment_succeeded")] - InvoicePaymentSucceeded, - #[serde(rename = "invoice.sent")] - InvoiceSent, - #[serde(rename = "invoice.updated")] - InvoiceUpdated, - #[serde(rename = "invoice.upcoming")] - InvoiceUpcoming, - #[serde(rename = "invoice.voided")] - InvoiceVoided, - #[serde(rename = "invoiceitem.created")] - InvoiceItemCreated, - #[serde(rename = "invoiceitem.deleted")] - InvoiceItemDeleted, - #[serde(rename = "invoiceitem.updated")] - InvoiceItemUpdated, - #[serde(rename = "order.created")] - OrderCreated, - #[serde(rename = "order.payment_failed")] - OrderPaymentFailed, - #[serde(rename = "order.payment_succeeded")] - OrderPaymentSucceeded, - #[serde(rename = "order.updated")] - OrderUpdated, - #[serde(rename = "order_return.updated")] - OrderReturnUpdated, - #[serde(rename = "payment_intent.amount_capturable_updated")] - PaymentIntentAmountCapturableUpdated, - #[serde(rename = "payment_intent.created")] - PaymentIntentCreated, - #[serde(rename = "payment_intent.payment_failed")] - PaymentIntentPaymentFailed, - #[serde(rename = "payment_intent.requires_capture")] - PaymentIntentRequiresCapture, - #[serde(rename = "payment_intent.succeeded")] - PaymentIntentSucceeded, - #[serde(rename = "payment_method.automatically_updated")] - PaymentMethodAutomaticallyUpdated, - #[serde(rename = "payment_method.attached")] - PaymentMethodAttached, - #[serde(rename = "payment_method.detached")] - PaymentMethodDetached, - #[serde(rename = "payout.canceled")] - PayoutCanceled, - #[serde(rename = "payout.created")] - PayoutCreated, - #[serde(rename = "payout.failed")] - PayoutFailed, - #[serde(rename = "payout.paid")] - PayoutPaid, - #[serde(rename = "payout.updated")] - PayoutUpdated, - #[serde(rename = "plan.created")] - PlanCreated, - #[serde(rename = "plan.deleted")] - PlanDeleted, - #[serde(rename = "plan.updated")] - PlanUpdated, - #[serde(rename = "product.created")] - ProductCreated, - #[serde(rename = "product.deleted")] - ProductDeleted, - #[serde(rename = "product.updated")] - ProductUpdated, - #[serde(rename = "review.closed")] - ReviewClosed, - #[serde(rename = "review.opened")] - ReviewOpened, - #[serde(rename = "sigma.scheduled_query_run.created")] - SigmaScheduledQueryRunCreated, - #[serde(rename = "sku.created")] - SkuCreated, - #[serde(rename = "sku.deleted")] - SkuDeleted, - #[serde(rename = "sku.updated")] - SkuUpdated, - #[serde(rename = "source.canceled")] - SourceCanceled, - #[serde(rename = "source.chargeable")] - Sourcechargeable, - #[serde(rename = "source.failed")] - SourceFailed, - #[serde(rename = "source.transaction.created")] - SourceTransactionCreated, - #[serde(rename = "transfer.created")] - TransferCreated, - #[serde(rename = "transfer.reversed")] - TransferReversed, - #[serde(rename = "transfer.updated")] - TransferUpdated, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Event { - pub id: EventId, - #[serde(rename = "type")] - pub event_type: EventType, - pub data: EventData, - pub created: i64, - pub livemode: bool, - pub account: Option, - // ... -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct EventData { - pub object: EventObject, - // previous_attributes: ... -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum EventObject { - Account(Account), - ApplicationFee(ApplicationFee), - #[serde(rename = "fee_refund")] - ApplicationFeeRefund(ApplicationFeeRefund), - Balance(Balance), - BankAccount(BankAccount), - Card(Card), - Charge(Charge), - Customer(Customer), - Dispute(Dispute), - #[serde(rename = "checkout.session")] - CheckoutSession(CheckoutSession), - File(File), - Invoice(Invoice), - #[serde(rename = "invoiceitem")] - InvoiceItem(InvoiceItem), - Order(Order), - OrderReturn(OrderReturn), - PaymentIntent(PaymentIntent), - PaymentMethod(PaymentMethod), - Payout(Payout), - Plan(Plan), - Product(Product), - Refund(Refund), - Review(Review), - Sku(Sku), - Subscription(Subscription), - Transfer(Transfer), -} - -#[cfg(feature = "webhook-events")] -pub struct Webhook { - current_timestamp: i64, -} - -#[cfg(feature = "webhook-events")] -impl Webhook { - pub fn construct_event(payload: &str, sig: &str, secret: &str) -> Result { - Self { current_timestamp: Utc::now().timestamp() }.do_construct_event(payload, sig, secret) - } - - fn do_construct_event( - self, - payload: &str, - sig: &str, - secret: &str, - ) -> Result { - // Get Stripe signature from header - let signature = Signature::parse(&sig)?; - let signed_payload = format!("{}{}{}", signature.t, ".", payload); - - // Compute HMAC with the SHA256 hash function, using endpoing secret as key - // and signed_payload string as the message. - let mut mac = - Hmac::::new_from_slice(secret.as_bytes()).map_err(|_| WebhookError::BadKey)?; - mac.update(signed_payload.as_bytes()); - let sig = hex::decode(signature.v1).map_err(|_| WebhookError::BadSignature)?; - mac.verify_slice(sig.as_slice()).map_err(|_| WebhookError::BadSignature)?; - - // Get current timestamp to compare to signature timestamp - if (self.current_timestamp - signature.t).abs() > 300 { - return Err(WebhookError::BadTimestamp(signature.t)); - } - - serde_json::from_str(&payload).map_err(WebhookError::BadParse) - } -} - -#[cfg(feature = "webhook-events")] -#[derive(Debug)] -struct Signature<'r> { - t: i64, - v1: &'r str, - v0: Option<&'r str>, -} - -#[cfg(feature = "webhook-events")] -impl<'r> Signature<'r> { - fn parse(raw: &'r str) -> Result, WebhookError> { - use std::collections::HashMap; - let headers: HashMap<&str, &str> = raw - .split(',') - .map(|header| { - let mut key_and_value = header.split('='); - let key = key_and_value.next(); - let value = key_and_value.next(); - (key, value) - }) - .filter_map(|(key, value)| match (key, value) { - (Some(key), Some(value)) => Some((key, value)), - _ => None, - }) - .collect(); - let t = headers.get("t").ok_or(WebhookError::BadSignature)?; - let v1 = headers.get("v1").ok_or(WebhookError::BadSignature)?; - let v0 = headers.get("v0").map(|r| *r); - Ok(Signature { t: t.parse::().map_err(WebhookError::BadHeader)?, v1, v0 }) - } -} - -#[cfg(test)] -mod tests { - #[cfg(feature = "webhook-events")] - #[test] - fn test_signature_parse() { - use super::Signature; - - let raw_signature = - "t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd"; - let signature = Signature::parse(raw_signature).unwrap(); - assert_eq!(signature.t, 1492774577); - assert_eq!( - signature.v1, - "5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" - ); - assert_eq!(signature.v0, None); - - let raw_signature_with_test_mode = "t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39"; - let signature = Signature::parse(raw_signature_with_test_mode).unwrap(); - assert_eq!(signature.t, 1492774577); - assert_eq!( - signature.v1, - "5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd" - ); - assert_eq!( - signature.v0, - Some("6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39") - ); - } - - #[cfg(feature = "webhook-events")] - #[test] - fn test_webhook_construct_event() { - let payload = r#"{ - "id": "evt_123", - "object": "event", - "account": "acct_123", - "api_version": "2017-05-25", - "created": 1533204620, - "data": { - "object": { - "id": "ii_123", - "object": "invoiceitem", - "amount": 1000, - "currency": "usd", - "customer": "cus_123", - "date": 1533204620, - "description": "Test Invoice Item", - "discountable": false, - "invoice": "in_123", - "livemode": false, - "metadata": {}, - "period": { - "start": 1533204620, - "end": 1533204620 - }, - "plan": null, - "proration": false, - "quantity": null, - "subscription": null - } - }, - "livemode": false, - "pending_webhooks": 1, - "request": { - "id": "req_123", - "idempotency_key": "idempotency-key-123" - }, - "type": "invoiceitem.created" -} -"#; - let event_timestamp = 1533204620; - let secret = "webhook_secret".to_string(); - let signature = format!("t={},v1=f0bdba6d4eacbd8ad8a3bbadd7248e633ec1477f7899c124c51b39405fa36613,v0=63f3a72374a733066c4be69ed7f8e5ac85c22c9f0a6a612ab9a025a9e4ee7eef", event_timestamp); - - let webhook = super::Webhook { current_timestamp: event_timestamp }; - - let event = webhook - .do_construct_event(payload, &signature, &secret) - .expect("Failed to construct event"); - - assert_eq!(event.event_type, super::EventType::InvoiceItemCreated); - assert_eq!(event.id.to_string(), "evt_123"); - } -} diff --git a/ft-stripe/src/resources/fee_refund.rs b/ft-stripe/src/resources/fee_refund.rs deleted file mode 100644 index 4fdd1f4..0000000 --- a/ft-stripe/src/resources/fee_refund.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::ApplicationFeeRefundId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{ApplicationFee, BalanceTransaction, Currency}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "FeeRefund". -/// -/// For more details see [https://stripe.com/docs/api/fee_refunds/object](https://stripe.com/docs/api/fee_refunds/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ApplicationFeeRefund { - /// Unique identifier for the object. - pub id: ApplicationFeeRefundId, - - /// Amount, in %s. - pub amount: i64, - - /// Balance transaction that describes the impact on your account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// ID of the application fee that was refunded. - pub fee: Expandable, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, -} - -impl Object for ApplicationFeeRefund { - type Id = ApplicationFeeRefundId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "fee_refund" - } -} diff --git a/ft-stripe/src/resources/file.rs b/ft-stripe/src/resources/file.rs deleted file mode 100644 index 24ec5ce..0000000 --- a/ft-stripe/src/resources/file.rs +++ /dev/null @@ -1,175 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::FileId; -use crate::params::{Expand, List, Object, RangeQuery, Timestamp}; -use crate::resources::FileLink; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "File". -/// -/// For more details see [https://stripe.com/docs/api/files/object](https://stripe.com/docs/api/files/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct File { - /// Unique identifier for the object. - pub id: FileId, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// A filename for the file, suitable for saving to a filesystem. - #[serde(skip_serializing_if = "Option::is_none")] - pub filename: Option, - - /// A list of [file links](https://stripe.com/docs/api#file_links) that point at this file. - #[serde(default)] - pub links: List, - - /// The purpose of the file. - /// - /// Possible values are `additional_verification`, `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `identity_document`, `pci_document`, `sigma_scheduled_query`, or `tax_document_user_upload`. - pub purpose: FilePurpose, - - /// The size in bytes of the file object. - pub size: u64, - - /// A user friendly title for the document. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - - /// The type of the file returned (e.g., `csv`, `pdf`, `jpg`, or `png`). - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// The URL from which the file can be downloaded using your live secret API key. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -impl File { - /// Returns a list of the files that your account has access to. - /// - /// The files are returned sorted by creation date, with the most recently created files appearing first. - pub fn list(client: &Client, params: ListFiles<'_>) -> Response> { - client.get_query("/files", ¶ms) - } - - /// Retrieves the details of an existing file object. - /// - /// Supply the unique file ID from a file, and Stripe will return the corresponding file object. - /// To access file contents, see the [File Upload Guide](https://stripe.com/docs/file-upload#download-file-contents). - pub fn retrieve(client: &Client, id: &FileId, expand: &[&str]) -> Response { - client.get_query(&format!("/files/{}", id), &Expand { expand }) - } -} - -impl Object for File { - type Id = FileId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "file" - } -} - -/// The parameters for `File::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListFiles<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// The file purpose to filter queries by. - /// - /// If none is provided, files will not be filtered by purpose. - #[serde(skip_serializing_if = "Option::is_none")] - pub purpose: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListFiles<'a> { - pub fn new() -> Self { - ListFiles { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - purpose: Default::default(), - starting_after: Default::default(), - } - } -} - -/// An enum representing the possible values of an `ListFiles`'s `purpose` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum FilePurpose { - AdditionalVerification, - BusinessIcon, - BusinessLogo, - CustomerSignature, - DisputeEvidence, - FinanceReportRun, - IdentityDocument, - PciDocument, - SigmaScheduledQuery, - TaxDocumentUserUpload, -} - -impl FilePurpose { - pub fn as_str(self) -> &'static str { - match self { - FilePurpose::AdditionalVerification => "additional_verification", - FilePurpose::BusinessIcon => "business_icon", - FilePurpose::BusinessLogo => "business_logo", - FilePurpose::CustomerSignature => "customer_signature", - FilePurpose::DisputeEvidence => "dispute_evidence", - FilePurpose::FinanceReportRun => "finance_report_run", - FilePurpose::IdentityDocument => "identity_document", - FilePurpose::PciDocument => "pci_document", - FilePurpose::SigmaScheduledQuery => "sigma_scheduled_query", - FilePurpose::TaxDocumentUserUpload => "tax_document_user_upload", - } - } -} - -impl AsRef for FilePurpose { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for FilePurpose { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/file_link.rs b/ft-stripe/src/resources/file_link.rs deleted file mode 100644 index 444f685..0000000 --- a/ft-stripe/src/resources/file_link.rs +++ /dev/null @@ -1,205 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{FileId, FileLinkId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{File, Scheduled}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "FileLink". -/// -/// For more details see [https://stripe.com/docs/api/file_links/object](https://stripe.com/docs/api/file_links/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct FileLink { - /// Unique identifier for the object. - pub id: FileLinkId, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Whether this link is already expired. - pub expired: bool, - - /// Time at which the link expires. - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - - /// The file object this link points to. - pub file: Expandable, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The publicly accessible URL to download the file. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -impl FileLink { - /// Returns a list of file links. - pub fn list(client: &Client, params: ListFileLinks<'_>) -> Response> { - client.get_query("/file_links", ¶ms) - } - - /// Creates a new file link object. - pub fn create(client: &Client, params: CreateFileLink<'_>) -> Response { - client.post_form("/file_links", ¶ms) - } - - /// Retrieves the file link with the given ID. - pub fn retrieve(client: &Client, id: &FileLinkId, expand: &[&str]) -> Response { - client.get_query(&format!("/file_links/{}", id), &Expand { expand }) - } - - /// Updates an existing file link object. - /// - /// Expired links can no longer be updated. - pub fn update( - client: &Client, - id: &FileLinkId, - params: UpdateFileLink<'_>, - ) -> Response { - client.post_form(&format!("/file_links/{}", id), ¶ms) - } -} - -impl Object for FileLink { - type Id = FileLinkId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "file_link" - } -} - -/// The parameters for `FileLink::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateFileLink<'a> { - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A future timestamp after which the link will no longer be usable. - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - - /// The ID of the file. - /// - /// The file's `purpose` must be one of the following: `business_icon`, `business_logo`, `customer_signature`, `dispute_evidence`, `finance_report_run`, `pci_document`, `sigma_scheduled_query`, or `tax_document_user_upload`. - pub file: FileId, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> CreateFileLink<'a> { - pub fn new(file: FileId) -> Self { - CreateFileLink { - expand: Default::default(), - expires_at: Default::default(), - file, - metadata: Default::default(), - } - } -} - -/// The parameters for `FileLink::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListFileLinks<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Filter links by their expiration status. - /// - /// By default, all links are returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub expired: Option, - - /// Only return links for the given file. - #[serde(skip_serializing_if = "Option::is_none")] - pub file: Option, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListFileLinks<'a> { - pub fn new() -> Self { - ListFileLinks { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - expired: Default::default(), - file: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `FileLink::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateFileLink<'a> { - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A future timestamp after which the link will no longer be usable, or `now` to expire the link immediately. - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdateFileLink<'a> { - pub fn new() -> Self { - UpdateFileLink { - expand: Default::default(), - expires_at: Default::default(), - metadata: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/invoice.rs b/ft-stripe/src/resources/invoice.rs deleted file mode 100644 index 7311e13..0000000 --- a/ft-stripe/src/resources/invoice.rs +++ /dev/null @@ -1,903 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, InvoiceId, SubscriptionId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Address, Charge, Currency, CustomField, Customer, Discount, InvoiceLineItem, PaymentIntent, - PaymentMethod, PaymentSource, Shipping, Subscription, TaxRate, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Invoice". -/// -/// For more details see [https://stripe.com/docs/api/invoices/object](https://stripe.com/docs/api/invoices/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Invoice { - /// Unique identifier for the object. - #[serde(default = "InvoiceId::none")] - pub id: InvoiceId, - - /// The country of the business associated with this invoice, most often the business creating the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_country: Option, - - /// The public name of the business associated with this invoice, most often the business creating the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub account_name: Option, - - /// Final amount due at this time for this invoice. - /// - /// If the invoice's total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the `amount_due` may be 0. - /// If there is a positive `starting_balance` for the invoice (the customer owes money), the `amount_due` will also take that into account. - /// The charge that gets generated for the invoice will be for the amount specified in `amount_due`. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_due: Option, - - /// The amount, in %s, that was paid. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_paid: Option, - - /// The amount remaining, in %s, that is due. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_remaining: Option, - - /// The fee in %s that will be applied to the invoice and transferred to the application owner's Stripe account when the invoice is paid. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - - /// Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. - /// - /// Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. - /// In other words, manual payment attempts after the first attempt do not affect the retry schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt_count: Option, - - /// Whether an attempt has been made to pay the invoice. - /// - /// An invoice is not attempted until 1 hour after the `invoice.created` webhook, for example, so you might not want to display that invoice as unpaid to your users. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempted: Option, - - /// Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) of the invoice. - /// - /// When `false`, the invoice's state will not automatically advance without an explicit action. - #[serde(skip_serializing_if = "Option::is_none")] - pub auto_advance: Option, - - /// Indicates the reason why the invoice was created. - /// - /// `subscription_cycle` indicates an invoice created by a subscription advancing into a new period. - /// `subscription_create` indicates an invoice created due to creating a subscription. - /// `subscription_update` indicates an invoice created due to updating a subscription. - /// `subscription` is set for all old invoices to indicate either a change to a subscription or a period advancement. - /// `manual` is set for all invoices unrelated to a subscription (for example: created via the invoice editor). - /// The `upcoming` value is reserved for simulated invoices per the upcoming invoice endpoint. - /// `subscription_threshold` indicates an invoice created due to a billing threshold being reached. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_reason: Option, - - /// ID of the latest charge generated for this invoice, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option>, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. - /// When sending an invoice, Stripe will email this invoice to the customer with payment instructions. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// Custom fields displayed on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub custom_fields: Option>, - - /// The ID of the customer who will be billed. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// The customer's address. - /// - /// Until the invoice is finalized, this field will equal `customer.address`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_address: Option
, - - /// The customer's email. - /// - /// Until the invoice is finalized, this field will equal `customer.email`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_email: Option, - - /// The customer's name. - /// - /// Until the invoice is finalized, this field will equal `customer.name`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_name: Option, - - /// The customer's phone number. - /// - /// Until the invoice is finalized, this field will equal `customer.phone`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_phone: Option, - - /// The customer's shipping information. - /// - /// Until the invoice is finalized, this field will equal `customer.shipping`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_shipping: Option, - - /// The customer's tax exempt status. - /// - /// Until the invoice is finalized, this field will equal `customer.tax_exempt`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_tax_exempt: Option, - - /// The customer's tax IDs. - /// - /// Until the invoice is finalized, this field will contain the same tax IDs as `customer.tax_ids`. - /// Once the invoice is finalized, this field will no longer be updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer_tax_ids: Option>, - - /// ID of the default payment method for the invoice. - /// - /// It must belong to the customer associated with the invoice. - /// If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option>, - - /// ID of the default payment source for the invoice. - /// - /// It must belong to the customer associated with the invoice and be in a chargeable state. - /// If not set, defaults to the subscription's default source, if any, or to the customer's default source. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option>, - - /// The tax rates applied to this invoice, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - /// Referenced as 'memo' in the Dashboard. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Describes the current discount applied to this invoice, if there is one. - #[serde(skip_serializing_if = "Option::is_none")] - pub discount: Option, - - /// The date on which payment for this invoice is due. - /// - /// This value will be `null` for invoices where `collection_method=charge_automatically`. - #[serde(skip_serializing_if = "Option::is_none")] - pub due_date: Option, - - /// Ending customer balance after the invoice is finalized. - /// - /// Invoices are finalized approximately an hour after successful webhook delivery or when payment collection is attempted for the invoice. - /// If the invoice has not been finalized yet, this will be null. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_balance: Option, - - /// Footer displayed on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub footer: Option, - - /// The URL for the hosted invoice page, which allows customers to view and pay an invoice. - /// - /// If the invoice has not been finalized yet, this will be null. - #[serde(skip_serializing_if = "Option::is_none")] - pub hosted_invoice_url: Option, - - /// The link to download the PDF for the invoice. - /// - /// If the invoice has not been finalized yet, this will be null. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_pdf: Option, - - /// The individual line items that make up the invoice. - /// - /// `lines` is sorted as follows: invoice items in reverse chronological order, followed by the subscription, if any. - #[serde(default)] - pub lines: List, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The time at which payment will next be attempted. - /// - /// This value will be `null` for invoices where `collection_method=send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_payment_attempt: Option, - - /// A unique, identifying string that appears on emails sent to the customer for this invoice. - /// - /// This starts with the customer's unique invoice_prefix if it is specified. - #[serde(skip_serializing_if = "Option::is_none")] - pub number: Option, - - /// Whether payment was successfully collected for this invoice. - /// - /// An invoice can be paid (most commonly) with a charge or with credit from the customer's account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub paid: Option, - - /// The PaymentIntent associated with this invoice. - /// - /// The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice. - /// Note that voiding an invoice will cancel the PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// End of the usage period during which invoice items were added to this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub period_end: Option, - - /// Start of the usage period during which invoice items were added to this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub period_start: Option, - - /// Total amount of all post-payment credit notes issued for this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub post_payment_credit_notes_amount: Option, - - /// Total amount of all pre-payment credit notes issued for this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub pre_payment_credit_notes_amount: Option, - - /// This is the transaction number that appears on email receipts sent for this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_number: Option, - - /// Starting customer balance before the invoice is finalized. - /// - /// If the invoice has not been finalized yet, this will be the current customer balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_balance: Option, - - /// Extra information about an invoice for the customer's credit card statement. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. - /// - /// [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview). - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub status_transitions: Option, - - /// The subscription that this invoice was prepared for, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option>, - - /// Only set for upcoming invoices that preview prorations. - /// - /// The time used to calculate prorations. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_proration_date: Option, - - /// Total of all subscriptions, invoice items, and prorations on the invoice before any discount or tax is applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub subtotal: Option, - - /// The amount of tax on this invoice. - /// - /// This is the sum of all the tax amounts on this invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax: Option, - - /// This percentage of the subtotal has been added to the total amount of the invoice, including invoice line items and discounts. - /// - /// This field is inherited from the subscription's `tax_percent` field, but can be changed before the invoice is paid. - /// This field defaults to null. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub threshold_reason: Option, - - /// Total after discounts and taxes. - #[serde(skip_serializing_if = "Option::is_none")] - pub total: Option, - - /// The aggregate amounts calculated per tax rate for all line items. - #[serde(skip_serializing_if = "Option::is_none")] - pub total_tax_amounts: Option>, - - /// Invoices are automatically paid or sent 1 hour after webhooks are delivered, or until all webhook delivery attempts have [been exhausted](https://stripe.com/docs/billing/webhooks#understand). - /// - /// This field tracks the time when webhooks for this invoice were successfully delivered. - /// If the invoice had no webhooks to deliver, this will be set while the invoice is being created. - #[serde(skip_serializing_if = "Option::is_none")] - pub webhooks_delivered_at: Option, -} - -impl Invoice { - /// You can list all invoices, or list the invoices for a specific customer. - /// - /// The invoices are returned sorted by creation date, with the most recently created invoices appearing first. - pub fn list(client: &Client, params: ListInvoices<'_>) -> Response> { - client.get_query("/invoices", ¶ms) - } - - /// This endpoint creates a draft invoice for a given customer. - /// - /// The draft invoice created pulls in all pending invoice items on that customer, including prorations. - pub fn create(client: &Client, params: CreateInvoice<'_>) -> Response { - client.post_form("/invoices", ¶ms) - } - - /// Retrieves the invoice with the given ID. - pub fn retrieve(client: &Client, id: &InvoiceId, expand: &[&str]) -> Response { - client.get_query(&format!("/invoices/{}", id), &Expand { expand }) - } -} - -impl Object for Invoice { - type Id = InvoiceId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "invoice" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceSettingCustomField { - /// The name of the custom field. - pub name: String, - - /// The value of the custom field. - pub value: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxAmount { - /// The amount, in %s, of the tax. - pub amount: i64, - - /// Whether this tax amount is inclusive or exclusive. - pub inclusive: bool, - - /// The tax rate that was applied to get this tax amount. - pub tax_rate: Expandable, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceThresholdReason { - /// The total invoice amount threshold boundary if it triggered the threshold invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_gte: Option, - - /// Indicates which line items triggered a threshold invoice. - pub item_reasons: Vec, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItemThresholdReason { - /// The IDs of the line items that triggered the threshold invoice. - pub line_item_ids: Vec, - - /// The quantity threshold boundary that applied to the given line item. - pub usage_gte: i64, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoicesResourceInvoiceTaxId { - /// The type of the tax ID, one of `eu_vat`, `br_cnpj`, `br_cpf`, `nz_gst`, `au_abn`, `in_gst`, `no_vat`, `za_vat`, `ch_vat`, `mx_rfc`, `sg_uen`, `ru_inn`, `ca_bn`, `hk_br`, `es_cif`, `tw_vat`, `th_vat`, `jp_cn`, `li_uid`, `my_itn`, `us_ein`, `kr_brn`, `ca_qst`, `my_sst`, `sg_gst`, or `unknown`. - #[serde(rename = "type")] - pub type_: TaxIdType, - - /// The value of the tax ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub value: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoicesStatusTransitions { - /// The time that the invoice draft was finalized. - #[serde(skip_serializing_if = "Option::is_none")] - pub finalized_at: Option, - - /// The time that the invoice was marked uncollectible. - #[serde(skip_serializing_if = "Option::is_none")] - pub marked_uncollectible_at: Option, - - /// The time that the invoice was paid. - #[serde(skip_serializing_if = "Option::is_none")] - pub paid_at: Option, - - /// The time that the invoice was voided. - #[serde(skip_serializing_if = "Option::is_none")] - pub voided_at: Option, -} - -/// The parameters for `Invoice::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateInvoice<'a> { - /// A fee in %s that will be applied to the invoice and transferred to the application owner's Stripe account. - /// - /// The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. - /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#invoices). - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - - /// Controls whether Stripe will perform [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) of the invoice. - /// - /// When `false`, the invoice's state will not automatically advance without an explicit action. - #[serde(skip_serializing_if = "Option::is_none")] - pub auto_advance: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. - /// When sending an invoice, Stripe will email this invoice to the customer with payment instructions. - /// Defaults to `charge_automatically`. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// A list of up to 4 custom fields to be displayed on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub custom_fields: Option>, - - /// The ID of the customer who will be billed. - pub customer: CustomerId, - - /// The number of days from when the invoice is created until it is due. - /// - /// Valid only for invoices where `collection_method=send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub days_until_due: Option, - - /// ID of the default payment method for the invoice. - /// - /// It must belong to the customer associated with the invoice. - /// If not set, defaults to the subscription's default payment method, if any, or to the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option<&'a str>, - - /// ID of the default payment source for the invoice. - /// - /// It must belong to the customer associated with the invoice and be in a chargeable state. - /// If not set, defaults to the subscription's default source, if any, or to the customer's default source. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option<&'a str>, - - /// The tax rates that will apply to any line item that does not have `tax_rates` set. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - /// Referenced as 'memo' in the Dashboard. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The date on which payment for this invoice is due. - /// - /// Valid only for invoices where `collection_method=send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub due_date: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Footer to be displayed on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub footer: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Extra information about a charge for the customer's credit card statement. - /// - /// It must contain at least one letter. - /// If not specified and this invoice is part of a subscription, the default `statement_descriptor` will be set to the first subscription item's product's `statement_descriptor`. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - - /// The ID of the subscription to invoice, if any. - /// - /// If not set, the created invoice will include all pending invoice items for the customer. - /// If set, the created invoice will only include pending invoice items for that subscription and pending invoice items not associated with any subscription. - /// The subscription's billing cycle and regular subscription events won't be affected. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, - - /// The percent tax rate applied to the invoice, represented as a decimal number. - /// - /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, -} - -impl<'a> CreateInvoice<'a> { - pub fn new(customer: CustomerId) -> Self { - CreateInvoice { - application_fee_amount: Default::default(), - auto_advance: Default::default(), - collection_method: Default::default(), - custom_fields: Default::default(), - customer, - days_until_due: Default::default(), - default_payment_method: Default::default(), - default_source: Default::default(), - default_tax_rates: Default::default(), - description: Default::default(), - due_date: Default::default(), - expand: Default::default(), - footer: Default::default(), - metadata: Default::default(), - statement_descriptor: Default::default(), - subscription: Default::default(), - tax_percent: Default::default(), - } - } -} - -/// The parameters for `Invoice::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListInvoices<'a> { - /// The collection method of the invoice to retrieve. - /// - /// Either `charge_automatically` or `send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return invoices for the customer specified by this customer ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub due_date: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// The status of the invoice, one of `draft`, `open`, `paid`, `uncollectible`, or `void`. - /// - /// [Learn more](https://stripe.com/docs/billing/invoices/workflow#workflow-overview). - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - /// Only return invoices for the subscription specified by this subscription ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, -} - -impl<'a> ListInvoices<'a> { - pub fn new() -> Self { - ListInvoices { - collection_method: Default::default(), - created: Default::default(), - customer: Default::default(), - due_date: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - status: Default::default(), - subscription: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Invoice`'s `collection_method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CollectionMethod { - ChargeAutomatically, - SendInvoice, -} - -impl CollectionMethod { - pub fn as_str(self) -> &'static str { - match self { - CollectionMethod::ChargeAutomatically => "charge_automatically", - CollectionMethod::SendInvoice => "send_invoice", - } - } -} - -impl AsRef for CollectionMethod { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CollectionMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Invoice`'s `billing_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum InvoiceBillingReason { - AutomaticPendingInvoiceItemInvoice, - Manual, - Subscription, - SubscriptionCreate, - SubscriptionCycle, - SubscriptionThreshold, - SubscriptionUpdate, - Upcoming, -} - -impl InvoiceBillingReason { - pub fn as_str(self) -> &'static str { - match self { - InvoiceBillingReason::AutomaticPendingInvoiceItemInvoice => { - "automatic_pending_invoice_item_invoice" - } - InvoiceBillingReason::Manual => "manual", - InvoiceBillingReason::Subscription => "subscription", - InvoiceBillingReason::SubscriptionCreate => "subscription_create", - InvoiceBillingReason::SubscriptionCycle => "subscription_cycle", - InvoiceBillingReason::SubscriptionThreshold => "subscription_threshold", - InvoiceBillingReason::SubscriptionUpdate => "subscription_update", - InvoiceBillingReason::Upcoming => "upcoming", - } - } -} - -impl AsRef for InvoiceBillingReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for InvoiceBillingReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Invoice`'s `customer_tax_exempt` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum InvoiceCustomerTaxExempt { - Exempt, - None, - Reverse, -} - -impl InvoiceCustomerTaxExempt { - pub fn as_str(self) -> &'static str { - match self { - InvoiceCustomerTaxExempt::Exempt => "exempt", - InvoiceCustomerTaxExempt::None => "none", - InvoiceCustomerTaxExempt::Reverse => "reverse", - } - } -} - -impl AsRef for InvoiceCustomerTaxExempt { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for InvoiceCustomerTaxExempt { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Invoice`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum InvoiceStatus { - Deleted, - Draft, - Open, - Paid, - Uncollectible, - Void, -} - -impl InvoiceStatus { - pub fn as_str(self) -> &'static str { - match self { - InvoiceStatus::Deleted => "deleted", - InvoiceStatus::Draft => "draft", - InvoiceStatus::Open => "open", - InvoiceStatus::Paid => "paid", - InvoiceStatus::Uncollectible => "uncollectible", - InvoiceStatus::Void => "void", - } - } -} - -impl AsRef for InvoiceStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for InvoiceStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListInvoices`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum InvoiceStatusFilter { - Draft, - Open, - Paid, - Uncollectible, - Void, -} - -impl InvoiceStatusFilter { - pub fn as_str(self) -> &'static str { - match self { - InvoiceStatusFilter::Draft => "draft", - InvoiceStatusFilter::Open => "open", - InvoiceStatusFilter::Paid => "paid", - InvoiceStatusFilter::Uncollectible => "uncollectible", - InvoiceStatusFilter::Void => "void", - } - } -} - -impl AsRef for InvoiceStatusFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for InvoiceStatusFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `InvoicesResourceInvoiceTaxId`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TaxIdType { - AuAbn, - BrCnpj, - BrCpf, - CaBn, - CaQst, - ChVat, - EsCif, - EuVat, - HkBr, - InGst, - JpCn, - KrBrn, - LiUid, - MxRfc, - MyItn, - MySst, - NoVat, - NzGst, - RuInn, - SgGst, - SgUen, - ThVat, - TwVat, - Unknown, - UsEin, - ZaVat, -} - -impl TaxIdType { - pub fn as_str(self) -> &'static str { - match self { - TaxIdType::AuAbn => "au_abn", - TaxIdType::BrCnpj => "br_cnpj", - TaxIdType::BrCpf => "br_cpf", - TaxIdType::CaBn => "ca_bn", - TaxIdType::CaQst => "ca_qst", - TaxIdType::ChVat => "ch_vat", - TaxIdType::EsCif => "es_cif", - TaxIdType::EuVat => "eu_vat", - TaxIdType::HkBr => "hk_br", - TaxIdType::InGst => "in_gst", - TaxIdType::JpCn => "jp_cn", - TaxIdType::KrBrn => "kr_brn", - TaxIdType::LiUid => "li_uid", - TaxIdType::MxRfc => "mx_rfc", - TaxIdType::MyItn => "my_itn", - TaxIdType::MySst => "my_sst", - TaxIdType::NoVat => "no_vat", - TaxIdType::NzGst => "nz_gst", - TaxIdType::RuInn => "ru_inn", - TaxIdType::SgGst => "sg_gst", - TaxIdType::SgUen => "sg_uen", - TaxIdType::ThVat => "th_vat", - TaxIdType::TwVat => "tw_vat", - TaxIdType::Unknown => "unknown", - TaxIdType::UsEin => "us_ein", - TaxIdType::ZaVat => "za_vat", - } - } -} - -impl AsRef for TaxIdType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TaxIdType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/invoice_ext.rs b/ft-stripe/src/resources/invoice_ext.rs deleted file mode 100644 index c3fb306..0000000 --- a/ft-stripe/src/resources/invoice_ext.rs +++ /dev/null @@ -1,73 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{CouponId, CustomerId, InvoiceId, PlanId, SubscriptionId, SubscriptionItemId}; -use crate::params::{Metadata, Timestamp}; -use crate::resources::{CollectionMethod, Invoice}; -use serde::Serialize; - -#[deprecated(since = "0.12.0")] -pub type InvoiceCollectionMethod = CollectionMethod; - -impl Invoice { - /// Retrieves the details of an upcoming invoice_id - /// - /// For more details see https://stripe.com/docs/api#upcoming_invoice - pub fn upcoming(client: &Client, params: RetrieveUpcomingInvoice) -> Response { - client.get_query("/invoices/upcoming", ¶ms) - } - - /// Pays an invoice. - /// - /// For more details see https://stripe.com/docs/api#pay_invoice. - pub fn pay(client: &Client, invoice_id: &InvoiceId) -> Response { - client.post(&format!("/invoices/{}/pay", invoice_id)) - } -} - -#[derive(Clone, Debug, Serialize)] -pub struct RetrieveUpcomingInvoice { - pub customer: CustomerId, // this is a required param - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_items: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_prorate: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_proration_date: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_tax_percent: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_trial_end: Option, -} - -impl RetrieveUpcomingInvoice { - pub fn new(customer: CustomerId) -> Self { - RetrieveUpcomingInvoice { - customer, - coupon: None, - subscription: None, - subscription_items: None, - subscription_prorate: None, - subscription_proration_date: None, - subscription_tax_percent: None, - subscription_trial_end: None, - } - } -} - -#[derive(Clone, Debug, Serialize)] -pub struct SubscriptionItemFilter { - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub deleted: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, -} diff --git a/ft-stripe/src/resources/invoiceitem.rs b/ft-stripe/src/resources/invoiceitem.rs deleted file mode 100644 index 91bf089..0000000 --- a/ft-stripe/src/resources/invoiceitem.rs +++ /dev/null @@ -1,453 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, InvoiceId, InvoiceItemId, PriceId, SubscriptionId}; -use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{Currency, Customer, Invoice, Period, Plan, Price, Subscription, TaxRate}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "InvoiceItem". -/// -/// For more details see [https://stripe.com/docs/api/invoiceitems/object](https://stripe.com/docs/api/invoiceitems/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItem { - /// Unique identifier for the object. - pub id: InvoiceItemId, - - /// Amount (in the `currency` specified) of the invoice item. - /// - /// This should always be equal to `unit_amount * quantity`. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The ID of the customer who will be billed when this invoice item is billed. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// If true, discounts will apply to this invoice item. - /// - /// Always false for prorations. - #[serde(skip_serializing_if = "Option::is_none")] - pub discountable: Option, - - /// The ID of the invoice this invoice item belongs to. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub period: Option, - - /// If the invoice item is a proration, the plan of the subscription that the proration was computed for. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// The price of the invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Whether the invoice item was created automatically as a proration adjustment when the customer switched plans. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration: Option, - - /// Quantity of units for the invoice item. - /// - /// If the invoice item is a proration, the quantity of the subscription that the proration was computed for. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The subscription that this invoice item has been created for, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option>, - - /// The subscription item that this invoice item has been created for, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_item: Option, - - /// The tax rates which apply to the invoice item. - /// - /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, - - /// Unit Amount (in the `currency` specified) of the invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -impl InvoiceItem { - /// Returns a list of your invoice items. - /// - /// Invoice items are returned sorted by creation date, with the most recently created invoice items appearing first. - pub fn list(client: &Client, params: ListInvoiceItems<'_>) -> Response> { - client.get_query("/invoiceitems", ¶ms) - } - - /// Creates an item to be added to a draft invoice. - /// - /// If no invoice is specified, the item will be on the next invoice created for the customer specified. - pub fn create(client: &Client, params: CreateInvoiceItem<'_>) -> Response { - client.post_form("/invoiceitems", ¶ms) - } - - /// Retrieves the invoice item with the given ID. - pub fn retrieve(client: &Client, id: &InvoiceItemId, expand: &[&str]) -> Response { - client.get_query(&format!("/invoiceitems/{}", id), &Expand { expand }) - } - - /// Updates the amount or description of an invoice item on an upcoming invoice. - /// - /// Updating an invoice item is only possible before the invoice it’s attached to is closed. - pub fn update( - client: &Client, - id: &InvoiceItemId, - params: UpdateInvoiceItem<'_>, - ) -> Response { - client.post_form(&format!("/invoiceitems/{}", id), ¶ms) - } - - /// Deletes an invoice item, removing it from an invoice. - /// - /// Deleting invoice items is only possible when they’re not attached to invoices, or if it’s attached to a draft invoice. - pub fn delete(client: &Client, id: &InvoiceItemId) -> Response> { - client.delete(&format!("/invoiceitems/{}", id)) - } -} - -impl Object for InvoiceItem { - type Id = InvoiceItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "invoiceitem" - } -} - -/// The parameters for `InvoiceItem::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateInvoiceItem<'a> { - /// The integer amount in **%s** of the charge to be applied to the upcoming invoice. - /// - /// Passing in a negative `amount` will reduce the `amount_due` on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The ID of the customer who will be billed when this invoice item is billed. - pub customer: CustomerId, - - /// An arbitrary string which you can attach to the invoice item. - /// - /// The description is displayed in the invoice for easy tracking. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Controls whether discounts apply to this invoice item. - /// - /// Defaults to false for prorations or negative invoice items, and true for all other invoice items. - #[serde(skip_serializing_if = "Option::is_none")] - pub discountable: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The ID of an existing invoice to add this invoice item to. - /// - /// When left blank, the invoice item will be added to the next upcoming scheduled invoice. - /// This is useful when adding invoice items in response to an invoice.created webhook. - /// You can only add invoice items to draft invoices. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The period associated with this invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub period: Option, - - /// The ID of the price object. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Data used to generate a new price object inline. - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - /// Non-negative integer. - /// - /// The quantity of units for the invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The ID of a subscription to add this invoice item to. - /// - /// When left blank, the invoice item will be be added to the next upcoming scheduled invoice. - /// When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. - /// Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, - - /// The tax rates which apply to the invoice item. - /// - /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, - - /// The integer unit amount in **%s** of the charge to be applied to the upcoming invoice. - /// - /// This `unit_amount` will be multiplied by the quantity to get the full amount. - /// Passing in a negative `unit_amount` will reduce the `amount_due` on the invoice. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. - /// - /// Only one of `unit_amount` and `unit_amount_decimal` can be set. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option<&'a str>, -} - -impl<'a> CreateInvoiceItem<'a> { - pub fn new(customer: CustomerId) -> Self { - CreateInvoiceItem { - amount: Default::default(), - currency: Default::default(), - customer, - description: Default::default(), - discountable: Default::default(), - expand: Default::default(), - invoice: Default::default(), - metadata: Default::default(), - period: Default::default(), - price: Default::default(), - price_data: Default::default(), - quantity: Default::default(), - subscription: Default::default(), - tax_rates: Default::default(), - unit_amount: Default::default(), - unit_amount_decimal: Default::default(), - } - } -} - -/// The parameters for `InvoiceItem::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListInvoiceItems<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// The identifier of the customer whose invoice items to return. - /// - /// If none is provided, all invoice items will be returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Only return invoice items belonging to this invoice. - /// - /// If none is provided, all invoice items will be returned. - /// If specifying an invoice, no customer identifier is needed. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Set to `true` to only show pending invoice items, which are not yet attached to any invoices. - /// - /// Set to `false` to only show invoice items already attached to invoices. - /// If unspecified, no filter is applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListInvoiceItems<'a> { - pub fn new() -> Self { - ListInvoiceItems { - created: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - invoice: Default::default(), - limit: Default::default(), - pending: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `InvoiceItem::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateInvoiceItem<'a> { - /// The integer amount in **%s** of the charge to be applied to the upcoming invoice. - /// - /// If you want to apply a credit to the customer's account, pass a negative amount. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// An arbitrary string which you can attach to the invoice item. - /// - /// The description is displayed in the invoice for easy tracking. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Controls whether discounts apply to this invoice item. - /// - /// Defaults to false for prorations or negative invoice items, and true for all other invoice items. - /// Cannot be set to true for prorations. - #[serde(skip_serializing_if = "Option::is_none")] - pub discountable: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The period associated with this invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub period: Option, - - /// The ID of the price object. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Data used to generate a new price object inline. - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - /// Non-negative integer. - /// - /// The quantity of units for the invoice item. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The tax rates which apply to the invoice item. - /// - /// When set, the `default_tax_rates` on the invoice do not apply to this invoice item. - /// Pass an empty string to remove previously-defined tax rates. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, - - /// The integer unit amount in **%s** of the charge to be applied to the upcoming invoice. - /// - /// This unit_amount will be multiplied by the quantity to get the full amount. - /// If you want to apply a credit to the customer's account, pass a negative unit_amount. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. - /// - /// Only one of `unit_amount` and `unit_amount_decimal` can be set. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option<&'a str>, -} - -impl<'a> UpdateInvoiceItem<'a> { - pub fn new() -> Self { - UpdateInvoiceItem { - amount: Default::default(), - description: Default::default(), - discountable: Default::default(), - expand: Default::default(), - metadata: Default::default(), - period: Default::default(), - price: Default::default(), - price_data: Default::default(), - quantity: Default::default(), - tax_rates: Default::default(), - unit_amount: Default::default(), - unit_amount_decimal: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItemPriceData { - pub currency: Currency, - - pub product: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} diff --git a/ft-stripe/src/resources/issuing_authorization.rs b/ft-stripe/src/resources/issuing_authorization.rs deleted file mode 100644 index 6bf0094..0000000 --- a/ft-stripe/src/resources/issuing_authorization.rs +++ /dev/null @@ -1,208 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::IssuingAuthorizationId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{ - BalanceTransaction, Currency, IssuingAuthorizationCheck, IssuingAuthorizationMethod, - IssuingAuthorizationReason, IssuingCard, IssuingCardholder, IssuingTransaction, MerchantData, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingAuthorization". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingAuthorization { - /// Unique identifier for the object. - pub id: IssuingAuthorizationId, - - /// The total amount that was authorized or rejected. - /// - /// This amount is in the card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub amount: i64, - - /// Whether the authorization has been approved. - pub approved: bool, - - /// How the card details were provided. - pub authorization_method: IssuingAuthorizationMethod, - - /// List of balance transactions associated with this authorization. - pub balance_transactions: Vec, - - pub card: IssuingCard, - - /// The cardholder to whom this authorization belongs. - #[serde(skip_serializing_if = "Option::is_none")] - pub cardholder: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// The total amount that was authorized or rejected. - /// - /// This amount is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub merchant_amount: i64, - - /// The currency that was presented to the cardholder for the authorization. - /// - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub merchant_currency: Currency, - - pub merchant_data: MerchantData, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The pending authorization request. - /// - /// This field will only be non-null during an `issuing_authorization.request` webhook. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_request: Option, - - /// History of every time the authorization was approved/denied (whether approved/denied by you directly or by Stripe based on your `spending_controls`). - /// - /// If the merchant changes the authorization by performing an [incremental authorization or partial capture](https://stripe.com/docs/issuing/purchases/authorizations), you can look at this field to see the previous states of the authorization. - pub request_history: Vec, - - /// The current status of the authorization in its lifecycle. - pub status: IssuingAuthorizationStatus, - - /// List of [transactions](https://stripe.com/docs/api/issuing/transactions) associated with this authorization. - pub transactions: Vec, - - pub verification_data: IssuingAuthorizationVerificationData, - - /// What, if any, digital wallet was used for this authorization. - /// - /// One of `apple_pay`, `google_pay`, or `samsung_pay`. - #[serde(skip_serializing_if = "Option::is_none")] - pub wallet: Option, -} - -impl Object for IssuingAuthorization { - type Id = IssuingAuthorizationId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.authorization" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingAuthorizationPendingRequest { - /// The additional amount Stripe will hold if the authorization is approved, in the card's [currency](https://stripe.com/docs/api#issuing_authorization_object-pending-request-currency) and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// If set `true`, you may provide [amount](https://stripe.com/docs/api/issuing/authorizations/approve#approve_issuing_authorization-amount) to control how much to hold for the authorization. - pub is_amount_controllable: bool, - - /// The amount the merchant is requesting to be authorized in the `merchant_currency`. - /// - /// The amount is in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub merchant_amount: i64, - - /// The local currency the merchant is requesting to authorize. - pub merchant_currency: Currency, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingAuthorizationRequest { - /// The authorization amount in your card's currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - /// - /// Stripe held this amount from your account to fund the authorization if the request was approved. - pub amount: i64, - - /// Whether this request was approved. - pub approved: bool, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The amount that was authorized at the time of this request. - /// - /// This amount is in the `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub merchant_amount: i64, - - /// The currency that was collected by the merchant and presented to the cardholder for the authorization. - /// - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub merchant_currency: Currency, - - /// The reason for the approval or decline. - pub reason: IssuingAuthorizationReason, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingAuthorizationVerificationData { - /// Whether the cardholder provided an address first line and if it matched the cardholder’s `billing.address.line1`. - pub address_line1_check: IssuingAuthorizationCheck, - - /// Whether the cardholder provided a postal code and if it matched the cardholder’s `billing.address.postal_code`. - pub address_postal_code_check: IssuingAuthorizationCheck, - - /// Whether the cardholder provided a CVC and if it matched Stripe’s record. - pub cvc_check: IssuingAuthorizationCheck, - - /// Whether the cardholder provided an expiry date and if it matched Stripe’s record. - pub expiry_check: IssuingAuthorizationCheck, -} - -/// An enum representing the possible values of an `IssuingAuthorization`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingAuthorizationStatus { - Closed, - Pending, - Reversed, -} - -impl IssuingAuthorizationStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingAuthorizationStatus::Closed => "closed", - IssuingAuthorizationStatus::Pending => "pending", - IssuingAuthorizationStatus::Reversed => "reversed", - } - } -} - -impl AsRef for IssuingAuthorizationStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingAuthorizationStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_authorization_ext.rs b/ft-stripe/src/resources/issuing_authorization_ext.rs deleted file mode 100644 index a812a2c..0000000 --- a/ft-stripe/src/resources/issuing_authorization_ext.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of the `IssuingAuthorizationVerificationData` fields. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingAuthorizationCheck { - Match, - Mismatch, - NotProvided, -} - -/// An enum representing the possible values of the `IssuingAuthorization`'s `authorization_method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingAuthorizationMethod { - KeyedIn, - Swipe, - Chip, - Contactless, - Online, -} - -/// An enum representing the possible values of the `IssuingAuthorizationRequest`'s `reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingAuthorizationReason { - AuthenticationFailed, - AuthorizationControls, - CardActive, - CardInactive, - InsufficientFunds, - AccountComplianceDisabled, - AccountInactive, - SuspectedFraud, - WebhookApproved, - WebhookDeclined, - WebhookTimeout, -} - -/// An enum representing the possible values of an `IssuingAuthorization`'s `wallet_provider` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingAuthorizationWalletProvider { - ApplePay, - GooglePay, - SamsungPay, -} - -impl IssuingAuthorizationWalletProvider { - pub fn as_str(self) -> &'static str { - match self { - IssuingAuthorizationWalletProvider::ApplePay => "apple_pay", - IssuingAuthorizationWalletProvider::GooglePay => "google_pay", - IssuingAuthorizationWalletProvider::SamsungPay => "samsung_pay", - } - } -} - -impl AsRef for IssuingAuthorizationWalletProvider { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingAuthorizationWalletProvider { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_card.rs b/ft-stripe/src/resources/issuing_card.rs deleted file mode 100644 index 95767d5..0000000 --- a/ft-stripe/src/resources/issuing_card.rs +++ /dev/null @@ -1,313 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::IssuingCardId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{ - Address, CardBrand, Currency, IssuingCardShippingStatus, IssuingCardShippingType, - IssuingCardType, IssuingCardholder, MerchantCategory, SpendingLimit, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingCard". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCard { - /// Unique identifier for the object. - pub id: IssuingCardId, - - /// The brand of the card. - pub brand: CardBrand, - - /// The reason why the card was canceled. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_reason: Option, - - pub cardholder: IssuingCardholder, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The card's CVC. - /// - /// For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). - /// Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc: Option, - - /// The expiration month of the card. - pub exp_month: i64, - - /// The expiration year of the card. - pub exp_year: i64, - - /// The last 4 digits of the card number. - pub last4: String, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The full unredacted card number. - /// - /// For security reasons, this is only available for virtual cards, and will be omitted unless you explicitly request it with [the `expand` parameter](https://stripe.com/docs/api/expanding_objects). - /// Additionally, it's only available via the ["Retrieve a card" endpoint](https://stripe.com/docs/api/issuing/cards/retrieve), not via "List all cards" or any other endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub number: Option, - - /// The latest card that replaces this card, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub replaced_by: Option>, - - /// The card this card replaces, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub replacement_for: Option>, - - /// The reason why the previous card needed to be replaced. - #[serde(skip_serializing_if = "Option::is_none")] - pub replacement_reason: Option, - - /// Where and how the card will be shipped. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - pub spending_controls: IssuingCardAuthorizationControls, - - /// Whether authorizations can be approved on this card. - pub status: IssuingCardStatus, - - /// The type of the card. - #[serde(rename = "type")] - pub type_: IssuingCardType, -} - -impl Object for IssuingCard { - type Id = IssuingCardId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.card" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardAuthorizationControls { - /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations permitted on this card. - #[serde(skip_serializing_if = "Option::is_none")] - pub allowed_categories: Option>, - - /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to always decline on this card. - #[serde(skip_serializing_if = "Option::is_none")] - pub blocked_categories: Option>, - - /// Limit the spending with rules based on time intervals and categories. - #[serde(skip_serializing_if = "Option::is_none")] - pub spending_limits: Option>, - - /// Currency for the amounts within spending_limits. - /// - /// Locked to the currency of the card. - #[serde(skip_serializing_if = "Option::is_none")] - pub spending_limits_currency: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardShipping { - pub address: Address, - - /// The delivery company that shipped a card. - #[serde(skip_serializing_if = "Option::is_none")] - pub carrier: Option, - - /// A unix timestamp representing a best estimate of when the card will be delivered. - #[serde(skip_serializing_if = "Option::is_none")] - pub eta: Option, - - /// Recipient name. - pub name: String, - - /// Shipment service, such as `standard` or `express`. - pub service: IssuingCardShippingService, - - /// The delivery status of the card. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - /// A tracking number for a card shipment. - #[serde(skip_serializing_if = "Option::is_none")] - pub tracking_number: Option, - - /// A link to the shipping carrier's site where you can view detailed information about a card shipment. - #[serde(skip_serializing_if = "Option::is_none")] - pub tracking_url: Option, - - /// Packaging options. - #[serde(rename = "type")] - pub type_: IssuingCardShippingType, -} - -/// An enum representing the possible values of an `IssuingCard`'s `cancellation_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardCancellationReason { - Lost, - Stolen, -} - -impl IssuingCardCancellationReason { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardCancellationReason::Lost => "lost", - IssuingCardCancellationReason::Stolen => "stolen", - } - } -} - -impl AsRef for IssuingCardCancellationReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardCancellationReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCard`'s `replacement_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardReplacementReason { - Damaged, - Expired, - Lost, - Stolen, -} - -impl IssuingCardReplacementReason { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardReplacementReason::Damaged => "damaged", - IssuingCardReplacementReason::Expired => "expired", - IssuingCardReplacementReason::Lost => "lost", - IssuingCardReplacementReason::Stolen => "stolen", - } - } -} - -impl AsRef for IssuingCardReplacementReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardReplacementReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardShipping`'s `carrier` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardShippingCarrier { - Fedex, - Usps, -} - -impl IssuingCardShippingCarrier { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardShippingCarrier::Fedex => "fedex", - IssuingCardShippingCarrier::Usps => "usps", - } - } -} - -impl AsRef for IssuingCardShippingCarrier { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardShippingCarrier { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardShipping`'s `service` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardShippingService { - Express, - Priority, - Standard, -} - -impl IssuingCardShippingService { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardShippingService::Express => "express", - IssuingCardShippingService::Priority => "priority", - IssuingCardShippingService::Standard => "standard", - } - } -} - -impl AsRef for IssuingCardShippingService { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardShippingService { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCard`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardStatus { - Active, - Canceled, - Inactive, -} - -impl IssuingCardStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardStatus::Active => "active", - IssuingCardStatus::Canceled => "canceled", - IssuingCardStatus::Inactive => "inactive", - } - } -} - -impl AsRef for IssuingCardStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_card_ext.rs b/ft-stripe/src/resources/issuing_card_ext.rs deleted file mode 100644 index 3199ea2..0000000 --- a/ft-stripe/src/resources/issuing_card_ext.rs +++ /dev/null @@ -1,126 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `IssuingCardPin`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardPinStatus { - Active, - Blocked, -} - -impl IssuingCardPinStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardPinStatus::Active => "active", - IssuingCardPinStatus::Blocked => "blocked", - } - } -} - -impl AsRef for IssuingCardPinStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardPinStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardShipping`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardShippingStatus { - Canceled, - Delivered, - Failure, - Pending, - Returned, - Shipped, -} - -impl IssuingCardShippingStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardShippingStatus::Canceled => "canceled", - IssuingCardShippingStatus::Delivered => "delivered", - IssuingCardShippingStatus::Failure => "failure", - IssuingCardShippingStatus::Pending => "pending", - IssuingCardShippingStatus::Returned => "returned", - IssuingCardShippingStatus::Shipped => "shipped", - } - } -} - -impl AsRef for IssuingCardShippingStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardShippingStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardShipping`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardShippingType { - Bulk, - Individual, -} - -impl IssuingCardShippingType { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardShippingType::Bulk => "bulk", - IssuingCardShippingType::Individual => "individual", - } - } -} - -impl AsRef for IssuingCardShippingType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardShippingType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCard`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardType { - Physical, - Virtual, -} - -impl IssuingCardType { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardType::Physical => "physical", - IssuingCardType::Virtual => "virtual", - } - } -} - -impl AsRef for IssuingCardType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_cardholder.rs b/ft-stripe/src/resources/issuing_cardholder.rs deleted file mode 100644 index bd86c6e..0000000 --- a/ft-stripe/src/resources/issuing_cardholder.rs +++ /dev/null @@ -1,308 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::IssuingCardholderId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{Address, Currency, File, MerchantCategory, SpendingLimit}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingCardholder". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholder { - /// Unique identifier for the object. - pub id: IssuingCardholderId, - - pub billing: IssuingCardholderAddress, - - /// Additional information about a `company` cardholder. - #[serde(skip_serializing_if = "Option::is_none")] - pub company: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// The cardholder's email address. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// Additional information about an `individual` cardholder. - #[serde(skip_serializing_if = "Option::is_none")] - pub individual: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The cardholder's name. - /// - /// This will be printed on cards issued to them. - pub name: String, - - /// The cardholder's phone number. - #[serde(skip_serializing_if = "Option::is_none")] - pub phone_number: Option, - - pub requirements: IssuingCardholderRequirements, - - /// Spending rules that give you some control over how this cardholder's cards can be used. - /// - /// Refer to our [authorizations](https://stripe.com/docs/issuing/purchases/authorizations) documentation for more details. - #[serde(skip_serializing_if = "Option::is_none")] - pub spending_controls: Option, - - /// Specifies whether to permit authorizations on this cardholder's cards. - pub status: IssuingCardholderStatus, - - /// One of `individual` or `company`. - #[serde(rename = "type")] - pub type_: IssuingCardholderType, -} - -impl Object for IssuingCardholder { - type Id = IssuingCardholderId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.cardholder" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderAddress { - pub address: Address, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderAuthorizationControls { - /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations permitted on this cardholder's cards. - #[serde(skip_serializing_if = "Option::is_none")] - pub allowed_categories: Option>, - - /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) of authorizations to always decline on this cardholder's cards. - #[serde(skip_serializing_if = "Option::is_none")] - pub blocked_categories: Option>, - - /// Limit the spending with rules based on time intervals and categories. - #[serde(skip_serializing_if = "Option::is_none")] - pub spending_limits: Option>, - - /// Currency for the amounts within spending_limits. - #[serde(skip_serializing_if = "Option::is_none")] - pub spending_limits_currency: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderCompany { - /// Whether the company's business ID number was provided. - pub tax_id_provided: bool, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderIndividual { - /// The date of birth of this cardholder. - #[serde(skip_serializing_if = "Option::is_none")] - pub dob: Option, - - /// The first name of this cardholder. - pub first_name: String, - - /// The last name of this cardholder. - pub last_name: String, - - /// Government-issued ID document for this cardholder. - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderIndividualDob { - /// The day of birth, between 1 and 31. - #[serde(skip_serializing_if = "Option::is_none")] - pub day: Option, - - /// The month of birth, between 1 and 12. - #[serde(skip_serializing_if = "Option::is_none")] - pub month: Option, - - /// The four-digit year of birth. - #[serde(skip_serializing_if = "Option::is_none")] - pub year: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderRequirements { - /// If `disabled_reason` is present, all cards will decline authorizations with `cardholder_verification_required` reason. - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_reason: Option, - - /// Array of fields that need to be collected in order to verify and re-enable the cardholder. - #[serde(skip_serializing_if = "Option::is_none")] - pub past_due: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderVerification { - /// An identifying document, either a passport or local ID card. - #[serde(skip_serializing_if = "Option::is_none")] - pub document: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholderIdDocument { - /// The back of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. - #[serde(skip_serializing_if = "Option::is_none")] - pub back: Option>, - - /// The front of a document returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. - #[serde(skip_serializing_if = "Option::is_none")] - pub front: Option>, -} - -/// An enum representing the possible values of an `IssuingCardholderRequirements`'s `disabled_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardholderRequirementsDisabledReason { - Listed, - #[serde(rename = "rejected.listed")] - RejectedListed, - UnderReview, -} - -impl IssuingCardholderRequirementsDisabledReason { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardholderRequirementsDisabledReason::Listed => "listed", - IssuingCardholderRequirementsDisabledReason::RejectedListed => "rejected.listed", - IssuingCardholderRequirementsDisabledReason::UnderReview => "under_review", - } - } -} - -impl AsRef for IssuingCardholderRequirementsDisabledReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardholderRequirementsDisabledReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardholderRequirements`'s `past_due` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardholderRequirementsPastDue { - #[serde(rename = "company.tax_id")] - CompanyTaxId, - #[serde(rename = "individual.dob.day")] - IndividualDobDay, - #[serde(rename = "individual.dob.month")] - IndividualDobMonth, - #[serde(rename = "individual.dob.year")] - IndividualDobYear, - #[serde(rename = "individual.first_name")] - IndividualFirstName, - #[serde(rename = "individual.last_name")] - IndividualLastName, - #[serde(rename = "individual.verification.document")] - IndividualVerificationDocument, -} - -impl IssuingCardholderRequirementsPastDue { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardholderRequirementsPastDue::CompanyTaxId => "company.tax_id", - IssuingCardholderRequirementsPastDue::IndividualDobDay => "individual.dob.day", - IssuingCardholderRequirementsPastDue::IndividualDobMonth => "individual.dob.month", - IssuingCardholderRequirementsPastDue::IndividualDobYear => "individual.dob.year", - IssuingCardholderRequirementsPastDue::IndividualFirstName => "individual.first_name", - IssuingCardholderRequirementsPastDue::IndividualLastName => "individual.last_name", - IssuingCardholderRequirementsPastDue::IndividualVerificationDocument => { - "individual.verification.document" - } - } - } -} - -impl AsRef for IssuingCardholderRequirementsPastDue { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardholderRequirementsPastDue { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardholder`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardholderStatus { - Active, - Blocked, - Inactive, -} - -impl IssuingCardholderStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardholderStatus::Active => "active", - IssuingCardholderStatus::Blocked => "blocked", - IssuingCardholderStatus::Inactive => "inactive", - } - } -} - -impl AsRef for IssuingCardholderStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardholderStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingCardholder`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingCardholderType { - Company, - Individual, -} - -impl IssuingCardholderType { - pub fn as_str(self) -> &'static str { - match self { - IssuingCardholderType::Company => "company", - IssuingCardholderType::Individual => "individual", - } - } -} - -impl AsRef for IssuingCardholderType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingCardholderType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_dispute.rs b/ft-stripe/src/resources/issuing_dispute.rs deleted file mode 100644 index 2325775..0000000 --- a/ft-stripe/src/resources/issuing_dispute.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::IssuingDisputeId; -use crate::params::Object; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingDispute". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingDispute { - /// Unique identifier for the object. - pub id: IssuingDisputeId, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, -} - -impl Object for IssuingDispute { - type Id = IssuingDisputeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.dispute" - } -} diff --git a/ft-stripe/src/resources/issuing_dispute_ext.rs b/ft-stripe/src/resources/issuing_dispute_ext.rs deleted file mode 100644 index 6ba0e72..0000000 --- a/ft-stripe/src/resources/issuing_dispute_ext.rs +++ /dev/null @@ -1,64 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `IssuingDispute`'s `reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingDisputeReason { - Fraudulent, - Other, -} - -impl IssuingDisputeReason { - pub fn as_str(self) -> &'static str { - match self { - IssuingDisputeReason::Fraudulent => "fraudulent", - IssuingDisputeReason::Other => "other", - } - } -} - -impl AsRef for IssuingDisputeReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingDisputeReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `IssuingDispute`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingDisputeStatus { - Lost, - UnderReview, - Unsubmitted, - Won, -} - -impl IssuingDisputeStatus { - pub fn as_str(self) -> &'static str { - match self { - IssuingDisputeStatus::Lost => "lost", - IssuingDisputeStatus::UnderReview => "under_review", - IssuingDisputeStatus::Unsubmitted => "unsubmitted", - IssuingDisputeStatus::Won => "won", - } - } -} - -impl AsRef for IssuingDisputeStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingDisputeStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/issuing_merchant_data.rs b/ft-stripe/src/resources/issuing_merchant_data.rs deleted file mode 100644 index 7f37dc2..0000000 --- a/ft-stripe/src/resources/issuing_merchant_data.rs +++ /dev/null @@ -1,326 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingAuthorizationMerchantData". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MerchantData { - /// Identifier assigned to the seller by the card brand. - pub network_id: String, - - /// A categorization of the seller's type of business. - /// - /// See the [merchant categories guide](https://stripe.com/docs/issuing/merchant-categories) for a list of possible values. - pub category: MerchantCategory, - - /// Name of the seller. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// City where the seller is located. - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option, - - /// State where the seller is located. - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - - /// Country where the seller is located. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Postal code where the seller is located. - #[serde(skip_serializing_if = "Option::is_none")] - pub postal_code: Option, -} - -/// An enum representing the industry of a merchant. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum MerchantCategory { - AcRefrigerationRepair, - AccountingBookkeepingServices, - AdvertisingServices, - AgriculturalCooperative, - AirlinesAirCarriers, - AirportsFlyingFields, - AmbulanceServices, - AmusementParksCarnivals, - AntiqueReproductions, - AntiqueShops, - Aquariums, - ArchitecturalSurveyingServices, - ArtDealersAndGalleries, - ArtistsSupplyAndCraftShops, - AutoAndHomeSupplyStores, - AutoBodyRepairShops, - AutoPaintShops, - AutoServiceShops, - AutomatedCashDisburse, - AutomatedFuelDispensers, - AutomobileAssociations, - AutomotivePartsAndAccessoriesStores, - AutomotiveTireStores, - BailAndBondPayments, - Bakeries, - BandsOrchestras, - BarberAndBeautyShops, - BettingCasinoGambling, - BicycleShops, - BilliardPoolEstablishments, - BoatDealers, - BoatRentalsAndLeases, - BookStores, - BooksPeriodicalsAndNewspapers, - BowlingAlleys, - BusLines, - BusinessSecretarialSchools, - BuyingShoppingServices, - CableSatelliteAndOtherPayTelevisionAndRadio, - CameraAndPhotographicSupplyStores, - CandyNutAndConfectioneryStores, - CarAndTruckDealersNewUsed, - CarAndTruckDealersUsedOnly, - CarRentalAgencies, - CarWashes, - CarpentryServices, - CarpetUpholsteryCleaning, - Caterers, - CharitableAndSocialServiceOrganizationsFundraising, - ChemicalsAndAlliedProducts, - ChidrensAndInfantsWearStores, - ChildCareServices, - ChiropodistsPodiatrists, - Chiropractors, - CigarStoresAndStands, - CivicSocialFraternalAssociations, - CleaningAndMaintenance, - ClothingRental, - CollegesUniversities, - CommercialEquipment, - CommercialFootwear, - CommercialPhotographyArtAndGraphics, - CommuterTransportAndFerries, - ComputerNetworkServices, - ComputerProgramming, - ComputerRepair, - ComputerSoftwareStores, - ComputersPeripheralsAndSoftware, - ConcreteWorkServices, - ConstructionMaterials, - ConsultingPublicRelations, - CorrespondenceSchools, - CosmeticStores, - CounselingServices, - CountryClubs, - CourierServices, - CourtCosts, - CreditReportingAgencies, - CruiseLines, - DairyProductsStores, - DanceHallStudiosSchools, - DatingEscortServices, - DentistsOrthodontists, - DepartmentStores, - DetectiveAgencies, - DirectMarketingCatalogMerchant, - DirectMarketingCombinationCatalogAndRetailMerchant, - DirectMarketingInboundTelemarketing, - DirectMarketingInsuranceServices, - DirectMarketingOther, - DirectMarketingOutboundTelemarketing, - DirectMarketingSubscription, - DirectMarketingTravel, - DiscountStores, - Doctors, - DoorToDoorSales, - DraperyWindowCoveringAndUpholsteryStores, - DrinkingPlaces, - DrugStoresAndPharmacies, - DrugsDrugProprietariesAndDruggistSundries, - DryCleaners, - DurableGoods, - DutyFreeStores, - EatingPlacesRestaurants, - EducationalServices, - ElectricRazorStores, - ElectricalPartsAndEquipment, - ElectricalServices, - ElectronicsRepairShops, - ElectronicsStores, - ElementarySecondarySchools, - EmploymentTempAgencies, - EquipmentRental, - ExterminatingServices, - FamilyClothingStores, - FastFoodRestaurants, - FinancialInstitutions, - FinesGovernmentAdministrativeEntities, - FireplaceFireplaceScreensAndAccessoriesStores, - FloorCoveringStores, - Florists, - FloristsSuppliesNurseryStockAndFlowers, - FreezerAndLockerMeatProvisioners, - FuelDealersNonAutomotive, - FuneralServicesCrematories, - FurnitureHomeFurnishingsAndEquipmentStoresExceptAppliances, - FurnitureRepairRefinishing, - FurriersAndFurShops, - GeneralServices, - GiftCardNoveltyAndSouvenirShops, - GlassPaintAndWallpaperStores, - GlasswareCrystalStores, - GolfCoursesPublic, - GovernmentServices, - GroceryStoresSupermarkets, - HardwareEquipmentAndSupplies, - HardwareStores, - HealthAndBeautySpas, - HearingAidsSalesAndSupplies, - #[serde(rename = "heating_plumbing_a_c")] - HeatingPlumbingAC, - HobbyToyAndGameShops, - HomeSupplyWarehouseStores, - Hospitals, - HotelsMotelsAndResorts, - HouseholdApplianceStores, - IndustrialSupplies, - InformationRetrievalServices, - InsuranceDefault, - InsuranceUnderwritingPremiums, - IntraCompanyPurchases, - JewelryStoresWatchesClocksAndSilverwareStores, - LandscapingServices, - Laundries, - LaundryCleaningServices, - LegalServicesAttorneys, - LuggageAndLeatherGoodsStores, - LumberBuildingMaterialsStores, - ManualCashDisburse, - MarinasServiceAndSupplies, - MasonryStoneworkAndPlaster, - MassageParlors, - MedicalAndDentalLabs, - MedicalDentalOphthalmicAndHospitalEquipmentAndSupplies, - MedicalServices, - MembershipOrganizations, - MensAndBoysClothingAndAccessoriesStores, - MensWomensClothingStores, - MetalServiceCenters, - Miscellaneous, - MiscellaneousApparelAndAccessoryShops, - MiscellaneousAutoDealers, - MiscellaneousBusinessServices, - MiscellaneousFoodStores, - MiscellaneousGeneralMerchandise, - MiscellaneousGeneralServices, - MiscellaneousHomeFurnishingSpecialtyStores, - MiscellaneousPublishingAndPrinting, - MiscellaneousRecreationServices, - MiscellaneousRepairShops, - MiscellaneousSpecialtyRetail, - MobileHomeDealers, - MotionPictureTheaters, - MotorFreightCarriersAndTrucking, - MotorHomesDealers, - MotorVehicleSuppliesAndNewParts, - MotorcycleShopsAndDealers, - MotorcycleShopsDealers, - MusicStoresMusicalInstrumentsPianosAndSheetMusic, - NewsDealersAndNewsstands, - NonFiMoneyOrders, - NonFiStoredValueCardPurchaseLoad, - NondurableGoods, - NurseriesLawnAndGardenSupplyStores, - NursingPersonalCare, - OfficeAndCommercialFurniture, - OpticiansEyeglasses, - OptometristsOphthalmologist, - OrthopedicGoodsProstheticDevices, - Osteopaths, - PackageStoresBeerWineAndLiquor, - PaintsVarnishesAndSupplies, - ParkingLotsGarages, - PassengerRailways, - PawnShops, - PetShopsPetFoodAndSupplies, - PetroleumAndPetroleumProducts, - PhotoDeveloping, - PhotographicPhotocopyMicrofilmEquipmentAndSupplies, - PhotographicStudios, - PictureVideoProduction, - PieceGoodsNotionsAndOtherDryGoods, - PlumbingHeatingEquipmentAndSupplies, - PoliticalOrganizations, - PostalServicesGovernmentOnly, - PreciousStonesAndMetalsWatchesAndJewelry, - ProfessionalServices, - PublicWarehousingAndStorage, - QuickCopyReproAndBlueprint, - Railroads, - RealEstateAgentsAndManagersRentals, - RecordStores, - RecreationalVehicleRentals, - ReligiousGoodsStores, - ReligiousOrganizations, - RoofingSidingSheetMetal, - SecretarialSupportServices, - SecurityBrokersDealers, - ServiceStations, - SewingNeedleworkFabricAndPieceGoodsStores, - ShoeRepairHatCleaning, - ShoeStores, - SmallApplianceRepair, - SnowmobileDealers, - SpecialTradeServices, - SpecialtyCleaning, - SportingGoodsStores, - SportingRecreationCamps, - SportsAndRidingApparelStores, - SportsClubsFields, - StampAndCoinStores, - StationaryOfficeSuppliesPrintingAndWritingPaper, - StationeryStoresOfficeAndSchoolSupplyStores, - SwimmingPoolsSales, - TUiTravelGermany, - TailorsAlterations, - TaxPaymentsGovernmentAgencies, - TaxPreparationServices, - TaxicabsLimousines, - TelecommunicationEquipmentAndTelephoneSales, - TelecommunicationServices, - TelegraphServices, - TentAndAwningShops, - TestingLaboratories, - TheatricalTicketAgencies, - Timeshares, - TireRetreadingAndRepair, - TollsBridgeFees, - TouristAttractionsAndExhibits, - TowingServices, - TrailerParksCampgrounds, - TransportationServices, - TravelAgenciesTourOperators, - TruckStopIteration, - TruckUtilityTrailerRentals, - TypesettingPlateMakingAndRelatedServices, - TypewriterStores, - #[serde(rename = "u_s_federal_government_agencies_or_departments")] - USFederalGovernmentAgenciesOrDepartments, - UniformsCommercialClothing, - UsedMerchandiseAndSecondhandStores, - Utilities, - VarietyStores, - VeterinaryServices, - VideoAmusementGameSupplies, - VideoGameArcades, - VideoTapeRentalStores, - VocationalTradeSchools, - WatchJewelryRepair, - WeldingRepair, - WholesaleClubs, - WigAndToupeeStores, - WiresMoneyOrders, - WomensAccessoryAndSpecialtyShops, - WomensReadyToWearStores, - WreckingAndSalvageYards, -} diff --git a/ft-stripe/src/resources/issuing_transaction.rs b/ft-stripe/src/resources/issuing_transaction.rs deleted file mode 100644 index 217d945..0000000 --- a/ft-stripe/src/resources/issuing_transaction.rs +++ /dev/null @@ -1,211 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::IssuingTransactionId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{ - BalanceTransaction, Currency, IssuingAuthorization, IssuingCard, IssuingCardholder, - IssuingTransactionType, MerchantData, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "IssuingTransaction". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransaction { - /// Unique identifier for the object. - pub id: IssuingTransactionId, - - /// The transaction amount, which will be reflected in your balance. - /// - /// This amount is in your currency and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - pub amount: i64, - - /// The `Authorization` object that led to this transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub authorization: Option>, - - /// ID of the [balance transaction](https://stripe.com/docs/api/balance_transactions) associated with this transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// The card used to make this transaction. - pub card: Expandable, - - /// The cardholder to whom this transaction belongs. - #[serde(skip_serializing_if = "Option::is_none")] - pub cardholder: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// The amount that the merchant will receive, denominated in `merchant_currency` and in the [smallest currency unit](https://stripe.com/docs/currencies#zero-decimal). - /// - /// It will be different from `amount` if the merchant is taking payment in a different currency. - pub merchant_amount: i64, - - /// The currency with which the merchant is taking payment. - pub merchant_currency: Currency, - - pub merchant_data: MerchantData, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// Additional purchase information that is optionally provided by the merchant. - #[serde(skip_serializing_if = "Option::is_none")] - pub purchase_details: Option, - - /// The nature of the transaction. - #[serde(rename = "type")] - pub type_: IssuingTransactionType, -} - -impl Object for IssuingTransaction { - type Id = IssuingTransactionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.transaction" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionPurchaseDetails { - /// Information about the flight that was purchased with this transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub flight: Option, - - /// Information about fuel that was purchased with this transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub fuel: Option, - - /// Information about lodging that was purchased with this transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub lodging: Option, - - /// The line items in the purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt: Option>, - - /// A merchant-specific order number. - #[serde(skip_serializing_if = "Option::is_none")] - pub reference: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionFlightData { - /// The time that the flight departed. - #[serde(skip_serializing_if = "Option::is_none")] - pub departure_at: Option, - - /// The name of the passenger. - #[serde(skip_serializing_if = "Option::is_none")] - pub passenger_name: Option, - - /// Whether the ticket is refundable. - #[serde(skip_serializing_if = "Option::is_none")] - pub refundable: Option, - - /// The legs of the trip. - #[serde(skip_serializing_if = "Option::is_none")] - pub segments: Option>, - - /// The travel agency that issued the ticket. - #[serde(skip_serializing_if = "Option::is_none")] - pub travel_agency: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionFlightDataLeg { - /// The flight's destination airport code. - #[serde(skip_serializing_if = "Option::is_none")] - pub arrival_airport_code: Option, - - /// The airline carrier code. - #[serde(skip_serializing_if = "Option::is_none")] - pub carrier: Option, - - /// The airport code that the flight departed from. - #[serde(skip_serializing_if = "Option::is_none")] - pub departure_airport_code: Option, - - /// The flight number. - #[serde(skip_serializing_if = "Option::is_none")] - pub flight_number: Option, - - /// The flight's service class. - #[serde(skip_serializing_if = "Option::is_none")] - pub service_class: Option, - - /// Whether a stopover is allowed on this flight. - #[serde(skip_serializing_if = "Option::is_none")] - pub stopover_allowed: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionFuelData { - /// The type of fuel that was purchased. - /// - /// One of `diesel`, `unleaded_plus`, `unleaded_regular`, `unleaded_super`, or `other`. - #[serde(rename = "type")] - pub type_: String, - - /// The units for `volume`. - /// - /// One of `us_gallon` or `liter`. - pub unit: String, - - /// The cost in cents per each unit of fuel, represented as a decimal string with at most 12 decimal places. - pub unit_cost_decimal: String, - - /// The volume of the fuel that was pumped, represented as a decimal string with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub volume_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionLodgingData { - /// The time of checking into the lodging. - #[serde(skip_serializing_if = "Option::is_none")] - pub check_in_at: Option, - - /// The number of nights stayed at the lodging. - #[serde(skip_serializing_if = "Option::is_none")] - pub nights: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransactionReceiptData { - /// The description of the item. - /// - /// The maximum length of this field is 26 characters. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The quantity of the item. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The total for this line item in cents. - #[serde(skip_serializing_if = "Option::is_none")] - pub total: Option, - - /// The unit cost of the item in cents. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_cost: Option, -} diff --git a/ft-stripe/src/resources/issuing_transaction_ext.rs b/ft-stripe/src/resources/issuing_transaction_ext.rs deleted file mode 100644 index 22b5a67..0000000 --- a/ft-stripe/src/resources/issuing_transaction_ext.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `IssuingTransaction`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum IssuingTransactionType { - Capture, - CashWithdrawal, - Dispute, - DisputeLoss, - Refund, - RefundReversal, -} - -impl IssuingTransactionType { - pub fn as_str(self) -> &'static str { - match self { - IssuingTransactionType::Capture => "capture", - IssuingTransactionType::CashWithdrawal => "cash_withdrawal", - IssuingTransactionType::Dispute => "dispute", - IssuingTransactionType::DisputeLoss => "dispute_loss", - IssuingTransactionType::Refund => "refund", - IssuingTransactionType::RefundReversal => "refund_reversal", - } - } -} - -impl AsRef for IssuingTransactionType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for IssuingTransactionType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/item.rs b/ft-stripe/src/resources/item.rs deleted file mode 100644 index 0525d63..0000000 --- a/ft-stripe/src/resources/item.rs +++ /dev/null @@ -1,63 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::CheckoutSessionItemId; -use crate::params::Object; -use crate::resources::{Currency, Price, TaxRate}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "PaymentPagesCheckoutSessionLineItem". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CheckoutSessionItem { - /// Unique identifier for the object. - pub id: CheckoutSessionItemId, - - /// Total before any discounts or taxes is applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_subtotal: Option, - - /// Total after discounts and taxes. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_total: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - /// Defaults to product name. - pub description: String, - - pub price: Price, - - /// The quantity of products being purchased. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The taxes applied to the line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub taxes: Option>, -} - -impl Object for CheckoutSessionItem { - type Id = CheckoutSessionItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "item" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentPagesCheckoutSessionLineItemResourceLineItemTax { - /// Amount of tax for this line item. - pub amount: i64, - - pub rate: TaxRate, -} diff --git a/ft-stripe/src/resources/line_item.rs b/ft-stripe/src/resources/line_item.rs deleted file mode 100644 index e605565..0000000 --- a/ft-stripe/src/resources/line_item.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::InvoiceLineItemId; -use crate::params::{Expandable, Metadata, Object}; -use crate::resources::{Currency, Period, Plan, Price, TaxRate}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "InvoiceLineItem". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceLineItem { - /// Unique identifier for the object. - pub id: InvoiceLineItemId, - - /// The amount, in %s. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// If true, discounts will apply to this line item. - /// - /// Always false for prorations. - pub discountable: bool, - - /// The ID of the [invoice item](https://stripe.com/docs/api/invoiceitems) associated with this line item if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_item: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Note that for line items with `type=subscription` this will reflect the metadata of the subscription that caused the line item to be created. - pub metadata: Metadata, - - pub period: Option, - - /// The plan of the subscription, if the line item is a subscription or a proration. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// The price of the line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Whether this is a proration. - pub proration: bool, - - /// The quantity of the subscription, if the line item is a subscription or a proration. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The subscription that the invoice item pertains to, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, - - /// The subscription item that generated this invoice item. - /// - /// Left empty if the line item is not an explicit result of a subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_item: Option, - - /// The amount of tax calculated per tax rate for this line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_amounts: Option>, - - /// The tax rates which apply to the line item. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, - - /// A string identifying the type of the source of this line item, either an `invoiceitem` or a `subscription`. - #[serde(rename = "type")] - pub type_: InvoiceLineItemType, -} - -impl Object for InvoiceLineItem { - type Id = InvoiceLineItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "line_item" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxAmount { - /// The amount, in %s, of the tax. - pub amount: i64, - - /// Whether this tax amount is inclusive or exclusive. - pub inclusive: bool, - - /// The tax rate that was applied to get this tax amount. - pub tax_rate: Expandable, -} - -/// An enum representing the possible values of an `InvoiceLineItem`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum InvoiceLineItemType { - #[serde(rename = "invoiceitem")] - InvoiceItem, - Subscription, -} - -impl InvoiceLineItemType { - pub fn as_str(self) -> &'static str { - match self { - InvoiceLineItemType::InvoiceItem => "invoiceitem", - InvoiceLineItemType::Subscription => "subscription", - } - } -} - -impl AsRef for InvoiceLineItemType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for InvoiceLineItemType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/line_item_ext.rs b/ft-stripe/src/resources/line_item_ext.rs deleted file mode 100644 index b282d63..0000000 --- a/ft-stripe/src/resources/line_item_ext.rs +++ /dev/null @@ -1,46 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, InvoiceId}; -use crate::resources::{Currency, InvoiceLineItem}; -use serde::{Deserialize, Serialize}; - -impl InvoiceLineItem { - /// Creates an invoice line item. - /// - /// For more details see https://stripe.com/docs/api#invoice_line_item_object - pub fn create(client: &Client, params: CreateInvoiceLineItem<'_>) -> Response { - client.post_form("/invoiceitems", ¶ms) - } -} - -#[derive(Clone, Debug, Default, Deserialize, Serialize)] -pub struct CreateInvoiceLineItem<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub discountable: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, -} - -impl CreateInvoiceLineItem<'_> { - pub fn new() -> Self { - CreateInvoiceLineItem { - amount: None, - currency: None, - customer: None, - description: None, - discountable: None, - invoice: None, - subscription: None, - } - } -} diff --git a/ft-stripe/src/resources/mandate.rs b/ft-stripe/src/resources/mandate.rs deleted file mode 100644 index 85ee42c..0000000 --- a/ft-stripe/src/resources/mandate.rs +++ /dev/null @@ -1,234 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::MandateId; -use crate::params::{Expand, Expandable, Object, Timestamp}; -use crate::resources::{Currency, PaymentMethod}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Mandate". -/// -/// For more details see [https://stripe.com/docs/api/mandates/object](https://stripe.com/docs/api/mandates/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Mandate { - /// Unique identifier for the object. - pub id: MandateId, - - pub customer_acceptance: CustomerAcceptance, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - #[serde(skip_serializing_if = "Option::is_none")] - pub multi_use: Option, - - /// ID of the payment method associated with this mandate. - pub payment_method: Expandable, - - pub payment_method_details: MandatePaymentMethodDetails, - - #[serde(skip_serializing_if = "Option::is_none")] - pub single_use: Option, - - /// The status of the mandate, which indicates whether it can be used to initiate a payment. - pub status: MandateStatus, - - /// The type of the mandate. - #[serde(rename = "type")] - pub type_: MandateType, -} - -impl Mandate { - /// Retrieves a Mandate object. - pub fn retrieve(client: &Client, id: &MandateId, expand: &[&str]) -> Response { - client.get_query(&format!("/mandates/{}", id), &Expand { expand }) - } -} - -impl Object for Mandate { - type Id = MandateId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "mandate" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CustomerAcceptance { - /// The time at which the customer accepted the Mandate. - #[serde(skip_serializing_if = "Option::is_none")] - pub accepted_at: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub offline: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub online: Option, - - /// The type of customer acceptance information included with the Mandate. - /// - /// One of `online` or `offline`. - #[serde(rename = "type")] - pub type_: CustomerAcceptanceType, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MandateMultiUse {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MandatePaymentMethodDetails { - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub sepa_debit: Option, - - /// The type of the payment method associated with this mandate. - /// - /// An additional hash is included on `payment_method_details` with a name matching this value. - /// It contains mandate information specific to the payment method. - #[serde(rename = "type")] - pub type_: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CardMandatePaymentMethodDetails {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MandateAuBecsDebit { - /// The URL of the mandate. - /// - /// This URL generally contains sensitive information about the customer and should be shared with them exclusively. - pub url: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MandateSepaDebit { - /// The unique reference of the mandate. - pub reference: String, - - /// The URL of the mandate. - /// - /// This URL generally contains sensitive information about the customer and should be shared with them exclusively. - pub url: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct MandateSingleUse { - /// On a single use mandate, the amount of the payment. - pub amount: i64, - - /// On a single use mandate, the currency of the payment. - pub currency: Currency, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OfflineAcceptance {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OnlineAcceptance { - /// The IP address from which the Mandate was accepted by the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub ip_address: Option, - - /// The user agent of the browser from which the Mandate was accepted by the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, -} - -/// An enum representing the possible values of an `CustomerAcceptance`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CustomerAcceptanceType { - Offline, - Online, -} - -impl CustomerAcceptanceType { - pub fn as_str(self) -> &'static str { - match self { - CustomerAcceptanceType::Offline => "offline", - CustomerAcceptanceType::Online => "online", - } - } -} - -impl AsRef for CustomerAcceptanceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CustomerAcceptanceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Mandate`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum MandateStatus { - Active, - Inactive, - Pending, -} - -impl MandateStatus { - pub fn as_str(self) -> &'static str { - match self { - MandateStatus::Active => "active", - MandateStatus::Inactive => "inactive", - MandateStatus::Pending => "pending", - } - } -} - -impl AsRef for MandateStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for MandateStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Mandate`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum MandateType { - MultiUse, - SingleUse, -} - -impl MandateType { - pub fn as_str(self) -> &'static str { - match self { - MandateType::MultiUse => "multi_use", - MandateType::SingleUse => "single_use", - } - } -} - -impl AsRef for MandateType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for MandateType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/order.rs b/ft-stripe/src/resources/order.rs deleted file mode 100644 index 983eebe..0000000 --- a/ft-stripe/src/resources/order.rs +++ /dev/null @@ -1,523 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CouponId, CustomerId, OrderId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Charge, Currency, Customer, OrderItem, OrderReturn, OrderStatusFilter, Shipping, ShippingParams, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Order". -/// -/// For more details see [https://stripe.com/docs/api/orders/object](https://stripe.com/docs/api/orders/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Order { - /// Unique identifier for the object. - pub id: OrderId, - - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. - pub amount: i64, - - /// The total amount that was returned to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_returned: Option, - - /// ID of the Connect Application that created the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option, - - /// A fee in cents that will be applied to the order and transferred to the application owner’s Stripe account. - /// - /// The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. - /// For more information, see the application fees documentation. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee: Option, - - /// The ID of the payment used to pay for the order. - /// - /// Present if the order status is `paid`, `fulfilled`, or `refunded`. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The customer used for the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// The email address of the customer placing the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// External coupon code to load for this order. - #[serde(skip_serializing_if = "Option::is_none")] - pub external_coupon_code: Option, - - /// List of items constituting the order. - /// - /// An order can have up to 25 items. - pub items: Vec, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// A list of returns that have taken place for this order. - #[serde(default)] - pub returns: List, - - /// The shipping method that is currently selected for this order, if any. - /// - /// If present, it is equal to one of the `id`s of shipping methods in the `shipping_methods` array. - /// At order creation time, if there are multiple shipping methods, Stripe will automatically selected the first method. - #[serde(skip_serializing_if = "Option::is_none")] - pub selected_shipping_method: Option, - - /// The shipping address for the order. - /// - /// Present if the order is for goods to be shipped. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// A list of supported shipping methods for this order. - /// - /// The desired shipping method can be specified either by updating the order, or when paying it. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_methods: Option>, - - /// Current order status. - /// - /// One of `created`, `paid`, `canceled`, `fulfilled`, or `returned`. - /// More details in the [Orders Guide](https://stripe.com/docs/orders/guide#understanding-order-statuses). - pub status: OrderStatus, - - /// The timestamps at which the order status was updated. - #[serde(skip_serializing_if = "Option::is_none")] - pub status_transitions: Option, - - /// Time at which the object was last updated. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub updated: Option, - - /// The user's order ID if it is different from the Stripe order ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub upstream_id: Option, -} - -impl Order { - /// Returns a list of your orders. - /// - /// The orders are returned sorted by creation date, with the most recently created orders appearing first. - pub fn list(client: &Client, params: ListOrders<'_>) -> Response> { - client.get_query("/orders", ¶ms) - } - - /// Creates a new order object. - pub fn create(client: &Client, params: CreateOrder<'_>) -> Response { - client.post_form("/orders", ¶ms) - } - - /// Retrieves the details of an existing order. - /// - /// Supply the unique order ID from either an order creation request or the order list, and Stripe will return the corresponding order information. - pub fn retrieve(client: &Client, id: &OrderId, expand: &[&str]) -> Response { - client.get_query(&format!("/orders/{}", id), &Expand { expand }) - } - - /// Updates the specific order by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. - pub fn update(client: &Client, id: &OrderId, params: UpdateOrder<'_>) -> Response { - client.post_form(&format!("/orders/{}", id), ¶ms) - } -} - -impl Object for Order { - type Id = OrderId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "order" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ShippingMethod { - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the line item. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The estimated delivery date for the given shipping method. - /// - /// Can be either a specific date or a range. - #[serde(skip_serializing_if = "Option::is_none")] - pub delivery_estimate: Option, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - pub description: String, - - /// Unique identifier for the object. - pub id: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct DeliveryEstimate { - /// If `type` is `"exact"`, `date` will be the expected delivery date in the format YYYY-MM-DD. - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - /// If `type` is `"range"`, `earliest` will be be the earliest delivery date in the format YYYY-MM-DD. - #[serde(skip_serializing_if = "Option::is_none")] - pub earliest: Option, - - /// If `type` is `"range"`, `latest` will be the latest delivery date in the format YYYY-MM-DD. - #[serde(skip_serializing_if = "Option::is_none")] - pub latest: Option, - - /// The type of estimate. - /// - /// Must be either `"range"` or `"exact"`. - #[serde(rename = "type")] - pub type_: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct StatusTransitions { - /// The time that the order was canceled. - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled: Option, - - /// The time that the order was fulfilled. - #[serde(skip_serializing_if = "Option::is_none")] - pub fulfiled: Option, - - /// The time that the order was paid. - #[serde(skip_serializing_if = "Option::is_none")] - pub paid: Option, - - /// The time that the order was returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub returned: Option, -} - -/// The parameters for `Order::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateOrder<'a> { - /// A coupon code that represents a discount to be applied to this order. - /// - /// Must be one-time duration and in same currency as the order. - /// An order can have multiple coupons. - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The ID of an existing customer to use for this order. - /// - /// If provided, the customer email and shipping address will be used to create the order. - /// Subsequently, the customer will also be charged to pay the order. - /// If `email` or `shipping` are also provided, they will override the values retrieved from the customer object. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// The email address of the customer placing the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// List of items constituting the order. - /// - /// An order can have up to 25 items. - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Shipping address for the order. - /// - /// Required if any of the SKUs are for products that have `shippable` set to true. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, -} - -impl<'a> CreateOrder<'a> { - pub fn new(currency: Currency) -> Self { - CreateOrder { - coupon: Default::default(), - currency, - customer: Default::default(), - email: Default::default(), - expand: Default::default(), - items: Default::default(), - metadata: Default::default(), - shipping: Default::default(), - } - } -} - -/// The parameters for `Order::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListOrders<'a> { - /// Date this order was created. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return orders for the given customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Only return orders with the given IDs. - #[serde(skip_serializing_if = "Option::is_none")] - pub ids: Option>, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return orders that have the given status. - /// - /// One of `created`, `paid`, `fulfilled`, or `refunded`. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - /// Filter orders based on when they were paid, fulfilled, canceled, or returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub status_transitions: Option, - - /// Only return orders with the given upstream order IDs. - #[serde(skip_serializing_if = "Option::is_none")] - pub upstream_ids: Option>, -} - -impl<'a> ListOrders<'a> { - pub fn new() -> Self { - ListOrders { - created: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - ids: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - status: Default::default(), - status_transitions: Default::default(), - upstream_ids: Default::default(), - } - } -} - -/// The parameters for `Order::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateOrder<'a> { - /// A coupon code that represents a discount to be applied to this order. - /// - /// Must be one-time duration and in same currency as the order. - /// An order can have multiple coupons. - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The shipping method to select for fulfilling this order. - /// - /// If specified, must be one of the `id`s of a shipping method in the `shipping_methods` array. - /// If specified, will overwrite the existing selected shipping method, updating `items` as necessary. - #[serde(skip_serializing_if = "Option::is_none")] - pub selected_shipping_method: Option<&'a str>, - - /// Tracking information once the order has been fulfilled. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// Current order status. - /// - /// One of `created`, `paid`, `canceled`, `fulfilled`, or `returned`. - /// More detail in the [Orders Guide](https://stripe.com/docs/orders/guide#understanding-order-statuses). - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, -} - -impl<'a> UpdateOrder<'a> { - pub fn new() -> Self { - UpdateOrder { - coupon: Default::default(), - expand: Default::default(), - metadata: Default::default(), - selected_shipping_method: Default::default(), - shipping: Default::default(), - status: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ListOrdersStatusTransitions { - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fulfilled: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub paid: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub returned: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OrderItemParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub parent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -/// An enum representing the possible values of an `OrderItemParams`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum OrderItemParamsType { - Discount, - Shipping, - Sku, - Tax, -} - -impl OrderItemParamsType { - pub fn as_str(self) -> &'static str { - match self { - OrderItemParamsType::Discount => "discount", - OrderItemParamsType::Shipping => "shipping", - OrderItemParamsType::Sku => "sku", - OrderItemParamsType::Tax => "tax", - } - } -} - -impl AsRef for OrderItemParamsType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for OrderItemParamsType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `UpdateOrder`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum OrderStatus { - Canceled, - Created, - Fulfilled, - Paid, - Returned, -} - -impl OrderStatus { - pub fn as_str(self) -> &'static str { - match self { - OrderStatus::Canceled => "canceled", - OrderStatus::Created => "created", - OrderStatus::Fulfilled => "fulfilled", - OrderStatus::Paid => "paid", - OrderStatus::Returned => "returned", - } - } -} - -impl AsRef for OrderStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for OrderStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/order_ext.rs b/ft-stripe/src/resources/order_ext.rs deleted file mode 100644 index 6d55862..0000000 --- a/ft-stripe/src/resources/order_ext.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `ListOrders`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum OrderStatusFilter { - Created, - Fulfilled, - Paid, - Refunded, -} - -impl OrderStatusFilter { - pub fn as_str(self) -> &'static str { - match self { - OrderStatusFilter::Created => "created", - OrderStatusFilter::Fulfilled => "fulfilled", - OrderStatusFilter::Paid => "paid", - OrderStatusFilter::Refunded => "refunded", - } - } -} - -impl AsRef for OrderStatusFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for OrderStatusFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/order_item.rs b/ft-stripe/src/resources/order_item.rs deleted file mode 100644 index 32a47ea..0000000 --- a/ft-stripe/src/resources/order_item.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::{Expandable, Object}; -use crate::resources::{Currency, Sku}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "OrderItem". -/// -/// For more details see [https://stripe.com/docs/api/order_items/object](https://stripe.com/docs/api/order_items/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OrderItem { - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the line item. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Description of the line item, meant to be displayable to the user (e.g., `"Express shipping"`). - pub description: String, - - /// The ID of the associated object for this line item. - /// - /// Expandable if not null (e.g., expandable to a SKU). - #[serde(skip_serializing_if = "Option::is_none")] - pub parent: Option>, - - /// A positive integer representing the number of instances of `parent` that are included in this order item. - /// - /// Applicable/present only if `type` is `sku`. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The type of line item. - /// - /// One of `sku`, `tax`, `shipping`, or `discount`. - #[serde(rename = "type")] - pub type_: String, -} - -impl Object for OrderItem { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "order_item" - } -} diff --git a/ft-stripe/src/resources/order_return.rs b/ft-stripe/src/resources/order_return.rs deleted file mode 100644 index bf20ae1..0000000 --- a/ft-stripe/src/resources/order_return.rs +++ /dev/null @@ -1,121 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{OrderId, OrderReturnId}; -use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; -use crate::resources::{Currency, Order, OrderItem, Refund}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "OrderReturn". -/// -/// For more details see [https://stripe.com/docs/api/order_returns/object](https://stripe.com/docs/api/order_returns/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OrderReturn { - /// Unique identifier for the object. - pub id: OrderReturnId, - - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the returned line item. - pub amount: i64, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The items included in this order return. - pub items: Vec, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// The order that this return includes items from. - #[serde(skip_serializing_if = "Option::is_none")] - pub order: Option>, - - /// The ID of the refund issued for this return. - #[serde(skip_serializing_if = "Option::is_none")] - pub refund: Option>, -} - -impl OrderReturn { - /// Returns a list of your order returns. - /// - /// The returns are returned sorted by creation date, with the most recently created return appearing first. - pub fn list(client: &Client, params: ListOrderReturns<'_>) -> Response> { - client.get_query("/order_returns", ¶ms) - } - - /// Retrieves the details of an existing order return. - /// - /// Supply the unique order ID from either an order return creation request or the order return list, and Stripe will return the corresponding order information. - pub fn retrieve(client: &Client, id: &OrderReturnId, expand: &[&str]) -> Response { - client.get_query(&format!("/order_returns/{}", id), &Expand { expand }) - } -} - -impl Object for OrderReturn { - type Id = OrderReturnId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "order_return" - } -} - -/// The parameters for `OrderReturn::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListOrderReturns<'a> { - /// Date this return was created. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// The order to retrieve returns for. - #[serde(skip_serializing_if = "Option::is_none")] - pub order: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListOrderReturns<'a> { - pub fn new() -> Self { - ListOrderReturns { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - order: Default::default(), - starting_after: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/payment_intent.rs b/ft-stripe/src/resources/payment_intent.rs deleted file mode 100644 index e799183..0000000 --- a/ft-stripe/src/resources/payment_intent.rs +++ /dev/null @@ -1,602 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, PaymentIntentId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Account, Application, Charge, Currency, Customer, Invoice, PaymentIntentOffSession, - PaymentMethod, PaymentSource, Review, Shipping, TransferDataParams, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "PaymentIntent". -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/object](https://stripe.com/docs/api/payment_intents/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentIntent { - /// Unique identifier for the object. - pub id: PaymentIntentId, - - /// Amount intended to be collected by this PaymentIntent. - pub amount: i64, - - /// Amount that can be captured from this PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_capturable: Option, - - /// Amount that was collected by this PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_received: Option, - - /// ID of the Connect application that created the PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option>, - - /// The amount of the application fee (if any) for the resulting payment. - /// - /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - - /// Populated when `status` is `canceled`, this is the time at which the PaymentIntent was canceled. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled_at: Option, - - /// Reason for cancellation of this PaymentIntent, either user-provided (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or generated by Stripe internally (`failed_invoice`, `void_invoice`, or `automatic`). - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_reason: Option, - - /// Capture method of this PaymentIntent, one of `automatic` or `manual`. - pub capture_method: PaymentIntentCaptureMethod, - - /// Charges that were created by this PaymentIntent, if any. - #[serde(default)] - pub charges: List, - - /// The client secret of this PaymentIntent. - /// - /// Used for client-side retrieval using a publishable key. - /// Please refer to our [automatic confirmation quickstart guide](https://stripe.com/docs/payments/payment-intents/quickstart#automatic-confirmation-flow) to learn about how `client_secret` should be handled. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_secret: Option, - - /// Confirmation method of this PaymentIntent, one of `manual` or `automatic`. - pub confirmation_method: PaymentIntentConfirmationMethod, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// ID of the Customer this PaymentIntent is for if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// ID of the invoice that created this PaymentIntent, if it exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice: Option>, - - /// The payment error encountered in the previous PaymentIntent confirmation. - #[serde(skip_serializing_if = "Option::is_none")] - pub last_payment_error: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// For more information, see the [documentation](https://stripe.com/docs/payments/payment-intents/creating-payment-intents#storing-information-in-metadata). - #[serde(default)] - pub metadata: Metadata, - - /// If present, this property tells you what actions you need to take in order for your customer to fulfill a payment using the provided source. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_action: Option, - - /// The account (if any) for which the funds of the PaymentIntent are intended. - /// - /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option>, - - /// ID of the payment method used in this PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option>, - - /// The list of payment method types (e.g. - /// - /// card) that this PaymentIntent is allowed to use. - pub payment_method_types: Vec, - - /// Email address that the receipt for the resulting payment will be sent to. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option, - - /// ID of the review associated with this PaymentIntent, if any. - #[serde(skip_serializing_if = "Option::is_none")] - pub review: Option>, - - /// Shipping information for this PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - - /// ID of the source used in this PaymentIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option>, - - /// Used in payment flows that collect payment details and charge later when the customer is not available to complete additional required steps for the payment. - /// - /// Setting this parameter indicates that this payment attempt is happening while the customer is not in your checkout flow. - /// Use `recurring` for payments made on a recurring basis (for example, subscriptions) and `one_off` for all other off-session payments. - pub off_session: Option, - - /// Extra information about a PaymentIntent. - /// - /// This will appear on your customer's statement when this PaymentIntent succeeds in creating a charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// Status of this PaymentIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, `canceled`, or `succeeded`. - /// - /// Read more about each PaymentIntent [status](https://stripe.com/docs/payments/payment-intents/status). - pub status: PaymentIntentStatus, - - /// The data with which to automatically create a Transfer when the payment is finalized. - /// - /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_data: Option, - - /// A string that identifies the resulting payment as part of a group. - /// - /// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option, -} - -impl PaymentIntent { - /// Creates a new payment_intent. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create). - pub fn create(client: &Client, params: CreatePaymentIntent<'_>) -> Response { - client.post_form("/payment_intents", params) - } - - /// Retrieves the details of a payment_intent. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/retrieve](https://stripe.com/docs/api/payment_intents/retrieve). - pub fn retrieve(client: &Client, payment_intent_id: &str) -> Response { - client.get(&format!("/payment_intents/{}", payment_intent_id)) - } - - /// Updates a payment_intent's properties. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update). - pub fn update( - client: &Client, - payment_intent_id: &str, - params: PaymentIntentUpdateParams<'_>, - ) -> Response { - client.post_form(&format!("/payment_intents/{}", payment_intent_id), params) - } - - /// Confirm that customer intends to pay with current or provided source. Upon confirmation, the PaymentIntent will attempt to initiate a payment. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm). - pub fn confirm( - client: &Client, - payment_intent_id: &str, - params: PaymentIntentConfirmParams<'_>, - ) -> Response { - client.post_form(&format!("/payment_intents/{}/confirm", payment_intent_id), params) - } - - /// Capture the funds of an existing uncaptured PaymentIntent where required_action="requires_capture". - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture). - pub fn capture( - client: &Client, - payment_intent_id: &str, - params: CapturePaymentIntent, - ) -> Response { - client.post_form(&format!("/payment_intents/{}/capture", payment_intent_id), params) - } - - /// A PaymentIntent object can be canceled when it is in one of these statuses: requires_source, requires_capture, requires_confirmation, requires_source_action. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel). - pub fn cancel( - client: &Client, - payment_intent_id: &str, - params: CancelPaymentIntent, - ) -> Response { - client.post_form(&format!("/payment_intents/{}/cancel", payment_intent_id), params) - } - - /// List all payment_intents. - /// - /// For more details see [https://stripe.com/docs/api/payment_intents/list](https://stripe.com/docs/api/payment_intents/list). - pub fn list(client: &Client, params: ListPaymentIntents) -> Response> { - client.get_query("/payment_intents", ¶ms) - } -} - -impl Object for PaymentIntent { - type Id = PaymentIntentId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "payment_intent" - } -} - -/// The resource representing a Stripe PaymentError object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentError { - #[serde(rename = "type")] - pub payment_error_type: PaymentErrorType, - pub charge: Option, - pub code: Option, - pub decline_code: Option, - pub doc_url: Option, - pub message: Option, - pub param: Option, - pub source: Option>, -} - -/// The resource representing a Stripe PaymentErrorType object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type). -#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] -pub enum PaymentErrorType { - #[serde(rename = "api_error")] - Api, - #[serde(rename = "api_connection_error")] - Connection, - #[serde(rename = "authentication_error")] - Authentication, - #[serde(rename = "card_error")] - Card, - #[serde(rename = "idempotency_error")] - Idempotency, - #[serde(rename = "invalid_request_error")] - InvalidRequest, - #[serde(rename = "rate_limit_error")] - RateLimit, - - /// A variant not yet supported by the library. - /// It is an error to send `Other` as part of a request. - #[serde(other, skip_serializing)] - Other, -} - -// TODO: This might be moved to `PaymentSourceType` if we determine -// that all of the variants are _always_ the same. -// -// In that case this can be replaced with a deprecated type alias. -/// Represents the way a `PaymentIntent` needs to be fulfilled. -#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentMethodType { - /// This `PaymentIntent` needs to be fulfilled through credit card payment. - Card, - /// This `PaymentIntent` needs to be fulfilled through an - /// [iDeal](https://stripe.com/docs/payments/ideal) payment. - Ideal, - /// This `PaymentIntent` needs to be fulfilled through a - /// [Sepa Direct Debit](https://stripe.com/docs/payments/sepa-debit) payment. - SepaDebit, -} - -/// The resource representing a Stripe CaptureMethod object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method). -#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] -#[serde(rename_all = "snake_case")] -pub enum CaptureMethod { - Automatic, - Manual, - - /// A variant not yet supported by the library. - /// It is an error to send `Other` as part of a request. - #[serde(other, skip_serializing)] - Other, -} -/// The resource representing a Stripe ConfirmationMethod object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method). -#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] -#[serde(rename_all = "snake_case")] -pub enum ConfirmationMethod { - Secret, - Publishable, - - /// A variant not yet supported by the library. - /// It is an error to send `Other` as part of a request. - #[serde(other, skip_serializing)] - Other, -} - -#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentNextActionType { - RedirectToUrl, - UseStripeSdk, - - /// A variant not yet supported by the library. - /// It is an error to send `Other` as part of a request. - #[serde(other, skip_serializing)] - Other, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentIntentNextAction { - /// Type of the next action to perform, one of `redirect_to_url` or `use_stripe_sdk`. - #[serde(rename = "type")] - pub type_: PaymentIntentNextActionType, - - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect_to_url: Option, - - /// When confirming a PaymentIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. - /// - /// The shape of the contents is subject to change and is only intended to be used by Stripe.js. - #[serde(skip_serializing_if = "Option::is_none")] - pub use_stripe_sdk: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentIntentNextActionRedirectToUrl { - /// If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. - #[serde(skip_serializing_if = "Option::is_none")] - pub return_url: Option, - - /// The URL you must redirect your customer to in order to authenticate the payment. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferData { - /// The account (if any) the payment will be attributed to for tax - /// reporting, and where funds from the payment will be transferred to upon - /// payment success. - pub destination: Expandable, -} - -/// The set of parameters that can be used when creating a payment_intent object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create) -#[derive(Clone, Debug, Default, Serialize)] -pub struct CreatePaymentIntent<'a> { - /// The list of payment types (e.g. card) that this PaymentIntent is allowed to use. - pub payment_method_types: Vec, - pub amount: u64, - pub currency: Currency, - pub payment_method: Option<&'a str>, - pub confirmation_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub capture_method: Option, - - /// Attempt to confirm this PaymentIntent on source attachment. - #[serde(skip_serializing_if = "Option::is_none")] - pub confirm: Option, // TODO: Is this the correct type? - - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub return_url: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub save_source_to_customer: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_data: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> CreatePaymentIntent<'a> { - pub fn new(amount: u64, currency: Currency) -> Self { - CreatePaymentIntent { - payment_method_types: Default::default(), - amount, - currency, - payment_method: Default::default(), - confirmation_method: Default::default(), - application_fee_amount: Default::default(), - capture_method: Default::default(), - confirm: Default::default(), - customer: Default::default(), - description: Default::default(), - metadata: Default::default(), - on_behalf_of: Default::default(), - receipt_email: Default::default(), - return_url: Default::default(), - save_source_to_customer: Default::default(), - shipping: Default::default(), - source: Default::default(), - statement_descriptor: Default::default(), - transfer_data: Default::default(), - transfer_group: Default::default(), - } - } -} - -/// The set of parameters that can be used when updating a payment_intent object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update) -#[derive(Clone, Debug, Default, Serialize)] -pub struct PaymentIntentUpdateParams<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub save_source_to_customer: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -/// The set of parameters that can be used when confirming a payment_intent object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm) -#[derive(Clone, Debug, Default, Serialize)] -pub struct PaymentIntentConfirmParams<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_email: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub return_url: Option<&'a str>, - #[serde(skip_serializing_if = "Option::is_none")] - pub save_source_to_customer: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option<&'a str>, -} - -/// The set of parameters that can be used when capturing a payment_intent object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture) -#[derive(Clone, Debug, Default, Serialize)] -pub struct CapturePaymentIntent { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_to_capture: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_amount: Option, -} - -/// The set of parameters that can be used when canceling a payment_intent object. -/// -/// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel) -#[derive(Clone, Debug, Default, Serialize)] -pub struct CancelPaymentIntent { - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_reason: Option, -} - -/// The parameters for `PaymentIntent::list`. -#[derive(Clone, Debug, Serialize)] -pub struct ListPaymentIntents<'a> { - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return PaymentIntents for the customer specified by this customer ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option<&'a PaymentIntentId>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option<&'a PaymentIntentId>, -} - -/// An enum representing the possible values of an `PaymentIntent`'s `cancellation_reason` field. -#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentCancellationReason { - Abandoned, - Automatic, - Duplicate, - FailedInvoice, - Fraudulent, - RequestedByCustomer, - VoidInvoice, -} - -/// An enum representing the possible values of an `PaymentIntent`'s `capture_method` field. -#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentCaptureMethod { - Automatic, - Manual, -} - -/// An enum representing the possible values of an `PaymentIntent`'s `confirmation_method` field. -#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentConfirmationMethod { - Automatic, - Manual, -} - -/// An enum representing the possible values of an `PaymentIntent`'s `status` field. -#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentIntentStatus { - Canceled, - Processing, - RequiresAction, - RequiresCapture, - RequiresConfirmation, - RequiresPaymentMethod, - RequiresSource, - Succeeded, -} diff --git a/ft-stripe/src/resources/payment_method.rs b/ft-stripe/src/resources/payment_method.rs deleted file mode 100644 index 8a65434..0000000 --- a/ft-stripe/src/resources/payment_method.rs +++ /dev/null @@ -1,949 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, PaymentMethodId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, Timestamp}; -use crate::resources::{Address, BillingDetails, Customer, PaymentMethodDetails}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "PaymentMethod". -/// -/// For more details see [https://stripe.com/docs/api/payment_methods/object](https://stripe.com/docs/api/payment_methods/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethod { - /// Unique identifier for the object. - pub id: PaymentMethodId, - - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit: Option, - - pub billing_details: BillingDetails, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card_present: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// The ID of the Customer to which this PaymentMethod is saved. - /// - /// This will not be set when the PaymentMethod has not been saved to a Customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fpx: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ideal: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub sepa_debit: Option, - - /// The type of the PaymentMethod. - /// - /// An additional hash is included on the PaymentMethod with a name matching this value. - /// It contains additional information specific to the PaymentMethod type. - #[serde(rename = "type")] - pub type_: PaymentMethodType, -} - -impl PaymentMethod { - /// Returns a list of PaymentMethods for a given Customer. - pub fn list(client: &Client, params: ListPaymentMethods<'_>) -> Response> { - client.get_query("/payment_methods", ¶ms) - } - - /// Creates a PaymentMethod object. - /// - /// Read the [Stripe.js reference](https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method) to learn how to create PaymentMethods via Stripe.js. - pub fn create(client: &Client, params: CreatePaymentMethod<'_>) -> Response { - client.post_form("/payment_methods", ¶ms) - } - - /// Retrieves a PaymentMethod object. - pub fn retrieve( - client: &Client, - id: &PaymentMethodId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/payment_methods/{}", id), &Expand { expand }) - } - - /// Updates a PaymentMethod object. - /// - /// A PaymentMethod must be attached a customer to be updated. - pub fn update( - client: &Client, - id: &PaymentMethodId, - params: UpdatePaymentMethod<'_>, - ) -> Response { - client.post_form(&format!("/payment_methods/{}", id), ¶ms) - } -} - -impl Object for PaymentMethod { - type Id = PaymentMethodId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "payment_method" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodAuBecsDebit { - /// Six-digit number identifying bank and branch associated with this bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub bsb_number: Option, - - /// Uniquely identifies this particular bank account. - /// - /// You can use this attribute to check whether two bank accounts are the same. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Last four digits of the bank account number. - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CardDetails { - /// Card brand. - /// - /// Can be `amex`, `diners`, `discover`, `jcb`, `mastercard`, `unionpay`, `visa`, or `unknown`. - pub brand: String, - - /// Checks on Card address and CVC if provided. - #[serde(skip_serializing_if = "Option::is_none")] - pub checks: Option, - - /// Two-letter ISO code representing the country of the card. - /// - /// You could use this attribute to get a sense of the international breakdown of cards you've collected. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Two-digit number representing the card's expiration month. - pub exp_month: i64, - - /// Four-digit number representing the card's expiration year. - pub exp_year: i64, - - /// Uniquely identifies this particular card number. - /// - /// You can use this attribute to check whether two customers who’ve signed up with you are using the same card number,for example. - /// For payment methods that tokenize card information (Apple Pay, Google Pay), the tokenized number might be provided instead of the underlying card number. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Card funding type. - /// - /// Can be `credit`, `debit`, `prepaid`, or `unknown`. - pub funding: String, - - /// Details of the original PaymentMethod that created this object. - #[serde(skip_serializing_if = "Option::is_none")] - pub generated_from: Option, - - /// The last four digits of the card. - pub last4: String, - - /// Contains details on how this Card maybe be used for 3D Secure authentication. - #[serde(skip_serializing_if = "Option::is_none")] - pub three_d_secure_usage: Option, - - /// If this Card is part of a card wallet, this contains the details of the card wallet. - #[serde(skip_serializing_if = "Option::is_none")] - pub wallet: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodCardChecks { - /// If a address line1 was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line1_check: Option, - - /// If a address postal code was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub address_postal_code_check: Option, - - /// If a CVC was provided, results of the check, one of `pass`, `fail`, `unavailable`, or `unchecked`. - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc_check: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodCardGeneratedCard { - /// The charge that created this object. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option, - - /// Transaction-specific details of the payment method used in the payment. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_details: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CardPresent {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletDetails { - #[serde(skip_serializing_if = "Option::is_none")] - pub amex_express_checkout: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub apple_pay: Option, - - /// (For tokenized numbers only.) The last four digits of the device account number. - #[serde(skip_serializing_if = "Option::is_none")] - pub dynamic_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub google_pay: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub masterpass: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub samsung_pay: Option, - - /// The type of the card wallet, one of `amex_express_checkout`, `apple_pay`, `google_pay`, `masterpass`, `samsung_pay`, or `visa_checkout`. - /// - /// An additional hash is included on the Wallet subhash with a name matching this value. - /// It contains additional information specific to the card wallet type. - #[serde(rename = "type")] - pub type_: WalletDetailsType, - - #[serde(skip_serializing_if = "Option::is_none")] - pub visa_checkout: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletAmexExpressCheckout {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletApplePay {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletGooglePay {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletMasterpass { - /// Owner's verified billing address. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_address: Option
, - - /// Owner's verified email. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// Owner's verified full name. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Owner's verified shipping address. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_address: Option
, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletSamsungPay {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WalletVisaCheckout { - /// Owner's verified billing address. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_address: Option
, - - /// Owner's verified email. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// Owner's verified full name. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Owner's verified shipping address. - /// - /// Values are verified or provided by the wallet directly (if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_address: Option
, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodFpx { - /// The customer's bank, if provided. - /// - /// Can be one of `affin_bank`, `alliance_bank`, `ambank`, `bank_islam`, `bank_muamalat`, `bank_rakyat`, `bsn`, `cimb`, `hong_leong_bank`, `hsbc`, `kfh`, `maybank2u`, `ocbc`, `public_bank`, `rhb`, `standard_chartered`, `uob`, `deutsche_bank`, `maybank2e`, or `pb_enterprise`. - pub bank: PaymentMethodFpxBank, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodIdeal { - /// The customer's bank, if provided. - /// - /// Can be one of `abn_amro`, `asn_bank`, `bunq`, `handelsbanken`, `ing`, `knab`, `moneyou`, `rabobank`, `regiobank`, `sns_bank`, `triodos_bank`, or `van_lanschot`. - #[serde(skip_serializing_if = "Option::is_none")] - pub bank: Option, - - /// The Bank Identifier Code of the customer's bank, if the bank was provided. - #[serde(skip_serializing_if = "Option::is_none")] - pub bic: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodSepaDebit { - /// Bank code of bank associated with the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option, - - /// Branch code of bank associated with the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub branch_code: Option, - - /// Two-letter ISO code representing the country the bank account is located in. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Uniquely identifies this particular bank account. - /// - /// You can use this attribute to check whether two bank accounts are the same. - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - /// Last four characters of the IBAN. - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ThreeDSecureUsage { - /// Whether 3D Secure is supported on this card. - pub supported: bool, -} - -/// The parameters for `PaymentMethod::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreatePaymentMethod<'a> { - /// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit: Option, - - /// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_details: Option, - - /// The `Customer` to whom the original PaymentMethod is attached. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// If this is an `fpx` PaymentMethod, this hash contains details about the FPX payment method. - #[serde(skip_serializing_if = "Option::is_none")] - pub fpx: Option, - - /// If this is an `ideal` PaymentMethod, this hash contains details about the iDEAL payment method. - #[serde(skip_serializing_if = "Option::is_none")] - pub ideal: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The PaymentMethod to share. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub sepa_debit: Option, - - /// The type of the PaymentMethod. - /// - /// An additional hash is included on the PaymentMethod with a name matching this value. - /// It contains additional information specific to the PaymentMethod type. - /// Required unless `payment_method` is specified (see the [Cloning PaymentMethods](https://stripe.com/docs/payments/payment-methods/connect#cloning-payment-methods) guide). - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -impl<'a> CreatePaymentMethod<'a> { - pub fn new() -> Self { - CreatePaymentMethod { - au_becs_debit: Default::default(), - billing_details: Default::default(), - customer: Default::default(), - expand: Default::default(), - fpx: Default::default(), - ideal: Default::default(), - metadata: Default::default(), - payment_method: Default::default(), - sepa_debit: Default::default(), - type_: Default::default(), - } - } -} - -/// The parameters for `PaymentMethod::list`. -#[derive(Clone, Debug, Serialize)] -pub struct ListPaymentMethods<'a> { - /// The ID of the customer whose PaymentMethods will be retrieved. - pub customer: CustomerId, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// A required filter on the list, based on the object `type` field. - #[serde(rename = "type")] - pub type_: PaymentMethodTypeFilter, -} - -impl<'a> ListPaymentMethods<'a> { - pub fn new(customer: CustomerId, type_: PaymentMethodTypeFilter) -> Self { - ListPaymentMethods { - customer, - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - type_, - } - } -} - -/// The parameters for `PaymentMethod::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdatePaymentMethod<'a> { - /// If this is an `au_becs_debit` PaymentMethod, this hash contains details about the bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit: Option, - - /// Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_details: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// If this is a `sepa_debit` PaymentMethod, this hash contains details about the SEPA debit bank account. - #[serde(skip_serializing_if = "Option::is_none")] - pub sepa_debit: Option, -} - -impl<'a> UpdatePaymentMethod<'a> { - pub fn new() -> Self { - UpdatePaymentMethod { - au_becs_debit: Default::default(), - billing_details: Default::default(), - expand: Default::default(), - metadata: Default::default(), - sepa_debit: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePaymentMethodAuBecsDebit { - pub account_number: String, - - pub bsb_number: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePaymentMethodFpx { - pub bank: CreatePaymentMethodFpxBank, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePaymentMethodIdeal { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePaymentMethodSepaDebit { - pub iban: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdatePaymentMethodAuBecsDebit {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdatePaymentMethodSepaDebit {} - -/// An enum representing the possible values of an `CreatePaymentMethodFpx`'s `bank` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePaymentMethodFpxBank { - AffinBank, - AllianceBank, - Ambank, - BankIslam, - BankMuamalat, - BankRakyat, - Bsn, - Cimb, - DeutscheBank, - HongLeongBank, - Hsbc, - Kfh, - Maybank2e, - Maybank2u, - Ocbc, - PbEnterprise, - PublicBank, - Rhb, - StandardChartered, - Uob, -} - -impl CreatePaymentMethodFpxBank { - pub fn as_str(self) -> &'static str { - match self { - CreatePaymentMethodFpxBank::AffinBank => "affin_bank", - CreatePaymentMethodFpxBank::AllianceBank => "alliance_bank", - CreatePaymentMethodFpxBank::Ambank => "ambank", - CreatePaymentMethodFpxBank::BankIslam => "bank_islam", - CreatePaymentMethodFpxBank::BankMuamalat => "bank_muamalat", - CreatePaymentMethodFpxBank::BankRakyat => "bank_rakyat", - CreatePaymentMethodFpxBank::Bsn => "bsn", - CreatePaymentMethodFpxBank::Cimb => "cimb", - CreatePaymentMethodFpxBank::DeutscheBank => "deutsche_bank", - CreatePaymentMethodFpxBank::HongLeongBank => "hong_leong_bank", - CreatePaymentMethodFpxBank::Hsbc => "hsbc", - CreatePaymentMethodFpxBank::Kfh => "kfh", - CreatePaymentMethodFpxBank::Maybank2e => "maybank2e", - CreatePaymentMethodFpxBank::Maybank2u => "maybank2u", - CreatePaymentMethodFpxBank::Ocbc => "ocbc", - CreatePaymentMethodFpxBank::PbEnterprise => "pb_enterprise", - CreatePaymentMethodFpxBank::PublicBank => "public_bank", - CreatePaymentMethodFpxBank::Rhb => "rhb", - CreatePaymentMethodFpxBank::StandardChartered => "standard_chartered", - CreatePaymentMethodFpxBank::Uob => "uob", - } - } -} - -impl AsRef for CreatePaymentMethodFpxBank { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePaymentMethodFpxBank { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreatePaymentMethodIdeal`'s `bank` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePaymentMethodIdealBank { - AbnAmro, - AsnBank, - Bunq, - Handelsbanken, - Ing, - Knab, - Moneyou, - Rabobank, - Regiobank, - SnsBank, - TriodosBank, - VanLanschot, -} - -impl CreatePaymentMethodIdealBank { - pub fn as_str(self) -> &'static str { - match self { - CreatePaymentMethodIdealBank::AbnAmro => "abn_amro", - CreatePaymentMethodIdealBank::AsnBank => "asn_bank", - CreatePaymentMethodIdealBank::Bunq => "bunq", - CreatePaymentMethodIdealBank::Handelsbanken => "handelsbanken", - CreatePaymentMethodIdealBank::Ing => "ing", - CreatePaymentMethodIdealBank::Knab => "knab", - CreatePaymentMethodIdealBank::Moneyou => "moneyou", - CreatePaymentMethodIdealBank::Rabobank => "rabobank", - CreatePaymentMethodIdealBank::Regiobank => "regiobank", - CreatePaymentMethodIdealBank::SnsBank => "sns_bank", - CreatePaymentMethodIdealBank::TriodosBank => "triodos_bank", - CreatePaymentMethodIdealBank::VanLanschot => "van_lanschot", - } - } -} - -impl AsRef for CreatePaymentMethodIdealBank { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePaymentMethodIdealBank { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `PaymentMethodFpx`'s `bank` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodFpxBank { - AffinBank, - AllianceBank, - Ambank, - BankIslam, - BankMuamalat, - BankRakyat, - Bsn, - Cimb, - DeutscheBank, - HongLeongBank, - Hsbc, - Kfh, - Maybank2e, - Maybank2u, - Ocbc, - PbEnterprise, - PublicBank, - Rhb, - StandardChartered, - Uob, -} - -impl PaymentMethodFpxBank { - pub fn as_str(self) -> &'static str { - match self { - PaymentMethodFpxBank::AffinBank => "affin_bank", - PaymentMethodFpxBank::AllianceBank => "alliance_bank", - PaymentMethodFpxBank::Ambank => "ambank", - PaymentMethodFpxBank::BankIslam => "bank_islam", - PaymentMethodFpxBank::BankMuamalat => "bank_muamalat", - PaymentMethodFpxBank::BankRakyat => "bank_rakyat", - PaymentMethodFpxBank::Bsn => "bsn", - PaymentMethodFpxBank::Cimb => "cimb", - PaymentMethodFpxBank::DeutscheBank => "deutsche_bank", - PaymentMethodFpxBank::HongLeongBank => "hong_leong_bank", - PaymentMethodFpxBank::Hsbc => "hsbc", - PaymentMethodFpxBank::Kfh => "kfh", - PaymentMethodFpxBank::Maybank2e => "maybank2e", - PaymentMethodFpxBank::Maybank2u => "maybank2u", - PaymentMethodFpxBank::Ocbc => "ocbc", - PaymentMethodFpxBank::PbEnterprise => "pb_enterprise", - PaymentMethodFpxBank::PublicBank => "public_bank", - PaymentMethodFpxBank::Rhb => "rhb", - PaymentMethodFpxBank::StandardChartered => "standard_chartered", - PaymentMethodFpxBank::Uob => "uob", - } - } -} - -impl AsRef for PaymentMethodFpxBank { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PaymentMethodFpxBank { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `PaymentMethodIdeal`'s `bank` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodIdealBank { - AbnAmro, - AsnBank, - Bunq, - Handelsbanken, - Ing, - Knab, - Moneyou, - Rabobank, - Regiobank, - SnsBank, - TriodosBank, - VanLanschot, -} - -impl PaymentMethodIdealBank { - pub fn as_str(self) -> &'static str { - match self { - PaymentMethodIdealBank::AbnAmro => "abn_amro", - PaymentMethodIdealBank::AsnBank => "asn_bank", - PaymentMethodIdealBank::Bunq => "bunq", - PaymentMethodIdealBank::Handelsbanken => "handelsbanken", - PaymentMethodIdealBank::Ing => "ing", - PaymentMethodIdealBank::Knab => "knab", - PaymentMethodIdealBank::Moneyou => "moneyou", - PaymentMethodIdealBank::Rabobank => "rabobank", - PaymentMethodIdealBank::Regiobank => "regiobank", - PaymentMethodIdealBank::SnsBank => "sns_bank", - PaymentMethodIdealBank::TriodosBank => "triodos_bank", - PaymentMethodIdealBank::VanLanschot => "van_lanschot", - } - } -} - -impl AsRef for PaymentMethodIdealBank { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PaymentMethodIdealBank { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `PaymentMethodIdeal`'s `bic` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodIdealBic { - #[serde(rename = "ABNANL2A")] - Abnanl2a, - #[serde(rename = "ASNBNL21")] - Asnbnl21, - #[serde(rename = "BUNQNL2A")] - Bunqnl2a, - #[serde(rename = "FVLBNL22")] - Fvlbnl22, - #[serde(rename = "HANDNL2A")] - Handnl2a, - #[serde(rename = "INGBNL2A")] - Ingbnl2a, - #[serde(rename = "KNABNL2H")] - Knabnl2h, - #[serde(rename = "MOYONL21")] - Moyonl21, - #[serde(rename = "RABONL2U")] - Rabonl2u, - #[serde(rename = "RBRBNL21")] - Rbrbnl21, - #[serde(rename = "SNSBNL2A")] - Snsbnl2a, - #[serde(rename = "TRIONL2U")] - Trionl2u, -} - -impl PaymentMethodIdealBic { - pub fn as_str(self) -> &'static str { - match self { - PaymentMethodIdealBic::Abnanl2a => "ABNANL2A", - PaymentMethodIdealBic::Asnbnl21 => "ASNBNL21", - PaymentMethodIdealBic::Bunqnl2a => "BUNQNL2A", - PaymentMethodIdealBic::Fvlbnl22 => "FVLBNL22", - PaymentMethodIdealBic::Handnl2a => "HANDNL2A", - PaymentMethodIdealBic::Ingbnl2a => "INGBNL2A", - PaymentMethodIdealBic::Knabnl2h => "KNABNL2H", - PaymentMethodIdealBic::Moyonl21 => "MOYONL21", - PaymentMethodIdealBic::Rabonl2u => "RABONL2U", - PaymentMethodIdealBic::Rbrbnl21 => "RBRBNL21", - PaymentMethodIdealBic::Snsbnl2a => "SNSBNL2A", - PaymentMethodIdealBic::Trionl2u => "TRIONL2U", - } - } -} - -impl AsRef for PaymentMethodIdealBic { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PaymentMethodIdealBic { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `PaymentMethod`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodType { - AuBecsDebit, - Card, - Fpx, - Ideal, - SepaDebit, -} - -impl PaymentMethodType { - pub fn as_str(self) -> &'static str { - match self { - PaymentMethodType::AuBecsDebit => "au_becs_debit", - PaymentMethodType::Card => "card", - PaymentMethodType::Fpx => "fpx", - PaymentMethodType::Ideal => "ideal", - PaymentMethodType::SepaDebit => "sepa_debit", - } - } -} - -impl AsRef for PaymentMethodType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PaymentMethodType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListPaymentMethods`'s `type_` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodTypeFilter { - AuBecsDebit, - Card, - CardPresent, - Fpx, - Ideal, - SepaDebit, -} - -impl PaymentMethodTypeFilter { - pub fn as_str(self) -> &'static str { - match self { - PaymentMethodTypeFilter::AuBecsDebit => "au_becs_debit", - PaymentMethodTypeFilter::Card => "card", - PaymentMethodTypeFilter::CardPresent => "card_present", - PaymentMethodTypeFilter::Fpx => "fpx", - PaymentMethodTypeFilter::Ideal => "ideal", - PaymentMethodTypeFilter::SepaDebit => "sepa_debit", - } - } -} - -impl AsRef for PaymentMethodTypeFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PaymentMethodTypeFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `WalletDetails`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum WalletDetailsType { - AmexExpressCheckout, - ApplePay, - GooglePay, - Masterpass, - SamsungPay, - VisaCheckout, -} - -impl WalletDetailsType { - pub fn as_str(self) -> &'static str { - match self { - WalletDetailsType::AmexExpressCheckout => "amex_express_checkout", - WalletDetailsType::ApplePay => "apple_pay", - WalletDetailsType::GooglePay => "google_pay", - WalletDetailsType::Masterpass => "masterpass", - WalletDetailsType::SamsungPay => "samsung_pay", - WalletDetailsType::VisaCheckout => "visa_checkout", - } - } -} - -impl AsRef for WalletDetailsType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for WalletDetailsType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/payment_method_ext.rs b/ft-stripe/src/resources/payment_method_ext.rs deleted file mode 100644 index acc5a49..0000000 --- a/ft-stripe/src/resources/payment_method_ext.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, PaymentMethodId}; -use crate::resources::PaymentMethod; -use serde::{Deserialize, Serialize}; - -/// The parameters for `PaymentMethod::attach` -/// -/// For more details see [https://stripe.com/docs/api/payment_methods/attach](https://stripe.com/docs/api/payment_methods/attach). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AttachPaymentMethod { - pub customer: CustomerId, -} - -impl PaymentMethod { - /// Attach a payment method to a customer - /// - /// For more details see [https://stripe.com/docs/api/payment_methods/attach](https://stripe.com/docs/api/payment_methods/attach). - pub fn attach( - client: &Client, - payment_method_id: &PaymentMethodId, - params: AttachPaymentMethod, - ) -> Response { - client.post_form(&format!("/payment_methods/{}/attach", payment_method_id), params) - } - - /// Detach a payment method from its customer - /// - /// For more details see [https://stripe.com/docs/api/payment_methods/detach](https://stripe.com/docs/api/payment_methods/detach). - pub fn detach(client: &Client, payment_method_id: &PaymentMethodId) -> Response { - client.post(&format!("/payment_methods/{}/detach", payment_method_id)) - } -} diff --git a/ft-stripe/src/resources/payment_source.rs b/ft-stripe/src/resources/payment_source.rs deleted file mode 100644 index 49a545d..0000000 --- a/ft-stripe/src/resources/payment_source.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::ids::{PaymentSourceId, SourceId, TokenId}; -use crate::params::Object; -use crate::resources::{Account, AlipayAccount, BankAccount, Card, Currency, Source}; -use serde::ser::SerializeStruct; -use serde::{Deserialize, Serialize}; - -/// A PaymentSourceParams represents all of the supported ways that can -/// be used to creating a new customer with a payment method or creating -/// a payment method directly for a customer via `Customer::attach_source`. -/// -/// Not to be confused with `SourceParams` which is used by `Source::create` -/// to create a source that is not necessarily attached to a customer. -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(untagged)] -pub enum PaymentSourceParams { - /// Creates a payment method (e.g. card or bank account) from tokenized data, - /// using a token typically received from Stripe Elements. - Token(TokenId), - - /// Attach an existing source to an existing customer or - /// create a new customer from an existing source. - Source(SourceId), -} - -/// A PaymentSource represents a payment method _associated with a customer or charge_. -/// This value is usually returned as a subresource on another request. -/// -/// Not to be confused with `Source` which represents a "generic" payment method -/// returned by the `Source::get` (which could still be a credit card, etc) -/// but is not necessarily attached to either a customer or charge. - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum PaymentSource { - Card(Card), - Source(Source), - Account(Account), - BankAccount(BankAccount), - AlipayAccount(AlipayAccount), -} - -impl Object for PaymentSource { - type Id = PaymentSourceId; - fn id(&self) -> Self::Id { - match self { - PaymentSource::Card(x) => PaymentSourceId::Card(x.id()), - PaymentSource::Source(x) => PaymentSourceId::Source(x.id()), - PaymentSource::Account(x) => PaymentSourceId::Account(x.id()), - PaymentSource::BankAccount(x) => PaymentSourceId::BankAccount(x.id()), - PaymentSource::AlipayAccount(x) => PaymentSourceId::AlipayAccount(x.id()), - } - } - fn object(&self) -> &'static str { - match self { - PaymentSource::Card(x) => x.object(), - PaymentSource::Source(x) => x.object(), - PaymentSource::Account(x) => x.object(), - PaymentSource::BankAccount(x) => x.object(), - PaymentSource::AlipayAccount(x) => x.object(), - } - } -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct BankAccountParams<'a> { - pub country: &'a str, - pub currency: Currency, - pub account_holder_name: Option<&'a str>, - pub account_holder_type: Option<&'a str>, - pub routing_number: Option<&'a str>, - pub account_number: &'a str, -} - -impl<'a> serde::ser::Serialize for BankAccountParams<'a> { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - let mut s = serializer.serialize_struct("BankAccountParams", 6)?; - s.serialize_field("object", "bank_account")?; - s.serialize_field("country", &self.country)?; - s.serialize_field("currency", &self.currency)?; - s.serialize_field("account_holder_name", &self.account_holder_name)?; - s.serialize_field("routing_number", &self.routing_number)?; - s.serialize_field("account_number", &self.account_number)?; - s.end() - } -} - -#[derive(Clone, Debug, Default, Deserialize)] -pub struct CardParams<'a> { - pub exp_month: &'a str, // eg. "12" - pub exp_year: &'a str, // eg. "17" or 2017" - - pub number: &'a str, // card number - pub name: Option<&'a str>, // cardholder's full name - pub cvc: Option<&'a str>, // card security code -} - -impl<'a> serde::ser::Serialize for CardParams<'a> { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - let mut s = serializer.serialize_struct("CardParams", 6)?; - s.serialize_field("object", "card")?; - s.serialize_field("exp_month", &self.exp_month)?; - s.serialize_field("exp_year", &self.exp_year)?; - s.serialize_field("number", &self.number)?; - s.serialize_field("name", &self.name)?; - s.serialize_field("cvc", &self.cvc)?; - s.end() - } -} diff --git a/ft-stripe/src/resources/payout.rs b/ft-stripe/src/resources/payout.rs deleted file mode 100644 index d017832..0000000 --- a/ft-stripe/src/resources/payout.rs +++ /dev/null @@ -1,383 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::PayoutId; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{BalanceTransaction, BankAccount, Card, Currency}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Payout". -/// -/// For more details see [https://stripe.com/docs/api/payouts/object](https://stripe.com/docs/api/payouts/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Payout { - /// Unique identifier for the object. - pub id: PayoutId, - - /// Amount (in %s) to be transferred to your bank account or debit card. - pub amount: i64, - - /// Date the payout is expected to arrive in the bank. - /// - /// This factors in delays like weekends or bank holidays. - pub arrival_date: Timestamp, - - /// Returns `true` if the payout was created by an [automated payout schedule](https://stripe.com/docs/payouts#payout-schedule), and `false` if it was [requested manually](https://stripe.com/docs/payouts#manual-payouts). - pub automatic: bool, - - /// ID of the balance transaction that describes the impact of this payout on your account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// ID of the bank account or card the payout was sent to. - #[serde(skip_serializing_if = "Option::is_none")] - pub destination: Option>, - - /// If the payout failed or was canceled, this will be the ID of the balance transaction that reversed the initial balance transaction, and puts the funds from the failed payout back in your balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_balance_transaction: Option>, - - /// Error code explaining reason for payout failure if available. - /// - /// See [Types of payout failures](https://stripe.com/docs/api#payout_failures) for a list of failure codes. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_code: Option, - - /// Message to user further explaining reason for payout failure if available. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_message: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// The method used to send this payout, which can be `standard` or `instant`. - /// - /// `instant` is only supported for payouts to debit cards. - /// (See [Instant payouts for marketplaces](https://stripe.com/blog/instant-payouts-for-marketplaces) for more information.). - pub method: String, - - /// The source balance this payout came from. - /// - /// One of `card`, `fpx`, or `bank_account`. - pub source_type: String, - - /// Extra information about a payout to be displayed on the user's bank statement. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// Current status of the payout: `paid`, `pending`, `in_transit`, `canceled` or `failed`. - /// - /// A payout is `pending` until it is submitted to the bank, when it becomes `in_transit`. - /// The status then changes to `paid` if the transaction goes through, or to `failed` or `canceled` (within 5 business days). - /// Some failed payouts may initially show as `paid` but then change to `failed`. - pub status: String, - - /// Can be `bank_account` or `card`. - #[serde(rename = "type")] - pub type_: PayoutType, -} - -impl Payout { - /// Returns a list of existing payouts sent to third-party bank accounts or that Stripe has sent you. - /// - /// The payouts are returned in sorted order, with the most recently created payouts appearing first. - // pub fn list(client: &Client, params: ListPayouts<'_>) -> Response> { - // client.get_query("/payouts", ¶ms) - // } - - /// To send funds to your own bank account, you create a new payout object. - /// - /// Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the payout amount, or you’ll receive an “Insufficient Funds” error. If your API key is in test mode, money won’t actually be sent, though everything else will occur as if in live mode. If you are creating a manual payout on a Stripe account that uses multiple payment source types, you’ll need to specify the source type balance that the payout should draw from. - /// The [balance object](https://stripe.com/docs/api#balance_object) details available and pending amounts by source type. - pub fn create(client: &Client, params: CreatePayout<'_>) -> Response { - client.post_form("/payouts", ¶ms) - } - - /// Retrieves the details of an existing payout. - /// - /// Supply the unique payout ID from either a payout creation request or the payout list, and Stripe will return the corresponding payout information. - pub fn retrieve(client: &Client, id: &PayoutId, expand: &[&str]) -> Response { - client.get_query(&format!("/payouts/{}", id), &Expand { expand }) - } - - /// Updates the specified payout by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. - /// This request accepts only the metadata as arguments. - pub fn update(client: &Client, id: &PayoutId, params: UpdatePayout<'_>) -> Response { - client.post_form(&format!("/payouts/{}", id), ¶ms) - } -} - -impl Object for Payout { - type Id = PayoutId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "payout" - } -} - -/// The parameters for `Payout::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreatePayout<'a> { - /// A positive integer in cents representing how much to payout. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The method used to send this payout, which can be `standard` or `instant`. - /// - /// `instant` is only supported for payouts to debit cards. - /// (See [Instant payouts for marketplaces for more information](https://stripe.com/blog/instant-payouts-for-marketplaces).). - #[serde(skip_serializing_if = "Option::is_none")] - pub method: Option, - - /// The balance type of your Stripe balance to draw this payout from. - /// - /// Balances for different payment sources are kept separately. - /// You can find the amounts with the balances API. - /// One of `bank_account`, `card`, or `fpx`. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_type: Option, - - /// A string to be displayed on the recipient's bank or card statement. - /// - /// This may be at most 22 characters. - /// Attempting to use a `statement_descriptor` longer than 22 characters will return an error. - /// Note: Most banks will truncate this information and/or display it inconsistently. - /// Some may not display it at all. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, -} - -impl<'a> CreatePayout<'a> { - pub fn new(amount: i64, currency: Currency) -> Self { - CreatePayout { - amount, - currency, - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - method: Default::default(), - source_type: Default::default(), - statement_descriptor: Default::default(), - } - } -} - -/// The parameters for `Payout::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListPayouts<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub arrival_date: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return payouts that have the given status: `pending`, `paid`, `failed`, or `canceled`. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option<&'a str>, -} - -impl<'a> ListPayouts<'a> { - pub fn new() -> Self { - ListPayouts { - arrival_date: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - status: Default::default(), - } - } -} - -/// The parameters for `Payout::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdatePayout<'a> { - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdatePayout<'a> { - pub fn new() -> Self { - UpdatePayout { expand: Default::default(), metadata: Default::default() } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "object", rename_all = "snake_case")] -pub enum PayoutDestination { - BankAccount(BankAccount), - Card(Card), -} - -/// An enum representing the possible values of an `CreatePayout`'s `method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PayoutMethod { - Instant, - Standard, -} - -impl PayoutMethod { - pub fn as_str(self) -> &'static str { - match self { - PayoutMethod::Instant => "instant", - PayoutMethod::Standard => "standard", - } - } -} - -impl AsRef for PayoutMethod { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PayoutMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreatePayout`'s `source_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PayoutSourceType { - BankAccount, - Card, - Fpx, -} - -impl PayoutSourceType { - pub fn as_str(self) -> &'static str { - match self { - PayoutSourceType::BankAccount => "bank_account", - PayoutSourceType::Card => "card", - PayoutSourceType::Fpx => "fpx", - } - } -} - -impl AsRef for PayoutSourceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PayoutSourceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Payout`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PayoutType { - BankAccount, - Card, -} - -impl PayoutType { - pub fn as_str(self) -> &'static str { - match self { - PayoutType::BankAccount => "bank_account", - PayoutType::Card => "card", - } - } -} - -impl AsRef for PayoutType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PayoutType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/payout_ext.rs b/ft-stripe/src/resources/payout_ext.rs deleted file mode 100644 index ff3ce7c..0000000 --- a/ft-stripe/src/resources/payout_ext.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{PayoutDestinationId, PayoutId}; -use crate::params::Object; -use crate::resources::{Payout, PayoutDestination}; - -impl Payout { - /// Cancels the payout. - /// - /// For more details see [https://stripe.com/docs/api/payouts/cancel](https://stripe.com/docs/api/payouts/cancel). - pub fn cancel(client: &Client, id: &PayoutId) -> Response { - client.post(&format!("/payouts/{}/cancel", id)) - } -} - -impl Object for PayoutDestination { - type Id = PayoutDestinationId; - fn id(&self) -> Self::Id { - match self { - PayoutDestination::BankAccount(x) => PayoutDestinationId::BankAccount(x.id()), - PayoutDestination::Card(x) => PayoutDestinationId::Card(x.id()), - } - } - fn object(&self) -> &'static str { - match self { - PayoutDestination::BankAccount(x) => x.object(), - PayoutDestination::Card(x) => x.object(), - } - } -} diff --git a/ft-stripe/src/resources/person.rs b/ft-stripe/src/resources/person.rs deleted file mode 100644 index 69b4fca..0000000 --- a/ft-stripe/src/resources/person.rs +++ /dev/null @@ -1,398 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::PersonId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{Address, Dob, File}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Person". -/// -/// For more details see [https://stripe.com/docs/api/persons/object](https://stripe.com/docs/api/persons/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Person { - /// Unique identifier for the object. - pub id: PersonId, - - #[serde(skip_serializing_if = "Option::is_none")] - pub account: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kana: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kanji: Option
, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dob: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub gender: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub id_number_provided: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub maiden_name: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub relationship: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub requirements: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ssn_last_4_provided: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -impl Object for Person { - type Id = PersonId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "person" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonVerification { - /// A document showing address, either a passport, local ID card, or utility bill from a well-known utility company. - #[serde(skip_serializing_if = "Option::is_none")] - pub additional_document: Option, - - /// A user-displayable string describing the verification state for the person. - /// - /// For example, this may say "Provided identity information could not be verified". - #[serde(skip_serializing_if = "Option::is_none")] - pub details: Option, - - /// One of `document_address_mismatch`, `document_dob_mismatch`, `document_duplicate_type`, `document_id_number_mismatch`, `document_name_mismatch`, `document_nationality_mismatch`, `failed_keyed_identity`, or `failed_other`. - /// - /// A machine-readable code specifying the verification state for the person. - #[serde(skip_serializing_if = "Option::is_none")] - pub details_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub document: Option, - - /// The state of verification for the person. - /// - /// Possible values are `unverified`, `pending`, or `verified`. - pub status: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonVerificationDocument { - /// The back of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. - #[serde(skip_serializing_if = "Option::is_none")] - pub back: Option>, - - /// A user-displayable string describing the verification state of this document. - /// - /// For example, if a document is uploaded and the picture is too fuzzy, this may say "Identity document is too unclear to read". - #[serde(skip_serializing_if = "Option::is_none")] - pub details: Option, - - /// One of `document_corrupt`, `document_country_not_supported`, `document_expired`, `document_failed_copy`, `document_failed_other`, `document_failed_test_mode`, `document_fraudulent`, `document_failed_greyscale`, `document_incomplete`, `document_invalid`, `document_manipulated`, `document_missing_back`, `document_missing_front`, `document_not_readable`, `document_not_uploaded`, `document_photo_mismatch`, `document_too_large`, or `document_type_not_supported`. - /// - /// A machine-readable code specifying the verification state for this document. - #[serde(skip_serializing_if = "Option::is_none")] - pub details_code: Option, - - /// The front of an ID returned by a [file upload](https://stripe.com/docs/api#create_file) with a `purpose` value of `identity_document`. - #[serde(skip_serializing_if = "Option::is_none")] - pub front: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonRelationship { - /// Whether the person is a director of the account's legal entity. - /// - /// Currently only required for accounts in the EU. - /// Directors are typically members of the governing board of the company, or responsible for ensuring the company meets its regulatory obligations. - #[serde(skip_serializing_if = "Option::is_none")] - pub director: Option, - - /// Whether the person has significant responsibility to control, manage, or direct the organization. - #[serde(skip_serializing_if = "Option::is_none")] - pub executive: Option, - - /// Whether the person is an owner of the account’s legal entity. - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - - /// The percent owned by the person of the account's legal entity. - #[serde(skip_serializing_if = "Option::is_none")] - pub percent_ownership: Option, - - /// Whether the person is authorized as the primary representative of the account. - /// - /// This is the person nominated by the business to provide information about themselves, and general information about the account. - /// There can only be one representative at any given time. - /// At the time the account is created, this person should be set to the person responsible for opening the account. - #[serde(skip_serializing_if = "Option::is_none")] - pub representative: Option, - - /// The person's title (e.g., CEO, Support Engineer). - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonRequirements { - /// Fields that need to be collected to keep the person's account enabled. - /// - /// If not collected by the account's `current_deadline`, these fields appear in `past_due` as well, and the account is disabled. - pub currently_due: Vec, - - /// The fields that need to be collected again because validation or verification failed for some reason. - pub errors: Vec, - - /// Fields that need to be collected assuming all volume thresholds are reached. - /// - /// As fields are needed, they are moved to `currently_due` and the account's `current_deadline` is set. - pub eventually_due: Vec, - - /// Fields that weren't collected by the account's `current_deadline`. - /// - /// These fields need to be collected to enable payouts for the person's account. - pub past_due: Vec, - - /// Fields that may become required depending on the results of verification or review. - /// - /// An empty array unless an asynchronous verification is pending. - /// If verification fails, the fields in this array become required and move to `currently_due` or `past_due`. - pub pending_verification: Vec, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AccountRequirementsError { - /// The code for the type of error. - pub code: AccountRequirementsErrorCode, - - /// An informative message that indicates the error type and provides additional details about the error. - pub reason: String, - - /// The specific user onboarding requirement field (in the requirements hash) that needs to be resolved. - pub requirement: String, -} - -/// An enum representing the possible values of an `AccountRequirementsError`'s `code` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum AccountRequirementsErrorCode { - InvalidAddressCityStatePostalCode, - InvalidStreetAddress, - InvalidValueOther, - VerificationDocumentAddressMismatch, - VerificationDocumentAddressMissing, - VerificationDocumentCorrupt, - VerificationDocumentCountryNotSupported, - VerificationDocumentDobMismatch, - VerificationDocumentDuplicateType, - VerificationDocumentExpired, - VerificationDocumentFailedCopy, - VerificationDocumentFailedGreyscale, - VerificationDocumentFailedOther, - VerificationDocumentFailedTestMode, - VerificationDocumentFraudulent, - VerificationDocumentIdNumberMismatch, - VerificationDocumentIdNumberMissing, - VerificationDocumentIncomplete, - VerificationDocumentInvalid, - VerificationDocumentManipulated, - VerificationDocumentMissingBack, - VerificationDocumentMissingFront, - VerificationDocumentNameMismatch, - VerificationDocumentNameMissing, - VerificationDocumentNationalityMismatch, - VerificationDocumentNotReadable, - VerificationDocumentNotUploaded, - VerificationDocumentPhotoMismatch, - VerificationDocumentTooLarge, - VerificationDocumentTypeNotSupported, - VerificationFailedAddressMatch, - VerificationFailedBusinessIecNumber, - VerificationFailedDocumentMatch, - VerificationFailedIdNumberMatch, - VerificationFailedKeyedIdentity, - VerificationFailedKeyedMatch, - VerificationFailedNameMatch, - VerificationFailedOther, -} - -impl AccountRequirementsErrorCode { - pub fn as_str(self) -> &'static str { - match self { - AccountRequirementsErrorCode::InvalidAddressCityStatePostalCode => { - "invalid_address_city_state_postal_code" - } - AccountRequirementsErrorCode::InvalidStreetAddress => "invalid_street_address", - AccountRequirementsErrorCode::InvalidValueOther => "invalid_value_other", - AccountRequirementsErrorCode::VerificationDocumentAddressMismatch => { - "verification_document_address_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentAddressMissing => { - "verification_document_address_missing" - } - AccountRequirementsErrorCode::VerificationDocumentCorrupt => { - "verification_document_corrupt" - } - AccountRequirementsErrorCode::VerificationDocumentCountryNotSupported => { - "verification_document_country_not_supported" - } - AccountRequirementsErrorCode::VerificationDocumentDobMismatch => { - "verification_document_dob_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentDuplicateType => { - "verification_document_duplicate_type" - } - AccountRequirementsErrorCode::VerificationDocumentExpired => { - "verification_document_expired" - } - AccountRequirementsErrorCode::VerificationDocumentFailedCopy => { - "verification_document_failed_copy" - } - AccountRequirementsErrorCode::VerificationDocumentFailedGreyscale => { - "verification_document_failed_greyscale" - } - AccountRequirementsErrorCode::VerificationDocumentFailedOther => { - "verification_document_failed_other" - } - AccountRequirementsErrorCode::VerificationDocumentFailedTestMode => { - "verification_document_failed_test_mode" - } - AccountRequirementsErrorCode::VerificationDocumentFraudulent => { - "verification_document_fraudulent" - } - AccountRequirementsErrorCode::VerificationDocumentIdNumberMismatch => { - "verification_document_id_number_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentIdNumberMissing => { - "verification_document_id_number_missing" - } - AccountRequirementsErrorCode::VerificationDocumentIncomplete => { - "verification_document_incomplete" - } - AccountRequirementsErrorCode::VerificationDocumentInvalid => { - "verification_document_invalid" - } - AccountRequirementsErrorCode::VerificationDocumentManipulated => { - "verification_document_manipulated" - } - AccountRequirementsErrorCode::VerificationDocumentMissingBack => { - "verification_document_missing_back" - } - AccountRequirementsErrorCode::VerificationDocumentMissingFront => { - "verification_document_missing_front" - } - AccountRequirementsErrorCode::VerificationDocumentNameMismatch => { - "verification_document_name_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentNameMissing => { - "verification_document_name_missing" - } - AccountRequirementsErrorCode::VerificationDocumentNationalityMismatch => { - "verification_document_nationality_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentNotReadable => { - "verification_document_not_readable" - } - AccountRequirementsErrorCode::VerificationDocumentNotUploaded => { - "verification_document_not_uploaded" - } - AccountRequirementsErrorCode::VerificationDocumentPhotoMismatch => { - "verification_document_photo_mismatch" - } - AccountRequirementsErrorCode::VerificationDocumentTooLarge => { - "verification_document_too_large" - } - AccountRequirementsErrorCode::VerificationDocumentTypeNotSupported => { - "verification_document_type_not_supported" - } - AccountRequirementsErrorCode::VerificationFailedAddressMatch => { - "verification_failed_address_match" - } - AccountRequirementsErrorCode::VerificationFailedBusinessIecNumber => { - "verification_failed_business_iec_number" - } - AccountRequirementsErrorCode::VerificationFailedDocumentMatch => { - "verification_failed_document_match" - } - AccountRequirementsErrorCode::VerificationFailedIdNumberMatch => { - "verification_failed_id_number_match" - } - AccountRequirementsErrorCode::VerificationFailedKeyedIdentity => { - "verification_failed_keyed_identity" - } - AccountRequirementsErrorCode::VerificationFailedKeyedMatch => { - "verification_failed_keyed_match" - } - AccountRequirementsErrorCode::VerificationFailedNameMatch => { - "verification_failed_name_match" - } - AccountRequirementsErrorCode::VerificationFailedOther => "verification_failed_other", - } - } -} - -impl AsRef for AccountRequirementsErrorCode { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for AccountRequirementsErrorCode { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/placeholders.rs b/ft-stripe/src/resources/placeholders.rs deleted file mode 100644 index 6bca72e..0000000 --- a/ft-stripe/src/resources/placeholders.rs +++ /dev/null @@ -1,599 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::ids::*; -use crate::params::Object; -use serde::{Deserialize, Serialize}; - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Account { - pub id: AccountId, -} - -#[cfg(not(feature = "connect"))] -impl Object for Account { - type Id = AccountId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "account" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Application { - pub id: (), -} - -#[cfg(not(feature = "connect"))] -impl Object for Application { - type Id = (); - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "application" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ApplicationFee { - pub id: ApplicationFeeId, -} - -#[cfg(not(feature = "connect"))] -impl Object for ApplicationFee { - type Id = ApplicationFeeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "application_fee" - } -} - -#[cfg(not(feature = "checkout"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CheckoutSession { - pub id: CheckoutSessionId, -} - -#[cfg(not(feature = "checkout"))] -impl Object for CheckoutSession { - type Id = CheckoutSessionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "checkout_session" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ConnectCollectionTransfer { - pub id: (), -} - -#[cfg(not(feature = "connect"))] -impl Object for ConnectCollectionTransfer { - type Id = (); - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "connect_collection_transfer" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Coupon { - pub id: CouponId, -} - -#[cfg(not(feature = "billing"))] -impl Object for Coupon { - type Id = CouponId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "coupon" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Discount { - pub id: (), -} - -#[cfg(not(feature = "billing"))] -impl Object for Discount { - type Id = (); - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "discount" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ApplicationFeeRefund { - pub id: ApplicationFeeRefundId, -} - -#[cfg(not(feature = "connect"))] -impl Object for ApplicationFeeRefund { - type Id = ApplicationFeeRefundId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "fee_refund" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Invoice { - pub id: InvoiceId, -} - -#[cfg(not(feature = "billing"))] -impl Object for Invoice { - type Id = InvoiceId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "invoice" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItem { - pub id: InvoiceItemId, -} - -#[cfg(not(feature = "billing"))] -impl Object for InvoiceItem { - type Id = InvoiceItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "invoiceitem" - } -} - -#[cfg(not(feature = "issuing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingAuthorization { - pub id: IssuingAuthorizationId, -} - -#[cfg(not(feature = "issuing"))] -impl Object for IssuingAuthorization { - type Id = IssuingAuthorizationId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.authorization" - } -} - -#[cfg(not(feature = "issuing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCard { - pub id: IssuingCardId, -} - -#[cfg(not(feature = "issuing"))] -impl Object for IssuingCard { - type Id = IssuingCardId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.card" - } -} - -#[cfg(not(feature = "issuing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingCardholder { - pub id: IssuingCardholderId, -} - -#[cfg(not(feature = "issuing"))] -impl Object for IssuingCardholder { - type Id = IssuingCardholderId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.cardholder" - } -} - -#[cfg(not(feature = "issuing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingDispute { - pub id: IssuingDisputeId, -} - -#[cfg(not(feature = "issuing"))] -impl Object for IssuingDispute { - type Id = IssuingDisputeId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.dispute" - } -} - -#[cfg(not(feature = "issuing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct IssuingTransaction { - pub id: IssuingTransactionId, -} - -#[cfg(not(feature = "issuing"))] -impl Object for IssuingTransaction { - type Id = IssuingTransactionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "issuing.transaction" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceLineItem { - pub id: InvoiceLineItemId, -} - -#[cfg(not(feature = "billing"))] -impl Object for InvoiceLineItem { - type Id = InvoiceLineItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "line_item" - } -} - -#[cfg(not(feature = "orders"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Order { - pub id: OrderId, -} - -#[cfg(not(feature = "orders"))] -impl Object for Order { - type Id = OrderId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "order" - } -} - -#[cfg(not(feature = "orders"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OrderItem { - pub id: (), -} - -#[cfg(not(feature = "orders"))] -impl Object for OrderItem { - type Id = (); - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "order_item" - } -} - -#[cfg(not(feature = "orders"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OrderReturn { - pub id: OrderReturnId, -} - -#[cfg(not(feature = "orders"))] -impl Object for OrderReturn { - type Id = OrderReturnId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "order_return" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Person { - pub id: PersonId, -} - -#[cfg(not(feature = "connect"))] -impl Object for Person { - type Id = PersonId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "person" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Plan { - pub id: PlanId, -} - -#[cfg(not(feature = "billing"))] -impl Object for Plan { - type Id = PlanId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "plan" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Recipient { - pub id: RecipientId, -} - -#[cfg(not(feature = "connect"))] -impl Object for Recipient { - type Id = RecipientId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "recipient" - } -} - -#[cfg(not(feature = "fraud"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Review { - pub id: ReviewId, -} - -#[cfg(not(feature = "fraud"))] -impl Object for Review { - type Id = ReviewId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "review" - } -} - -#[cfg(not(feature = "sigma"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ScheduledQueryRun { - pub id: ScheduledQueryRunId, -} - -#[cfg(not(feature = "sigma"))] -impl Object for ScheduledQueryRun { - type Id = ScheduledQueryRunId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "scheduled_query_run" - } -} - -#[cfg(not(feature = "orders"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Sku { - pub id: SkuId, -} - -#[cfg(not(feature = "orders"))] -impl Object for Sku { - type Id = SkuId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "sku" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Subscription { - pub id: SubscriptionId, -} - -#[cfg(not(feature = "billing"))] -impl Object for Subscription { - type Id = SubscriptionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItem { - pub id: SubscriptionItemId, -} - -#[cfg(not(feature = "billing"))] -impl Object for SubscriptionItem { - type Id = SubscriptionItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription_item" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionSchedule { - pub id: SubscriptionScheduleId, -} - -#[cfg(not(feature = "billing"))] -impl Object for SubscriptionSchedule { - type Id = SubscriptionScheduleId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription_schedule" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleRevision { - pub id: (), -} - -#[cfg(not(feature = "billing"))] -impl Object for SubscriptionScheduleRevision { - type Id = (); - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription_schedule_revision" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxId { - pub id: TaxIdId, -} - -#[cfg(not(feature = "billing"))] -impl Object for TaxId { - type Id = TaxIdId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "tax_id" - } -} - -#[cfg(not(feature = "billing"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxRate { - pub id: TaxRateId, -} - -#[cfg(not(feature = "billing"))] -impl Object for TaxRate { - type Id = TaxRateId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "tax_rate" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Topup { - pub id: TopupId, -} - -#[cfg(not(feature = "connect"))] -impl Object for Topup { - type Id = TopupId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "topup" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Transfer { - pub id: TransferId, -} - -#[cfg(not(feature = "connect"))] -impl Object for Transfer { - type Id = TransferId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "transfer" - } -} - -#[cfg(not(feature = "connect"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferReversal { - pub id: TransferReversalId, -} - -#[cfg(not(feature = "connect"))] -impl Object for TransferReversal { - type Id = TransferReversalId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "transfer_reversal" - } -} - -#[cfg(not(feature = "webhook-endpoints"))] -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WebhookEndpoint { - pub id: WebhookEndpointId, -} - -#[cfg(not(feature = "webhook-endpoints"))] -impl Object for WebhookEndpoint { - type Id = WebhookEndpointId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "webhook_endpoint" - } -} diff --git a/ft-stripe/src/resources/plan.rs b/ft-stripe/src/resources/plan.rs deleted file mode 100644 index 6b5a87d..0000000 --- a/ft-stripe/src/resources/plan.rs +++ /dev/null @@ -1,675 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::PlanId; -use crate::params::{ - Deleted, Expand, Expandable, IdOrCreate, List, Metadata, Object, RangeQuery, Timestamp, -}; -use crate::resources::{CreateProduct, Currency, Product, UpTo}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Plan". -/// -/// For more details see [https://stripe.com/docs/api/plans/object](https://stripe.com/docs/api/plans/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Plan { - /// Unique identifier for the object. - pub id: PlanId, - - /// Whether the plan can be used for new purchases. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Specifies a usage aggregation strategy for plans of `usage_type=metered`. - /// - /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. - /// Defaults to `sum`. - #[serde(skip_serializing_if = "Option::is_none")] - pub aggregate_usage: Option, - - /// The unit amount in %s to be charged, represented as a whole integer if possible. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// The unit amount in %s to be charged, represented as a decimal string with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_decimal: Option, - - /// Describes how to compute the price per period. - /// - /// Either `per_unit` or `tiered`. - /// `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`). - /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_scheme: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// The frequency at which a subscription is billed. - /// - /// One of `day`, `week`, `month` or `year`. - #[serde(skip_serializing_if = "Option::is_none")] - pub interval: Option, - - /// The number of intervals (specified in the `interval` attribute) between subscription billings. - /// - /// For example, `interval=month` and `interval_count=3` bills every 3 months. - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// A brief description of the plan, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option, - - /// The product whose pricing this plan determines. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>, - - /// Each element represents a pricing tier. - /// - /// This parameter requires `billing_scheme` to be set to `tiered`. - /// See also the documentation for `billing_scheme`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers: Option>, - - /// Defines if the tiering price should be `graduated` or `volume` based. - /// - /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price. - /// In `graduated` tiering, pricing can change as the quantity grows. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers_mode: Option, - - /// Apply a transformation to the reported usage or set quantity before computing the amount billed. - /// - /// Cannot be combined with `tiers`. - #[serde(skip_serializing_if = "Option::is_none")] - pub transform_usage: Option, - - /// 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). - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, - - /// Configures how the quantity per period should be determined. - /// - /// Can be either `metered` or `licensed`. - /// `licensed` automatically bills the `quantity` set when adding it to a subscription. - /// `metered` aggregates the total usage based on usage records. - /// Defaults to `licensed`. - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_type: Option, -} - -impl Plan { - /// Returns a list of your plans. - pub fn list(client: &Client, params: ListPlans<'_>) -> Response> { - client.get_query("/plans", ¶ms) - } - - /// You can create plans using the API, or in the Stripe [Dashboard](https://dashboard.stripe.com/subscriptions/products). - pub fn create(client: &Client, params: CreatePlan<'_>) -> Response { - client.post_form("/plans", ¶ms) - } - - /// Retrieves the plan with the given ID. - pub fn retrieve(client: &Client, id: &PlanId, expand: &[&str]) -> Response { - client.get_query(&format!("/plans/{}", id), &Expand { expand }) - } - - /// Updates the specified plan by setting the values of the parameters passed. - /// - /// Any parameters not provided are left unchanged. - /// By design, you cannot change a plan’s ID, amount, currency, or billing cycle. - pub fn update(client: &Client, id: &PlanId, params: UpdatePlan<'_>) -> Response { - client.post_form(&format!("/plans/{}", id), ¶ms) - } - - /// Deleting plans means new subscribers can’t be added. - /// - /// Existing subscribers aren’t affected. - pub fn delete(client: &Client, id: &PlanId) -> Response> { - client.delete(&format!("/plans/{}", id)) - } -} - -impl Object for Plan { - type Id = PlanId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "plan" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PlanTier { - /// Price for the entire tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount: Option, - - /// Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount_decimal: Option, - - /// Per unit price for units relevant to the tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, - - /// Up to and including to this quantity will be contained in the tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub up_to: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransformUsage { - /// Divide usage by this number. - pub divide_by: i64, - - /// After division, either round the result `up` or `down`. - pub round: TransformUsageRound, -} - -/// The parameters for `Plan::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreatePlan<'a> { - /// Whether the plan is currently available for new subscriptions. - /// - /// Defaults to `true`. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Specifies a usage aggregation strategy for plans of `usage_type=metered`. - /// - /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. - /// Defaults to `sum`. - #[serde(skip_serializing_if = "Option::is_none")] - pub aggregate_usage: Option, - - /// A positive integer in %s (or 0 for a free plan) representing how much to charge on a recurring basis. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Same as `amount`, but accepts a decimal value with at most 12 decimal places. - /// - /// Only one of `amount` and `amount_decimal` can be set. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_decimal: Option<&'a str>, - - /// Describes how to compute the price per period. - /// - /// Either `per_unit` or `tiered`. - /// `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`). - /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_scheme: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// An identifier randomly generated by Stripe. - /// - /// Used to identify this plan when subscribing a customer. - /// You can optionally override this ID, but the ID must be unique across all plans in your Stripe account. - /// You can, however, use the same plan ID in both live and test modes. - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option<&'a str>, - - /// Specifies billing frequency. - /// - /// Either `day`, `week`, `month` or `year`. - pub interval: PlanInterval, - - /// The number of intervals between subscription billings. - /// - /// For example, `interval=month` and `interval_count=3` bills every 3 months. - /// Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// A brief description of the plan, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option<&'a str>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// Each element represents a pricing tier. - /// - /// This parameter requires `billing_scheme` to be set to `tiered`. - /// See also the documentation for `billing_scheme`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers: Option>, - - /// Defines if the tiering price should be `graduated` or `volume` based. - /// - /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers_mode: Option, - - /// Apply a transformation to the reported usage or set quantity before computing the billed price. - /// - /// Cannot be combined with `tiers`. - #[serde(skip_serializing_if = "Option::is_none")] - pub transform_usage: Option, - - /// 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). - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, - - /// Configures how the quantity per period should be determined. - /// - /// Can be either `metered` or `licensed`. - /// `licensed` automatically bills the `quantity` set when adding it to a subscription. - /// `metered` aggregates the total usage based on usage records. - /// Defaults to `licensed`. - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_type: Option, -} - -impl<'a> CreatePlan<'a> { - pub fn new(currency: Currency, interval: PlanInterval) -> Self { - CreatePlan { - active: Default::default(), - aggregate_usage: Default::default(), - amount: Default::default(), - amount_decimal: Default::default(), - billing_scheme: Default::default(), - currency, - expand: Default::default(), - id: Default::default(), - interval, - interval_count: Default::default(), - metadata: Default::default(), - nickname: Default::default(), - product: Default::default(), - tiers: Default::default(), - tiers_mode: Default::default(), - transform_usage: Default::default(), - trial_period_days: Default::default(), - usage_type: Default::default(), - } - } -} - -/// The parameters for `Plan::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListPlans<'a> { - /// Only return plans that are active or inactive (e.g., pass `false` to list all inactive plans). - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return plans for the given product. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListPlans<'a> { - pub fn new() -> Self { - ListPlans { - active: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - product: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Plan::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdatePlan<'a> { - /// Whether the plan is currently available for new subscriptions. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// A brief description of the plan, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option<&'a str>, - - /// The product the plan belongs to. - /// - /// Note that after updating, statement descriptors and line items of the plan in active subscriptions will be affected. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// 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). - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, -} - -impl<'a> UpdatePlan<'a> { - pub fn new() -> Self { - UpdatePlan { - active: Default::default(), - expand: Default::default(), - metadata: Default::default(), - nickname: Default::default(), - product: Default::default(), - trial_period_days: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePlanTiers { - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount_decimal: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, - - pub up_to: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePlanTransformUsage { - pub divide_by: i64, - - pub round: CreatePlanTransformUsageRound, -} - -/// An enum representing the possible values of an `CreatePlanTransformUsage`'s `round` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePlanTransformUsageRound { - Down, - Up, -} - -impl CreatePlanTransformUsageRound { - pub fn as_str(self) -> &'static str { - match self { - CreatePlanTransformUsageRound::Down => "down", - CreatePlanTransformUsageRound::Up => "up", - } - } -} - -impl AsRef for CreatePlanTransformUsageRound { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePlanTransformUsageRound { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Plan`'s `aggregate_usage` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanAggregateUsage { - LastDuringPeriod, - LastEver, - Max, - Sum, -} - -impl PlanAggregateUsage { - pub fn as_str(self) -> &'static str { - match self { - PlanAggregateUsage::LastDuringPeriod => "last_during_period", - PlanAggregateUsage::LastEver => "last_ever", - PlanAggregateUsage::Max => "max", - PlanAggregateUsage::Sum => "sum", - } - } -} - -impl AsRef for PlanAggregateUsage { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanAggregateUsage { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Plan`'s `billing_scheme` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanBillingScheme { - PerUnit, - Tiered, -} - -impl PlanBillingScheme { - pub fn as_str(self) -> &'static str { - match self { - PlanBillingScheme::PerUnit => "per_unit", - PlanBillingScheme::Tiered => "tiered", - } - } -} - -impl AsRef for PlanBillingScheme { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanBillingScheme { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Plan`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanInterval { - Day, - Month, - Week, - Year, -} - -impl PlanInterval { - pub fn as_str(self) -> &'static str { - match self { - PlanInterval::Day => "day", - PlanInterval::Month => "month", - PlanInterval::Week => "week", - PlanInterval::Year => "year", - } - } -} - -impl AsRef for PlanInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Plan`'s `tiers_mode` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanTiersMode { - Graduated, - Volume, -} - -impl PlanTiersMode { - pub fn as_str(self) -> &'static str { - match self { - PlanTiersMode::Graduated => "graduated", - PlanTiersMode::Volume => "volume", - } - } -} - -impl AsRef for PlanTiersMode { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanTiersMode { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Plan`'s `usage_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanUsageType { - Licensed, - Metered, -} - -impl PlanUsageType { - pub fn as_str(self) -> &'static str { - match self { - PlanUsageType::Licensed => "licensed", - PlanUsageType::Metered => "metered", - } - } -} - -impl AsRef for PlanUsageType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanUsageType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `TransformUsage`'s `round` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TransformUsageRound { - Down, - Up, -} - -impl TransformUsageRound { - pub fn as_str(self) -> &'static str { - match self { - TransformUsageRound::Down => "down", - TransformUsageRound::Up => "up", - } - } -} - -impl AsRef for TransformUsageRound { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TransformUsageRound { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/platform_tax_fee.rs b/ft-stripe/src/resources/platform_tax_fee.rs deleted file mode 100644 index 61b0721..0000000 --- a/ft-stripe/src/resources/platform_tax_fee.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::Object; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "PlatformTax". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PlatformTaxFee { - /// The Connected account that incurred this charge. - pub account: String, - - /// The payment object that caused this tax to be inflicted. - pub source_transaction: String, - - /// The type of tax (VAT). - #[serde(rename = "type")] - pub type_: String, -} - -impl Object for PlatformTaxFee { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "platform_tax_fee" - } -} diff --git a/ft-stripe/src/resources/price.rs b/ft-stripe/src/resources/price.rs deleted file mode 100644 index 9aa27dc..0000000 --- a/ft-stripe/src/resources/price.rs +++ /dev/null @@ -1,921 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::PriceId; -use crate::params::{ - Expand, Expandable, IdOrCreate, List, Metadata, Object, RangeQuery, Timestamp, -}; -use crate::resources::{CreateProduct, Currency, Product, UpTo}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Price". -/// -/// For more details see [https://stripe.com/docs/api/prices/object](https://stripe.com/docs/api/prices/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Price { - /// Unique identifier for the object. - pub id: PriceId, - - /// Whether the price can be used for new purchases. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Describes how to compute the price per period. - /// - /// Either `per_unit` or `tiered`. - /// `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). - /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_scheme: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// A lookup key used to retrieve prices dynamically from a static string. - #[serde(skip_serializing_if = "Option::is_none")] - pub lookup_key: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// A brief description of the plan, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option, - - /// The ID of the product this price is associated with. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>, - - /// The recurring components of a price such as `interval` and `usage_type`. - #[serde(skip_serializing_if = "Option::is_none")] - pub recurring: Option, - - /// Each element represents a pricing tier. - /// - /// This parameter requires `billing_scheme` to be set to `tiered`. - /// See also the documentation for `billing_scheme`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers: Option>, - - /// Defines if the tiering price should be `graduated` or `volume` based. - /// - /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price. - /// In `graduated` tiering, pricing can change as the quantity grows. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers_mode: Option, - - /// Apply a transformation to the reported usage or set quantity before computing the amount billed. - /// - /// Cannot be combined with `tiers`. - #[serde(skip_serializing_if = "Option::is_none")] - pub transform_quantity: Option, - - /// One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// The unit amount in %s to be charged, represented as a whole integer if possible. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// The unit amount in %s to be charged, represented as a decimal string with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -impl Price { - /// Returns a list of your prices. - pub fn list(client: &Client, params: ListPrices<'_>) -> Response> { - client.get_query("/prices", ¶ms) - } - - /// Creates a new price for an existing product. - /// - /// The price can be recurring or one-time. - pub fn create(client: &Client, params: CreatePrice<'_>) -> Response { - client.post_form("/prices", ¶ms) - } - - /// Retrieves the price with the given ID. - pub fn retrieve(client: &Client, id: &PriceId, expand: &[&str]) -> Response { - client.get_query(&format!("/prices/{}", id), &Expand { expand }) - } - - /// Updates the specified price by setting the values of the parameters passed. - /// - /// Any parameters not provided are left unchanged. - pub fn update(client: &Client, id: &PriceId, params: UpdatePrice<'_>) -> Response { - client.post_form(&format!("/prices/{}", id), ¶ms) - } -} - -impl Object for Price { - type Id = PriceId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "price" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PriceTier { - /// Price for the entire tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount: Option, - - /// Same as `flat_amount`, but contains a decimal value with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount_decimal: Option, - - /// Per unit price for units relevant to the tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but contains a decimal value with at most 12 decimal places. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, - - /// Up to and including to this quantity will be contained in the tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub up_to: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Recurring { - /// Specifies a usage aggregation strategy for prices of `usage_type=metered`. - /// - /// Allowed values are `sum` for summing up all usage during a period, `last_during_period` for using the last usage record reported within a period, `last_ever` for using the last usage record ever (across period bounds) or `max` which uses the usage record with the maximum reported usage during a period. - /// Defaults to `sum`. - #[serde(skip_serializing_if = "Option::is_none")] - pub aggregate_usage: Option, - - /// The frequency at which a subscription is billed. - /// - /// One of `day`, `week`, `month` or `year`. - pub interval: RecurringInterval, - - /// The number of intervals (specified in the `interval` attribute) between subscription billings. - /// - /// For example, `interval=month` and `interval_count=3` bills every 3 months. - pub interval_count: u64, - - /// Default number of trial days when subscribing a customer to this price using [`trial_from_plan=true`](https://stripe.com/docs/api#create_subscription-trial_from_plan). - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, - - /// Configures how the quantity per period should be determined. - /// - /// Can be either `metered` or `licensed`. - /// `licensed` automatically bills the `quantity` set when adding it to a subscription. - /// `metered` aggregates the total usage based on usage records. - /// Defaults to `licensed`. - pub usage_type: RecurringUsageType, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransformQuantity { - /// Divide usage by this number. - pub divide_by: i64, - - /// After division, either round the result `up` or `down`. - pub round: TransformQuantityRound, -} - -/// The parameters for `Price::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreatePrice<'a> { - /// Whether the price is currently active. - /// - /// Defaults to `true`. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Describes how to compute the price per period. - /// - /// Either `per_unit` or `tiered`. - /// `per_unit` indicates that the fixed amount (specified in `unit_amount` or `unit_amount_decimal`) will be charged per unit in `quantity` (for prices with `usage_type=licensed`), or per unit of total usage (for prices with `usage_type=metered`). - /// `tiered` indicates that the unit pricing will be computed using a tiering strategy as defined using the `tiers` and `tiers_mode` attributes. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_scheme: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A lookup key used to retrieve prices dynamically from a static string. - #[serde(skip_serializing_if = "Option::is_none")] - pub lookup_key: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// A brief description of the price, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option<&'a str>, - - /// The ID of the product that this price will belong to. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// These fields can be used to create a new product that this price will belong to. - #[serde(skip_serializing_if = "Option::is_none")] - pub product_data: Option, - - /// The recurring components of a price such as `interval` and `usage_type`. - #[serde(skip_serializing_if = "Option::is_none")] - pub recurring: Option, - - /// Each element represents a pricing tier. - /// - /// This parameter requires `billing_scheme` to be set to `tiered`. - /// See also the documentation for `billing_scheme`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers: Option>, - - /// Defines if the tiering price should be `graduated` or `volume` based. - /// - /// In `volume`-based tiering, the maximum quantity within a period determines the per unit price, in `graduated` tiering pricing can successively change as the quantity grows. - #[serde(skip_serializing_if = "Option::is_none")] - pub tiers_mode: Option, - - /// If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_lookup_key: Option, - - /// Apply a transformation to the reported usage or set quantity before computing the billed price. - /// - /// Cannot be combined with `tiers`. - #[serde(skip_serializing_if = "Option::is_none")] - pub transform_quantity: Option, - - /// A positive integer in %s (or 0 for a free price) representing how much to charge. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - /// Same as `unit_amount`, but accepts a decimal value with at most 12 decimal places. - /// - /// Only one of `unit_amount` and `unit_amount_decimal` can be set. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option<&'a str>, -} - -impl<'a> CreatePrice<'a> { - pub fn new(currency: Currency) -> Self { - CreatePrice { - active: Default::default(), - billing_scheme: Default::default(), - currency, - expand: Default::default(), - lookup_key: Default::default(), - metadata: Default::default(), - nickname: Default::default(), - product: Default::default(), - product_data: Default::default(), - recurring: Default::default(), - tiers: Default::default(), - tiers_mode: Default::default(), - transfer_lookup_key: Default::default(), - transform_quantity: Default::default(), - unit_amount: Default::default(), - unit_amount_decimal: Default::default(), - } - } -} - -/// The parameters for `Price::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListPrices<'a> { - /// Only return prices that are active or inactive (e.g., pass `false` to list all inactive prices). - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return prices for the given currency. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return the price with these lookup_keys, if any exist. - #[serde(skip_serializing_if = "Option::is_none")] - pub lookup_keys: Option>, - - /// Only return prices for the given product. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// Only return prices with these recurring fields. - #[serde(skip_serializing_if = "Option::is_none")] - pub recurring: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return prices of type `recurring` or `one_time`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -impl<'a> ListPrices<'a> { - pub fn new() -> Self { - ListPrices { - active: Default::default(), - created: Default::default(), - currency: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - lookup_keys: Default::default(), - product: Default::default(), - recurring: Default::default(), - starting_after: Default::default(), - type_: Default::default(), - } - } -} - -/// The parameters for `Price::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdatePrice<'a> { - /// Whether the price is currently active. - /// - /// Defaults to `true`. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A lookup key used to retrieve prices dynamically from a static string. - #[serde(skip_serializing_if = "Option::is_none")] - pub lookup_key: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// A brief description of the price, hidden from customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub nickname: Option<&'a str>, - - /// The recurring components of a price such as `interval` and `usage_type`. - #[serde(skip_serializing_if = "Option::is_none")] - pub recurring: Option, - - /// If set to true, will atomically remove the lookup key from the existing price, and assign it to this price. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_lookup_key: Option, -} - -impl<'a> UpdatePrice<'a> { - pub fn new() -> Self { - UpdatePrice { - active: Default::default(), - expand: Default::default(), - lookup_key: Default::default(), - metadata: Default::default(), - nickname: Default::default(), - recurring: Default::default(), - transfer_lookup_key: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePriceProductData { - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option, - - #[serde(default)] - pub metadata: Metadata, - - pub name: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_label: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePriceRecurring { - #[serde(skip_serializing_if = "Option::is_none")] - pub aggregate_usage: Option, - - pub interval: CreatePriceRecurringInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_type: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePriceTiers { - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub flat_amount_decimal: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, - - pub up_to: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreatePriceTransformQuantity { - pub divide_by: i64, - - pub round: CreatePriceTransformQuantityRound, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ListPricesRecurring { - #[serde(skip_serializing_if = "Option::is_none")] - pub interval: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub usage_type: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdatePriceRecurring { - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, -} - -/// An enum representing the possible values of an `CreatePriceRecurring`'s `aggregate_usage` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePriceRecurringAggregateUsage { - LastDuringPeriod, - LastEver, - Max, - Sum, -} - -impl CreatePriceRecurringAggregateUsage { - pub fn as_str(self) -> &'static str { - match self { - CreatePriceRecurringAggregateUsage::LastDuringPeriod => "last_during_period", - CreatePriceRecurringAggregateUsage::LastEver => "last_ever", - CreatePriceRecurringAggregateUsage::Max => "max", - CreatePriceRecurringAggregateUsage::Sum => "sum", - } - } -} - -impl AsRef for CreatePriceRecurringAggregateUsage { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePriceRecurringAggregateUsage { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreatePriceRecurring`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePriceRecurringInterval { - Day, - Month, - Week, - Year, -} - -impl CreatePriceRecurringInterval { - pub fn as_str(self) -> &'static str { - match self { - CreatePriceRecurringInterval::Day => "day", - CreatePriceRecurringInterval::Month => "month", - CreatePriceRecurringInterval::Week => "week", - CreatePriceRecurringInterval::Year => "year", - } - } -} - -impl AsRef for CreatePriceRecurringInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePriceRecurringInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreatePriceRecurring`'s `usage_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePriceRecurringUsageType { - Licensed, - Metered, -} - -impl CreatePriceRecurringUsageType { - pub fn as_str(self) -> &'static str { - match self { - CreatePriceRecurringUsageType::Licensed => "licensed", - CreatePriceRecurringUsageType::Metered => "metered", - } - } -} - -impl AsRef for CreatePriceRecurringUsageType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePriceRecurringUsageType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreatePriceTransformQuantity`'s `round` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreatePriceTransformQuantityRound { - Down, - Up, -} - -impl CreatePriceTransformQuantityRound { - pub fn as_str(self) -> &'static str { - match self { - CreatePriceTransformQuantityRound::Down => "down", - CreatePriceTransformQuantityRound::Up => "up", - } - } -} - -impl AsRef for CreatePriceTransformQuantityRound { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreatePriceTransformQuantityRound { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListPricesRecurring`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ListPricesRecurringInterval { - Day, - Month, - Week, - Year, -} - -impl ListPricesRecurringInterval { - pub fn as_str(self) -> &'static str { - match self { - ListPricesRecurringInterval::Day => "day", - ListPricesRecurringInterval::Month => "month", - ListPricesRecurringInterval::Week => "week", - ListPricesRecurringInterval::Year => "year", - } - } -} - -impl AsRef for ListPricesRecurringInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ListPricesRecurringInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListPricesRecurring`'s `usage_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ListPricesRecurringUsageType { - Licensed, - Metered, -} - -impl ListPricesRecurringUsageType { - pub fn as_str(self) -> &'static str { - match self { - ListPricesRecurringUsageType::Licensed => "licensed", - ListPricesRecurringUsageType::Metered => "metered", - } - } -} - -impl AsRef for ListPricesRecurringUsageType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ListPricesRecurringUsageType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Price`'s `billing_scheme` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PriceBillingScheme { - PerUnit, - Tiered, -} - -impl PriceBillingScheme { - pub fn as_str(self) -> &'static str { - match self { - PriceBillingScheme::PerUnit => "per_unit", - PriceBillingScheme::Tiered => "tiered", - } - } -} - -impl AsRef for PriceBillingScheme { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PriceBillingScheme { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Price`'s `tiers_mode` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PriceTiersMode { - Graduated, - Volume, -} - -impl PriceTiersMode { - pub fn as_str(self) -> &'static str { - match self { - PriceTiersMode::Graduated => "graduated", - PriceTiersMode::Volume => "volume", - } - } -} - -impl AsRef for PriceTiersMode { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PriceTiersMode { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Price`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PriceType { - OneTime, - Recurring, -} - -impl PriceType { - pub fn as_str(self) -> &'static str { - match self { - PriceType::OneTime => "one_time", - PriceType::Recurring => "recurring", - } - } -} - -impl AsRef for PriceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PriceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Recurring`'s `aggregate_usage` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RecurringAggregateUsage { - LastDuringPeriod, - LastEver, - Max, - Sum, -} - -impl RecurringAggregateUsage { - pub fn as_str(self) -> &'static str { - match self { - RecurringAggregateUsage::LastDuringPeriod => "last_during_period", - RecurringAggregateUsage::LastEver => "last_ever", - RecurringAggregateUsage::Max => "max", - RecurringAggregateUsage::Sum => "sum", - } - } -} - -impl AsRef for RecurringAggregateUsage { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RecurringAggregateUsage { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Recurring`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RecurringInterval { - Day, - Month, - Week, - Year, -} - -impl RecurringInterval { - pub fn as_str(self) -> &'static str { - match self { - RecurringInterval::Day => "day", - RecurringInterval::Month => "month", - RecurringInterval::Week => "week", - RecurringInterval::Year => "year", - } - } -} - -impl AsRef for RecurringInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RecurringInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Recurring`'s `usage_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RecurringUsageType { - Licensed, - Metered, -} - -impl RecurringUsageType { - pub fn as_str(self) -> &'static str { - match self { - RecurringUsageType::Licensed => "licensed", - RecurringUsageType::Metered => "metered", - } - } -} - -impl AsRef for RecurringUsageType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RecurringUsageType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `TransformQuantity`'s `round` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TransformQuantityRound { - Down, - Up, -} - -impl TransformQuantityRound { - pub fn as_str(self) -> &'static str { - match self { - TransformQuantityRound::Down => "down", - TransformQuantityRound::Up => "up", - } - } -} - -impl AsRef for TransformQuantityRound { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TransformQuantityRound { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/product.rs b/ft-stripe/src/resources/product.rs deleted file mode 100644 index dea7989..0000000 --- a/ft-stripe/src/resources/product.rs +++ /dev/null @@ -1,501 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::ProductId; -use crate::params::{Deleted, Expand, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::PackageDimensions; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Product". -/// -/// For more details see [https://stripe.com/docs/api/products/object](https://stripe.com/docs/api/products/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Product { - /// Unique identifier for the object. - pub id: ProductId, - - /// Whether the product is currently available for purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A list of up to 5 attributes that each SKU can provide values for (e.g., `["color", "size"]`). - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option>, - - /// A short one-line description of the product, meant to be displayable to the customer. - /// - /// Only applicable to products of `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub caption: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// An array of connect application identifiers that cannot purchase this product. - /// - /// Only applicable to products of `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub deactivate_on: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// The product's description, meant to be displayable to the customer. - /// - /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub images: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The product's name, meant to be displayable to the customer. - /// - /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// The dimensions of this product for shipping purposes. - /// - /// A SKU associated with this product can override this value by having its own `package_dimensions`. - /// Only applicable to products of `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// Whether this product is a shipped good. - /// - /// Only applicable to products of `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub shippable: Option, - - /// Extra information about a product which will appear on your customer's credit card statement. - /// - /// In the case that multiple products are billed at once, the first statement descriptor will be used. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// The type of the product. - /// - /// The product is either of type `good`, which is eligible for use with Orders and SKUs, or `service`, which is eligible for use with Subscriptions and Plans. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. - /// - /// When set, this will be included in associated invoice line item descriptions. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_label: Option, - - /// Time at which the object was last updated. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub updated: Option, - - /// A URL of a publicly-accessible webpage for this product. - /// - /// Only applicable to products of `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -impl Product { - /// Returns a list of your products. - /// - /// The products are returned sorted by creation date, with the most recently created products appearing first. - pub fn list(client: &Client, params: ListProducts<'_>) -> Response> { - client.get_query("/products", ¶ms) - } - - /// Creates a new product object. - pub fn create(client: &Client, params: CreateProduct<'_>) -> Response { - client.post_form("/products", ¶ms) - } - - /// Retrieves the details of an existing product. - /// - /// Supply the unique product ID from either a product creation request or the product list, and Stripe will return the corresponding product information. - pub fn retrieve(client: &Client, id: &ProductId, expand: &[&str]) -> Response { - client.get_query(&format!("/products/{}", id), &Expand { expand }) - } - - /// Updates the specific product by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. - pub fn update(client: &Client, id: &ProductId, params: UpdateProduct<'_>) -> Response { - client.post_form(&format!("/products/{}", id), ¶ms) - } - - /// Delete a product. - /// - /// Deleting a product with type=`good` is only possible if it has no SKUs associated with it. - /// Deleting a product with type=`service` is only possible if it has no plans associated with it. - pub fn delete(client: &Client, id: &ProductId) -> Response> { - client.delete(&format!("/products/{}", id)) - } -} - -impl Object for Product { - type Id = ProductId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "product" - } -} - -/// The parameters for `Product::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateProduct<'a> { - /// Whether the product is currently available for purchase. - /// - /// Defaults to `true`. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A list of up to 5 alphanumeric attributes. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option>, - - /// A short one-line description of the product, meant to be displayable to the customer. - /// - /// May only be set if type=`good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub caption: Option<&'a str>, - - /// An array of Connect application names or identifiers that should not be able to order the SKUs for this product. - /// - /// May only be set if type=`good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub deactivate_on: Option>, - - /// The product's description, meant to be displayable to the customer. - /// - /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// An identifier will be randomly generated by Stripe. - /// - /// You can optionally override this ID, but the ID must be unique across all products in your Stripe account. - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option<&'a str>, - - /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub images: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The product's name, meant to be displayable to the customer. - /// - /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. - pub name: &'a str, - - /// The dimensions of this product for shipping purposes. - /// - /// A SKU associated with this product can override this value by having its own `package_dimensions`. - /// May only be set if type=`good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// Whether this product is shipped (i.e., physical goods). - /// - /// Defaults to `true`. - /// May only be set if type=`good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub shippable: Option, - - /// An arbitrary string to be displayed on your customer's credit card or bank statement. - /// - /// While most banks display this information consistently, some may display it incorrectly or not at all. This may be up to 22 characters. - /// The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. - /// Non-ASCII characters are automatically stripped. It must contain at least one letter. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - - /// The type of the product. - /// - /// Defaults to `service` if not explicitly specified, enabling use of this product with Subscriptions and Plans. - /// Set this parameter to `good` to use this product with Orders and SKUs. - /// On API versions before `2018-02-05`, this field defaults to `good` for compatibility reasons. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. - /// - /// When set, this will be included in associated invoice line item descriptions. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_label: Option<&'a str>, - - /// A URL of a publicly-accessible webpage for this product. - /// - /// May only be set if type=`good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option<&'a str>, -} - -impl<'a> CreateProduct<'a> { - pub fn new(name: &'a str) -> Self { - CreateProduct { - active: Default::default(), - attributes: Default::default(), - caption: Default::default(), - deactivate_on: Default::default(), - description: Default::default(), - expand: Default::default(), - id: Default::default(), - images: Default::default(), - metadata: Default::default(), - name, - package_dimensions: Default::default(), - shippable: Default::default(), - statement_descriptor: Default::default(), - type_: Default::default(), - unit_label: Default::default(), - url: Default::default(), - } - } -} - -/// The parameters for `Product::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListProducts<'a> { - /// Only return products that are active or inactive (e.g., pass `false` to list all inactive products). - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Only return products that were created during the given date interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Only return products with the given IDs. - #[serde(skip_serializing_if = "Option::is_none")] - pub ids: Option>, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return products that can be shipped (i.e., physical, not digital products). - #[serde(skip_serializing_if = "Option::is_none")] - pub shippable: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return products of this type. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// Only return products with the given url. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option<&'a str>, -} - -impl<'a> ListProducts<'a> { - pub fn new() -> Self { - ListProducts { - active: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - ids: Default::default(), - limit: Default::default(), - shippable: Default::default(), - starting_after: Default::default(), - type_: Default::default(), - url: Default::default(), - } - } -} - -/// The parameters for `Product::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateProduct<'a> { - /// Whether the product is available for purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A list of up to 5 alphanumeric attributes that each SKU can provide values for (e.g., `["color", "size"]`). - /// - /// If a value for `attributes` is specified, the list specified will replace the existing attributes list on this product. - /// Any attributes not present after the update will be deleted from the SKUs for this product. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option>, - - /// A short one-line description of the product, meant to be displayable to the customer. - /// - /// May only be set if `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub caption: Option<&'a str>, - - /// An array of Connect application names or identifiers that should not be able to order the SKUs for this product. - /// - /// May only be set if `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub deactivate_on: Option>, - - /// The product's description, meant to be displayable to the customer. - /// - /// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A list of up to 8 URLs of images for this product, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub images: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The product's name, meant to be displayable to the customer. - /// - /// Whenever this product is sold via a subscription, name will show up on associated invoice line item descriptions. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, - - /// The dimensions of this product for shipping purposes. - /// - /// A SKU associated with this product can override this value by having its own `package_dimensions`. - /// May only be set if `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// Whether this product is shipped (i.e., physical goods). - /// - /// Defaults to `true`. - /// May only be set if `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub shippable: Option, - - /// An arbitrary string to be displayed on your customer's credit card or bank statement. - /// - /// While most banks display this information consistently, some may display it incorrectly or not at all. This may be up to 22 characters. - /// The statement description may not include `<`, `>`, `\`, `"`, `'` characters, and will appear on your customer's statement in capital letters. - /// Non-ASCII characters are automatically stripped. It must contain at least one letter. - /// May only be set if `type=service`. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - - /// A label that represents units of this product in Stripe and on customers’ receipts and invoices. - /// - /// When set, this will be included in associated invoice line item descriptions. - /// May only be set if `type=service`. - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_label: Option<&'a str>, - - /// A URL of a publicly-accessible webpage for this product. - /// - /// May only be set if `type=good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option<&'a str>, -} - -impl<'a> UpdateProduct<'a> { - pub fn new() -> Self { - UpdateProduct { - active: Default::default(), - attributes: Default::default(), - caption: Default::default(), - deactivate_on: Default::default(), - description: Default::default(), - expand: Default::default(), - images: Default::default(), - metadata: Default::default(), - name: Default::default(), - package_dimensions: Default::default(), - shippable: Default::default(), - statement_descriptor: Default::default(), - unit_label: Default::default(), - url: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Product`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ProductType { - Good, - Service, -} - -impl ProductType { - pub fn as_str(self) -> &'static str { - match self { - ProductType::Good => "good", - ProductType::Service => "service", - } - } -} - -impl AsRef for ProductType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ProductType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/recipient.rs b/ft-stripe/src/resources/recipient.rs deleted file mode 100644 index f3f65fa..0000000 --- a/ft-stripe/src/resources/recipient.rs +++ /dev/null @@ -1,326 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::RecipientId; -use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{Account, BankAccount, Card}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "TransferRecipient". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Recipient { - /// Unique identifier for the object. - pub id: RecipientId, - - /// Hash describing the current account on the recipient, if there is one. - #[serde(skip_serializing_if = "Option::is_none")] - pub active_account: Option, - - #[serde(default)] - pub cards: List, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// The default card to use for creating transfers to this recipient. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_card: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The ID of the [Custom account](https://stripe.com/docs/connect/custom-accounts) this recipient was migrated to. - /// - /// If set, the recipient can no longer be updated, nor can transfers be made to it: use the Custom account instead. - #[serde(skip_serializing_if = "Option::is_none")] - pub migrated_to: Option>, - - /// Full, legal name of the recipient. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub rolled_back_from: Option>, - - /// Type of the recipient, one of `individual` or `corporation`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -impl Recipient { - /// Returns a list of your recipients. - /// - /// The recipients are returned sorted by creation date, with the most recently created recipients appearing first. - pub fn list(client: &Client, params: ListRecipients<'_>) -> Response> { - client.get_query("/recipients", ¶ms) - } - - /// Creates a new `Recipient` object and verifies the recipient’s identity. - /// Also verifies the recipient’s bank account information or debit card, if either is provided. - pub fn create(client: &Client, params: CreateRecipient<'_>) -> Response { - client.post_form("/recipients", ¶ms) - } - - /// Retrieves the details of an existing recipient. - /// - /// You need only supply the unique recipient identifier that was returned upon recipient creation. - pub fn retrieve(client: &Client, id: &RecipientId, expand: &[&str]) -> Response { - client.get_query(&format!("/recipients/{}", id), &Expand { expand }) - } - - /// Updates the specified recipient by setting the values of the parameters passed. - /// Any parameters not provided will be left unchanged. - /// - /// If you update the name or tax ID, the identity verification will automatically be rerun. - /// If you update the bank account, the bank account validation will automatically be rerun. - pub fn update( - client: &Client, - id: &RecipientId, - params: UpdateRecipient<'_>, - ) -> Response { - client.post_form(&format!("/recipients/{}", id), ¶ms) - } - - /// Permanently deletes a recipient. - /// - /// It cannot be undone. - pub fn delete(client: &Client, id: &RecipientId) -> Response> { - client.delete(&format!("/recipients/{}", id)) - } -} - -impl Object for Recipient { - type Id = RecipientId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "recipient" - } -} - -/// The parameters for `Recipient::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateRecipient<'a> { - /// An arbitrary string which you can attach to a `Recipient` object. - /// - /// It is displayed alongside the recipient in the web interface. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The recipient's email address. - /// - /// It is displayed alongside the recipient in the web interface, and can be useful for searching and tracking. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The recipient's full, legal name. - /// - /// For type `individual`, should be in the format `First Last`, `First Middle Last`, or `First M Last` (no prefixes or suffixes). - /// For `corporation`, the full, incorporated name. - pub name: &'a str, - - /// The recipient's tax ID, as a string. - /// - /// For type `individual`, the full SSN; for type `corporation`, the full EIN. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id: Option<&'a str>, - - /// Type of the recipient: either `individual` or `corporation`. - #[serde(rename = "type")] - pub type_: RecipientType, -} - -impl<'a> CreateRecipient<'a> { - pub fn new(name: &'a str, type_: RecipientType) -> Self { - CreateRecipient { - description: Default::default(), - email: Default::default(), - expand: Default::default(), - metadata: Default::default(), - name, - tax_id: Default::default(), - type_, - } - } -} - -/// The parameters for `Recipient::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListRecipients<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// Only return recipients that are verified or unverified. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified: Option, -} - -impl<'a> ListRecipients<'a> { - pub fn new() -> Self { - ListRecipients { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - type_: Default::default(), - verified: Default::default(), - } - } -} - -/// The parameters for `Recipient::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateRecipient<'a> { - /// ID of the card to set as the recipient's new default for payouts. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_card: Option<&'a str>, - - /// An arbitrary string which you can attach to a `Recipient` object. - /// - /// It is displayed alongside the recipient in the web interface. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The recipient's email address. - /// - /// It is displayed alongside the recipient in the web interface, and can be useful for searching and tracking. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The recipient's full, legal name. - /// - /// For type `individual`, should be in the format `First Last`, `First Middle Last`, or `First M Last` (no prefixes or suffixes). - /// For `corporation`, the full, incorporated name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<&'a str>, - - /// The recipient's tax ID, as a string. - /// - /// For type `individual`, the full SSN; for type `corporation`, the full EIN. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_id: Option<&'a str>, -} - -impl<'a> UpdateRecipient<'a> { - pub fn new() -> Self { - UpdateRecipient { - default_card: Default::default(), - description: Default::default(), - email: Default::default(), - expand: Default::default(), - metadata: Default::default(), - name: Default::default(), - tax_id: Default::default(), - } - } -} - -/// An enum representing the possible values of an `ListRecipients`'s `type_` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RecipientType { - Corporation, - Individual, -} - -impl RecipientType { - pub fn as_str(self) -> &'static str { - match self { - RecipientType::Corporation => "corporation", - RecipientType::Individual => "individual", - } - } -} - -impl AsRef for RecipientType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RecipientType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/refund.rs b/ft-stripe/src/resources/refund.rs deleted file mode 100644 index 8412717..0000000 --- a/ft-stripe/src/resources/refund.rs +++ /dev/null @@ -1,287 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ChargeId, PaymentIntentId, RefundId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{BalanceTransaction, Charge, Currency, PaymentIntent, TransferReversal}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Refund". -/// -/// For more details see [https://stripe.com/docs/api/refunds/object](https://stripe.com/docs/api/refunds/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Refund { - /// Unique identifier for the object. - pub id: RefundId, - - /// Amount, in %s. - pub amount: i64, - - /// Balance transaction that describes the impact on your account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// ID of the charge that was refunded. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - /// (Available on non-card refunds only). - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// If the refund failed, this balance transaction describes the adjustment made on your account balance that reverses the initial balance transaction. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_balance_transaction: Option>, - - /// If the refund failed, the reason for refund failure if known. - /// - /// Possible values are `lost_or_stolen_card`, `expired_or_canceled_card`, or `unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_reason: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// ID of the PaymentIntent that was refunded. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// Reason for the refund, either user-provided (`duplicate`, `fraudulent`, or `requested_by_customer`) or generated by Stripe internally (`expired_uncaptured_charge`). - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - - /// This is the transaction number that appears on email receipts sent for this refund. - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt_number: Option, - - /// The transfer reversal that is associated with the refund. - /// - /// Only present if the charge came from another Stripe account. - /// See the Connect documentation for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_transfer_reversal: Option>, - - /// Status of the refund. - /// - /// For credit card refunds, this can be `pending`, `succeeded`, or `failed`. - /// For other types of refunds, it can be `pending`, `succeeded`, `failed`, or `canceled`. - /// Refer to our [refunds](https://stripe.com/docs/refunds#failed-refunds) documentation for more details. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - /// If the accompanying transfer was reversed, the transfer reversal object. - /// - /// Only applicable if the charge was created using the destination parameter. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_reversal: Option>, -} - -impl Refund { - /// Returns a list of all refunds you’ve previously created. - /// - /// The refunds are returned in sorted order, with the most recent refunds appearing first. - /// For convenience, the 10 most recent refunds are always available by default on the charge object. - pub fn list(client: &Client, params: ListRefunds<'_>) -> Response> { - client.get_query("/refunds", ¶ms) - } - - /// Create a refund. - pub fn create(client: &Client, params: CreateRefund<'_>) -> Response { - client.post_form("/refunds", ¶ms) - } - - /// Retrieves the details of an existing refund. - pub fn retrieve(client: &Client, id: &RefundId, expand: &[&str]) -> Response { - client.get_query(&format!("/refunds/{}", id), &Expand { expand }) - } - - /// Updates the specified refund by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. This request only accepts `metadata` as an argument. - pub fn update(client: &Client, id: &RefundId, params: UpdateRefund<'_>) -> Response { - client.post_form(&format!("/refunds/{}", id), ¶ms) - } -} - -impl Object for Refund { - type Id = RefundId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "refund" - } -} - -/// The parameters for `Refund::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateRefund<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_application_fee: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub reverse_transfer: Option, -} - -impl<'a> CreateRefund<'a> { - pub fn new() -> Self { - CreateRefund { - amount: Default::default(), - charge: Default::default(), - expand: Default::default(), - metadata: Default::default(), - payment_intent: Default::default(), - reason: Default::default(), - refund_application_fee: Default::default(), - reverse_transfer: Default::default(), - } - } -} - -/// The parameters for `Refund::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListRefunds<'a> { - /// Only return refunds for the charge specified by this charge ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return refunds for the PaymentIntent specified by this ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListRefunds<'a> { - pub fn new() -> Self { - ListRefunds { - charge: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - payment_intent: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Refund::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateRefund<'a> { - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdateRefund<'a> { - pub fn new() -> Self { - UpdateRefund { expand: Default::default(), metadata: Default::default() } - } -} - -/// An enum representing the possible values of an `CreateRefund`'s `reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum RefundReason { - Duplicate, - Fraudulent, - RequestedByCustomer, -} - -impl RefundReason { - pub fn as_str(self) -> &'static str { - match self { - RefundReason::Duplicate => "duplicate", - RefundReason::Fraudulent => "fraudulent", - RefundReason::RequestedByCustomer => "requested_by_customer", - } - } -} - -impl AsRef for RefundReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for RefundReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/reserve_transaction.rs b/ft-stripe/src/resources/reserve_transaction.rs deleted file mode 100644 index 013c905..0000000 --- a/ft-stripe/src/resources/reserve_transaction.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::Object; -use crate::resources::Currency; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "ReserveTransaction". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ReserveTransaction { - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, -} - -impl Object for ReserveTransaction { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "reserve_transaction" - } -} diff --git a/ft-stripe/src/resources/review.rs b/ft-stripe/src/resources/review.rs deleted file mode 100644 index 3b57e15..0000000 --- a/ft-stripe/src/resources/review.rs +++ /dev/null @@ -1,241 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::ReviewId; -use crate::params::{Expand, Expandable, List, Object, RangeQuery, Timestamp}; -use crate::resources::{Charge, PaymentIntent, ReviewReason}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "RadarReview". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Review { - /// Unique identifier for the object. - pub id: ReviewId, - - /// The ZIP or postal code of the card used, if applicable. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_zip: Option, - - /// The charge associated with this review. - #[serde(skip_serializing_if = "Option::is_none")] - pub charge: Option>, - - /// The reason the review was closed, or null if it has not yet been closed. - /// - /// One of `approved`, `refunded`, `refunded_as_fraud`, or `disputed`. - #[serde(skip_serializing_if = "Option::is_none")] - pub closed_reason: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// The IP address where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub ip_address: Option, - - /// Information related to the location of the payment. - /// - /// Note that this information is an approximation and attempts to locate the nearest population center - it should not be used to determine a specific address. - #[serde(skip_serializing_if = "Option::is_none")] - pub ip_address_location: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// If `true`, the review needs action. - pub open: bool, - - /// The reason the review was opened. - /// - /// One of `rule` or `manual`. - pub opened_reason: ReviewOpenedReason, - - /// The PaymentIntent ID associated with this review, if one exists. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_intent: Option>, - - /// The reason the review is currently open or closed. - /// - /// One of `rule`, `manual`, `approved`, `refunded`, `refunded_as_fraud`, or `disputed`. - pub reason: ReviewReason, - - /// Information related to the browsing session of the user who initiated the payment. - #[serde(skip_serializing_if = "Option::is_none")] - pub session: Option, -} - -impl Review { - /// Returns a list of `Review` objects that have `open` set to `true`. - /// - /// The objects are sorted in descending order by creation date, with the most recently created object appearing first. - pub fn list(client: &Client, params: ListReviews<'_>) -> Response> { - client.get_query("/reviews", ¶ms) - } - - /// Retrieves a `Review` object. - pub fn retrieve(client: &Client, id: &ReviewId, expand: &[&str]) -> Response { - client.get_query(&format!("/reviews/{}", id), &Expand { expand }) - } -} - -impl Object for Review { - type Id = ReviewId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "review" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct RadarReviewResourceLocation { - /// The city where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option, - - /// Two-letter ISO code representing the country where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// The geographic latitude where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub latitude: Option, - - /// The geographic longitude where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub longitude: Option, - - /// The state/county/province/region where the payment originated. - #[serde(skip_serializing_if = "Option::is_none")] - pub region: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct RadarReviewResourceSession { - /// The browser used in this browser session (e.g., `Chrome`). - #[serde(skip_serializing_if = "Option::is_none")] - pub browser: Option, - - /// Information about the device used for the browser session (e.g., `Samsung SM-G930T`). - #[serde(skip_serializing_if = "Option::is_none")] - pub device: Option, - - /// The platform for the browser session (e.g., `Macintosh`). - #[serde(skip_serializing_if = "Option::is_none")] - pub platform: Option, - - /// The version for the browser session (e.g., `61.0.3163.100`). - #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, -} - -/// The parameters for `Review::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListReviews<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListReviews<'a> { - pub fn new() -> Self { - ListReviews { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Review`'s `closed_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ReviewClosedReason { - Approved, - Disputed, - Refunded, - RefundedAsFraud, -} - -impl ReviewClosedReason { - pub fn as_str(self) -> &'static str { - match self { - ReviewClosedReason::Approved => "approved", - ReviewClosedReason::Disputed => "disputed", - ReviewClosedReason::Refunded => "refunded", - ReviewClosedReason::RefundedAsFraud => "refunded_as_fraud", - } - } -} - -impl AsRef for ReviewClosedReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ReviewClosedReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Review`'s `opened_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ReviewOpenedReason { - Manual, - Rule, -} - -impl ReviewOpenedReason { - pub fn as_str(self) -> &'static str { - match self { - ReviewOpenedReason::Manual => "manual", - ReviewOpenedReason::Rule => "rule", - } - } -} - -impl AsRef for ReviewOpenedReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ReviewOpenedReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/review_ext.rs b/ft-stripe/src/resources/review_ext.rs deleted file mode 100644 index 6e57e63..0000000 --- a/ft-stripe/src/resources/review_ext.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `Review`'s `reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ReviewReason { - Approved, - Disputed, - Manual, - Refunded, - RefundedAsFraud, - Rule, -} - -impl ReviewReason { - pub fn as_str(self) -> &'static str { - match self { - ReviewReason::Approved => "approved", - ReviewReason::Disputed => "disputed", - ReviewReason::Manual => "manual", - ReviewReason::Refunded => "refunded", - ReviewReason::RefundedAsFraud => "refunded_as_fraud", - ReviewReason::Rule => "rule", - } - } -} - -impl AsRef for ReviewReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ReviewReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/scheduled_query_run.rs b/ft-stripe/src/resources/scheduled_query_run.rs deleted file mode 100644 index f2b84c0..0000000 --- a/ft-stripe/src/resources/scheduled_query_run.rs +++ /dev/null @@ -1,62 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::ScheduledQueryRunId; -use crate::params::{Object, Timestamp}; -use crate::resources::File; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "ScheduledQueryRun". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ScheduledQueryRun { - /// Unique identifier for the object. - pub id: ScheduledQueryRunId, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// When the query was run, Sigma contained a snapshot of your Stripe data at this time. - pub data_load_time: Timestamp, - - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - - /// The file object representing the results of the query. - #[serde(skip_serializing_if = "Option::is_none")] - pub file: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Time at which the result expires and is no longer available for download. - pub result_available_until: Timestamp, - - /// SQL for the query. - pub sql: String, - - /// The query's execution status, which will be `completed` for successful runs, and `canceled`, `failed`, or `timed_out` otherwise. - pub status: String, - - /// Title of the query. - pub title: String, -} - -impl Object for ScheduledQueryRun { - type Id = ScheduledQueryRunId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "scheduled_query_run" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SigmaScheduledQueryRunError { - /// Information about the run failure. - pub message: String, -} diff --git a/ft-stripe/src/resources/setup_intent.rs b/ft-stripe/src/resources/setup_intent.rs deleted file mode 100644 index 3bed533..0000000 --- a/ft-stripe/src/resources/setup_intent.rs +++ /dev/null @@ -1,655 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, PaymentMethodId, SetupIntentId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - Account, ApiErrors, Application, Currency, Customer, Mandate, PaymentMethod, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "SetupIntent". -/// -/// For more details see [https://stripe.com/docs/api/setup_intents/object](https://stripe.com/docs/api/setup_intents/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SetupIntent { - /// Unique identifier for the object. - pub id: SetupIntentId, - - /// ID of the Connect application that created the SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option>, - - /// Reason for cancellation of this SetupIntent, one of `abandoned`, `requested_by_customer`, or `duplicate`. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancellation_reason: Option, - - /// The client secret of this SetupIntent. - /// - /// Used for client-side retrieval using a publishable key. The client secret can be used to complete payment setup from your frontend. - /// It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer. - /// Make sure that you have TLS enabled on any page that includes the client secret. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_secret: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// ID of the Customer this SetupIntent belongs to, if one exists. - /// - /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. - /// - /// Payment methods attached to other Customers cannot be used with this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The error encountered in the previous SetupIntent confirmation. - #[serde(skip_serializing_if = "Option::is_none")] - pub last_setup_error: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// ID of the multi use Mandate generated by the SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// If present, this property tells you what actions you need to take in order for your customer to continue payment setup. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_action: Option, - - /// The account (if any) for which the setup is intended. - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option>, - - /// ID of the payment method used with this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option>, - - /// Payment-method-specific configuration for this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_options: Option, - - /// The list of payment method types (e.g. - /// - /// card) that this SetupIntent is allowed to set up. - pub payment_method_types: Vec, - - /// ID of the single_use Mandate generated by the SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub single_use_mandate: Option>, - - /// [Status](https://stripe.com/docs/payments/intents#intent-statuses) of this SetupIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `canceled`, or `succeeded`. - pub status: SetupIntentStatus, - - /// Indicates how the payment method is intended to be used in the future. - /// - /// Use `on_session` if you intend to only reuse the payment method when the customer is in your checkout flow. - /// - /// Use `off_session` if your customer may or may not be in your checkout flow. - /// If not provided, this value defaults to `off_session`. - pub usage: String, -} - -impl SetupIntent { - /// Returns a list of SetupIntents. - pub fn list(client: &Client, params: ListSetupIntents<'_>) -> Response> { - client.get_query("/setup_intents", ¶ms) - } - - /// Creates a SetupIntent object. - /// - /// After the SetupIntent is created, attach a payment method and [confirm](https://stripe.com/docs/api/setup_intents/confirm) - /// to collect any required permissions to charge the payment method later. - pub fn create(client: &Client, params: CreateSetupIntent<'_>) -> Response { - client.post_form("/setup_intents", ¶ms) - } - - /// Retrieves the details of a SetupIntent that has previously been created. - /// - /// Client-side retrieval using a publishable key is allowed when the `client_secret` is provided in the query string. - /// When retrieved with a publishable key, only a subset of properties will be returned. - /// Please refer to the [SetupIntent](https://stripe.com/docs/api#setup_intent_object) object reference for more details. - pub fn retrieve(client: &Client, id: &SetupIntentId, expand: &[&str]) -> Response { - client.get_query(&format!("/setup_intents/{}", id), &Expand { expand }) - } - - /// Updates a SetupIntent object. - pub fn update( - client: &Client, - id: &SetupIntentId, - params: UpdateSetupIntent<'_>, - ) -> Response { - client.post_form(&format!("/setup_intents/{}", id), ¶ms) - } -} - -impl Object for SetupIntent { - type Id = SetupIntentId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "setup_intent" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SetupIntentNextAction { - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect_to_url: Option, - - /// Type of the next action to perform, one of `redirect_to_url` or `use_stripe_sdk`. - #[serde(rename = "type")] - pub type_: String, - - /// When confirming a SetupIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows. - /// - /// The shape of the contents is subject to change and is only intended to be used by Stripe.js. - #[serde(skip_serializing_if = "Option::is_none")] - pub use_stripe_sdk: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SetupIntentNextActionRedirectToUrl { - /// If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion. - #[serde(skip_serializing_if = "Option::is_none")] - pub return_url: Option, - - /// The URL you must redirect your customer to in order to authenticate. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SetupIntentPaymentMethodOptions { - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SetupIntentPaymentMethodOptionsCard { - /// We strongly recommend that you rely on our SCA Engine to automatically prompt your customers for authentication based on risk level and [other requirements](https://stripe.com/docs/strong-customer-authentication). - /// - /// However, if you wish to request 3D Secure based on logic from your own fraud engine, provide this option. - /// Permitted values include: `automatic` or `any`. - /// If not provided, defaults to `automatic`. - /// Read our guide on [manually requesting 3D Secure](https://stripe.com/docs/payments/3d-secure#manual-three-ds) for more information on how this configuration interacts with Radar and our SCA Engine. - #[serde(skip_serializing_if = "Option::is_none")] - pub request_three_d_secure: Option, -} - -/// The parameters for `SetupIntent::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateSetupIntent<'a> { - /// Set to `true` to attempt to confirm this SetupIntent immediately. - /// - /// This parameter defaults to `false`. - /// If the payment method attached is a card, a return_url may be provided in case additional authentication is required. - #[serde(skip_serializing_if = "Option::is_none")] - pub confirm: Option, - - /// ID of the Customer this SetupIntent belongs to, if one exists. - /// - /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. - /// - /// Payment methods attached to other Customers cannot be used with this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// This hash contains details about the Mandate to create. - /// - /// This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate_data: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The Stripe account ID for which this SetupIntent is created. - #[serde(skip_serializing_if = "Option::is_none")] - pub on_behalf_of: Option<&'a str>, - - /// ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// Payment-method-specific configuration for this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_options: Option, - - /// The list of payment method types (e.g. - /// - /// card) that this SetupIntent is allowed to use. - /// If this is not provided, defaults to ["card"]. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_types: Option>, - - /// The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method's app or site. - /// - /// If you'd prefer to redirect to a mobile application, you can alternatively supply an application URI scheme. - /// This parameter can only be used with [`confirm=true`](https://stripe.com/docs/api/setup_intents/create#create_setup_intent-confirm). - #[serde(skip_serializing_if = "Option::is_none")] - pub return_url: Option<&'a str>, - - /// If this hash is populated, this SetupIntent will generate a single_use Mandate on success. - #[serde(skip_serializing_if = "Option::is_none")] - pub single_use: Option, -} - -impl<'a> CreateSetupIntent<'a> { - pub fn new() -> Self { - CreateSetupIntent { - confirm: Default::default(), - customer: Default::default(), - description: Default::default(), - expand: Default::default(), - mandate_data: Default::default(), - metadata: Default::default(), - on_behalf_of: Default::default(), - payment_method: Default::default(), - payment_method_options: Default::default(), - payment_method_types: Default::default(), - return_url: Default::default(), - single_use: Default::default(), - } - } -} - -/// The parameters for `SetupIntent::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListSetupIntents<'a> { - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return SetupIntents for the customer specified by this customer ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return SetupIntents associated with the specified payment method. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListSetupIntents<'a> { - pub fn new() -> Self { - ListSetupIntents { - created: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - payment_method: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `SetupIntent::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSetupIntent<'a> { - /// ID of the Customer this SetupIntent belongs to, if one exists. - /// - /// If present, the SetupIntent's payment method will be attached to the Customer on successful setup. - /// - /// Payment methods attached to other Customers cannot be used with this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// ID of the payment method (a PaymentMethod, Card, or saved Source object) to attach to this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method: Option, - - /// Payment-method-specific configuration for this SetupIntent. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_options: Option, - - /// The list of payment method types (e.g. - /// - /// card) that this SetupIntent is allowed to set up. - /// If this is not provided, defaults to ["card"]. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_types: Option>, -} - -impl<'a> UpdateSetupIntent<'a> { - pub fn new() -> Self { - UpdateSetupIntent { - customer: Default::default(), - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - payment_method: Default::default(), - payment_method_options: Default::default(), - payment_method_types: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentMandateData { - pub customer_acceptance: CreateSetupIntentMandateDataCustomerAcceptance, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentPaymentMethodOptions { - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentSingleUse { - pub amount: i64, - - pub currency: Currency, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSetupIntentPaymentMethodOptions { - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentMandateDataCustomerAcceptance { - #[serde(skip_serializing_if = "Option::is_none")] - pub accepted_at: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub offline: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub online: Option, - - #[serde(rename = "type")] - pub type_: CreateSetupIntentMandateDataCustomerAcceptanceType, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentPaymentMethodOptionsCard { - #[serde(skip_serializing_if = "Option::is_none")] - pub request_three_d_secure: - Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSetupIntentPaymentMethodOptionsCard { - #[serde(skip_serializing_if = "Option::is_none")] - pub request_three_d_secure: - Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentMandateDataCustomerAcceptanceOffline {} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSetupIntentMandateDataCustomerAcceptanceOnline { - pub ip_address: String, - - pub user_agent: String, -} - -/// An enum representing the possible values of an `CreateSetupIntentMandateDataCustomerAcceptance`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreateSetupIntentMandateDataCustomerAcceptanceType { - Offline, - Online, -} - -impl CreateSetupIntentMandateDataCustomerAcceptanceType { - pub fn as_str(self) -> &'static str { - match self { - CreateSetupIntentMandateDataCustomerAcceptanceType::Offline => "offline", - CreateSetupIntentMandateDataCustomerAcceptanceType::Online => "online", - } - } -} - -impl AsRef for CreateSetupIntentMandateDataCustomerAcceptanceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreateSetupIntentMandateDataCustomerAcceptanceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - Any, - Automatic, -} - -impl CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - pub fn as_str(self) -> &'static str { - match self { - CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", - CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", - } - } -} - -impl AsRef for CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SetupIntent`'s `cancellation_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SetupIntentCancellationReason { - Abandoned, - Duplicate, - RequestedByCustomer, -} - -impl SetupIntentCancellationReason { - pub fn as_str(self) -> &'static str { - match self { - SetupIntentCancellationReason::Abandoned => "abandoned", - SetupIntentCancellationReason::Duplicate => "duplicate", - SetupIntentCancellationReason::RequestedByCustomer => "requested_by_customer", - } - } -} - -impl AsRef for SetupIntentCancellationReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SetupIntentCancellationReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - Any, - Automatic, - ChallengeOnly, -} - -impl SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - pub fn as_str(self) -> &'static str { - match self { - SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", - SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", - SetupIntentPaymentMethodOptionsCardRequestThreeDSecure::ChallengeOnly => { - "challenge_only" - } - } - } -} - -impl AsRef for SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SetupIntent`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SetupIntentStatus { - Canceled, - Processing, - RequiresAction, - RequiresConfirmation, - RequiresPaymentMethod, - Succeeded, -} - -impl SetupIntentStatus { - pub fn as_str(self) -> &'static str { - match self { - SetupIntentStatus::Canceled => "canceled", - SetupIntentStatus::Processing => "processing", - SetupIntentStatus::RequiresAction => "requires_action", - SetupIntentStatus::RequiresConfirmation => "requires_confirmation", - SetupIntentStatus::RequiresPaymentMethod => "requires_payment_method", - SetupIntentStatus::Succeeded => "succeeded", - } - } -} - -impl AsRef for SetupIntentStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SetupIntentStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `UpdateSetupIntentPaymentMethodOptionsCard`'s `request_three_d_secure` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - Any, - Automatic, -} - -impl UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - pub fn as_str(self) -> &'static str { - match self { - UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Any => "any", - UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure::Automatic => "automatic", - } - } -} - -impl AsRef for UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for UpdateSetupIntentPaymentMethodOptionsCardRequestThreeDSecure { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/sku.rs b/ft-stripe/src/resources/sku.rs deleted file mode 100644 index d3240de..0000000 --- a/ft-stripe/src/resources/sku.rs +++ /dev/null @@ -1,375 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::SkuId; -use crate::params::{Deleted, Expand, Expandable, IdOrCreate, List, Metadata, Object, Timestamp}; -use crate::resources::{CreateProduct, Currency, PackageDimensions, Product}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "SKU". -/// -/// For more details see [https://stripe.com/docs/api/skus/object](https://stripe.com/docs/api/skus/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Sku { - /// Unique identifier for the object. - pub id: SkuId, - - /// Whether the SKU is available for purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A dictionary of attributes and values for the attributes defined by the product. - /// - /// If, for example, a product's attributes are `["size", "gender"]`, a valid SKU has the following dictionary of attributes: `{"size": "Medium", "gender": "Unisex"}`. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// The URL of an image for this SKU, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub image: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub inventory: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The dimensions of this SKU for shipping purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// The ID of the product this SKU is associated with. - /// - /// The product must be currently active. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>, - - /// Time at which the object was last updated. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub updated: Option, -} - -impl Sku { - /// Returns a list of your SKUs. - /// - /// The SKUs are returned sorted by creation date, with the most recently created SKUs appearing first. - pub fn list(client: &Client, params: ListSkus<'_>) -> Response> { - client.get_query("/skus", ¶ms) - } - - /// Creates a new SKU associated with a product. - pub fn create(client: &Client, params: CreateSku<'_>) -> Response { - client.post_form("/skus", ¶ms) - } - - /// Retrieves the details of an existing SKU. - /// - /// Supply the unique SKU identifier from either a SKU creation request or from the product, and Stripe will return the corresponding SKU information. - pub fn retrieve(client: &Client, id: &SkuId, expand: &[&str]) -> Response { - client.get_query(&format!("/skus/{}", id), &Expand { expand }) - } - - /// Updates the specific SKU by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. Note that a SKU’s `attributes` are not editable. - /// Instead, you would need to deactivate the existing SKU and create a new one with the new attribute values. - pub fn update(client: &Client, id: &SkuId, params: UpdateSku<'_>) -> Response { - client.post_form(&format!("/skus/{}", id), ¶ms) - } - - /// Delete a SKU. - /// - /// Deleting a SKU is only possible until it has been used in an order. - pub fn delete(client: &Client, id: &SkuId) -> Response> { - client.delete(&format!("/skus/{}", id)) - } -} - -impl Object for Sku { - type Id = SkuId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "sku" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Inventory { - /// The count of inventory available. - /// - /// Will be present if and only if `type` is `finite`. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// Inventory type. - /// - /// Possible values are `finite`, `bucket` (not quantified), and `infinite`. - #[serde(rename = "type")] - pub type_: String, - - /// An indicator of the inventory available. - /// - /// Possible values are `in_stock`, `limited`, and `out_of_stock`. - /// Will be present if and only if `type` is `bucket`. - #[serde(skip_serializing_if = "Option::is_none")] - pub value: Option, -} - -/// The parameters for `Sku::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateSku<'a> { - /// Whether the SKU is available for purchase. - /// - /// Default to `true`. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A dictionary of attributes and values for the attributes defined by the product. - /// - /// If, for example, a product's attributes are `["size", "gender"]`, a valid SKU has the following dictionary of attributes: `{"size": "Medium", "gender": "Unisex"}`. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The identifier for the SKU. - /// - /// Must be unique. - /// If not provided, an identifier will be randomly generated. - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option<&'a str>, - - /// The URL of an image for this SKU, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub image: Option<&'a str>, - - /// Description of the SKU's inventory. - #[serde(skip_serializing_if = "Option::is_none")] - pub inventory: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The dimensions of this SKU for shipping purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). - pub price: i64, - - /// The ID of the product this SKU is associated with. - /// - /// Must be a product with type `good`. - pub product: IdOrCreate<'a, CreateProduct<'a>>, -} - -impl<'a> CreateSku<'a> { - pub fn new( - currency: Currency, - inventory: Option, - price: i64, - product: IdOrCreate<'a, CreateProduct<'a>>, - ) -> Self { - CreateSku { - active: Default::default(), - attributes: Default::default(), - currency, - expand: Default::default(), - id: Default::default(), - image: Default::default(), - inventory, - metadata: Default::default(), - package_dimensions: Default::default(), - price, - product, - } - } -} - -/// The parameters for `Sku::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListSkus<'a> { - /// Only return SKUs that are active or inactive (e.g., pass `false` to list all inactive products). - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Only return SKUs that have the specified key-value pairs in this partially constructed dictionary. - /// - /// Can be specified only if `product` is also supplied. - /// For instance, if the associated product has attributes `["color", "size"]`, passing in `attributes[color]=red` returns all the SKUs for this product that have `color` set to `red`. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Only return SKUs with the given IDs. - #[serde(skip_serializing_if = "Option::is_none")] - pub ids: Option>, - - /// Only return SKUs that are either in stock or out of stock (e.g., pass `false` to list all SKUs that are out of stock). - /// - /// If no value is provided, all SKUs are returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub in_stock: Option, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// The ID of the product whose SKUs will be retrieved. - /// - /// Must be a product with type `good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListSkus<'a> { - pub fn new() -> Self { - ListSkus { - active: Default::default(), - attributes: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - ids: Default::default(), - in_stock: Default::default(), - limit: Default::default(), - product: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `Sku::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSku<'a> { - /// Whether this SKU is available for purchase. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// A dictionary of attributes and values for the attributes defined by the product. - /// - /// When specified, `attributes` will partially update the existing attributes dictionary on the product, with the postcondition that a value must be present for each attribute key on the product. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The URL of an image for this SKU, meant to be displayable to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub image: Option<&'a str>, - - /// Description of the SKU's inventory. - #[serde(skip_serializing_if = "Option::is_none")] - pub inventory: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The dimensions of this SKU for shipping purposes. - #[serde(skip_serializing_if = "Option::is_none")] - pub package_dimensions: Option, - - /// The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 100 to charge ¥100, Japanese Yen being a zero-decimal currency). - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// The ID of the product that this SKU should belong to. - /// - /// The product must exist, have the same set of attribute names as the SKU's current product, and be of type `good`. - #[serde(skip_serializing_if = "Option::is_none")] - pub product: Option>>, -} - -impl<'a> UpdateSku<'a> { - pub fn new() -> Self { - UpdateSku { - active: Default::default(), - attributes: Default::default(), - currency: Default::default(), - expand: Default::default(), - image: Default::default(), - inventory: Default::default(), - metadata: Default::default(), - package_dimensions: Default::default(), - price: Default::default(), - product: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/source.rs b/ft-stripe/src/resources/source.rs deleted file mode 100644 index cb49314..0000000 --- a/ft-stripe/src/resources/source.rs +++ /dev/null @@ -1,1512 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, SourceId, TokenId}; -use crate::params::{Expand, Metadata, Object, Timestamp}; -use crate::resources::{ - Address, BillingDetails, Currency, Shipping, SourceRedirectFlowFailureReason, - SourceRedirectFlowStatus, SourceStatus, SourceUsage, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Source". -/// -/// For more details see [https://stripe.com/docs/api/sources/object](https://stripe.com/docs/api/sources/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Source { - /// Unique identifier for the object. - pub id: SourceId, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ach_credit_transfer: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ach_debit: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub alipay: Option, - - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount associated with the source. - /// - /// This is the amount for which the source will be chargeable once ready. - /// Required for `single_use` sources. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub au_becs_debit: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bancontact: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card_present: Option, - - /// The client secret of the source. - /// - /// Used for client-side retrieval using a publishable key. - pub client_secret: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub code_verification: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. - /// - /// This is the currency for which the source will be chargeable once ready. - /// Required for `single_use` sources. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The ID of the customer to which this source is attached. - /// - /// This will not be present when the source has not been attached to a customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub eps: Option, - - /// The authentication `flow` of the source. - /// - /// `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. - pub flow: SourceFlow, - - #[serde(skip_serializing_if = "Option::is_none")] - pub giropay: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ideal: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub klarna: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub multibanco: Option, - - /// Information about the owner of the payment instrument that may be used or required by particular source types. - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub p24: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub receiver: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub sepa_debit: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub sofort: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub source_order: Option, - - /// Extra information about a source. - /// - /// This will appear on your customer's statement every time you charge the source. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// The status of the source, one of `canceled`, `chargeable`, `consumed`, `failed`, or `pending`. - /// - /// Only `chargeable` sources can be used to create a charge. - pub status: SourceStatus, - - #[serde(skip_serializing_if = "Option::is_none")] - pub three_d_secure: Option, - - /// The `type` of the source. - /// - /// The `type` is a payment method, one of `ach_credit_transfer`, `ach_debit`, `alipay`, `bancontact`, `card`, `card_present`, `eps`, `giropay`, `ideal`, `multibanco`, `klarna`, `p24`, `sepa_debit`, `sofort`, `three_d_secure`, or `wechat`. - /// An additional hash is included on the source with a name matching this value. - /// It contains additional information specific to the [payment method](https://stripe.com/docs/sources) used. - #[serde(rename = "type")] - pub type_: SourceType, - - /// Either `reusable` or `single_use`. - /// - /// Whether this source should be reusable or not. - /// Some source types may or may not be reusable by construction, while others may leave the option at creation. - /// If an incompatible value is passed, an error will be returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub usage: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub wechat: Option, -} - -impl Source { - /// Creates a new source object. - pub fn create(client: &Client, params: CreateSource<'_>) -> Response { - client.post_form("/sources", ¶ms) - } - - /// Retrieves an existing source object. - /// - /// Supply the unique source ID from a source creation request and Stripe will return the corresponding up-to-date source object information. - pub fn retrieve(client: &Client, id: &SourceId, expand: &[&str]) -> Response { - client.get_query(&format!("/sources/{}", id), &Expand { expand }) - } - - /// Updates the specified source by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. This request accepts the `metadata` and `owner` as arguments. - /// It is also possible to update type specific information for selected payment methods. - /// Please refer to our [payment method guides](https://stripe.com/docs/sources) for more detail. - pub fn update(client: &Client, id: &SourceId, params: UpdateSource<'_>) -> Response { - client.post_form(&format!("/sources/{}", id), ¶ms) - } -} - -impl Object for Source { - type Id = SourceId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "source" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceCodeVerificationFlow { - /// The number of attempts remaining to authenticate the source object with a verification code. - pub attempts_remaining: i64, - - /// The status of the code verification, either `pending` (awaiting verification, `attempts_remaining` should be greater than 0), `succeeded` (successful verification) or `failed` (failed verification, cannot be verified anymore as `attempts_remaining` should be 0). - pub status: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceOrder { - /// A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total amount for the order. - pub amount: i64, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// The email address of the customer placing the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// List of items constituting the order. - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceOrderItem { - /// The amount (price) for this order item. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// This currency of this order item. - /// - /// Required when `amount` is present. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// Human-readable description for this order item. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The quantity of this order item. - /// - /// When type is `sku`, this is the number of instances of the SKU to be ordered. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The type of this order item. - /// - /// Must be `sku`, `tax`, or `shipping`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceOwner { - /// Owner's address. - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - /// Owner's email address. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// Owner's full name. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Owner's phone number (including extension). - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - /// Verified owner's address. - /// - /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_address: Option
, - - /// Verified owner's email address. - /// - /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_email: Option, - - /// Verified owner's full name. - /// - /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_name: Option, - - /// Verified owner's phone number (including extension). - /// - /// Verified values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement. - /// They cannot be set or mutated. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_phone: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceReceiverFlow { - /// The address of the receiver source. - /// - /// This is the value that should be communicated to the customer to send their funds to. - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option, - - /// The total amount that was moved to your balance. - /// - /// This is almost always equal to the amount charged. - /// In rare cases when customers deposit excess funds and we are unable to refund those, those funds get moved to your balance and show up in amount_charged as well. - /// The amount charged is expressed in the source's currency. - pub amount_charged: i64, - - /// The total amount received by the receiver source. - /// - /// `amount_received = amount_returned + amount_charged` should be true for consumed sources unless customers deposit excess funds. - /// The amount received is expressed in the source's currency. - pub amount_received: i64, - - /// The total amount that was returned to the customer. - /// - /// The amount returned is expressed in the source's currency. - pub amount_returned: i64, - - /// Type of refund attribute method, one of `email`, `manual`, or `none`. - pub refund_attributes_method: String, - - /// Type of refund attribute status, one of `missing`, `requested`, or `available`. - pub refund_attributes_status: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceRedirectFlow { - /// The failure reason for the redirect, either `user_abort` (the customer aborted or dropped out of the redirect flow), `declined` (the authentication failed or the transaction was declined), or `processing_error` (the redirect failed due to a technical error). - /// - /// Present only if the redirect status is `failed`. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_reason: Option, - - /// The URL you provide to redirect the customer to after they authenticated their payment. - pub return_url: String, - - /// The status of the redirect, either `pending` (ready to be used by your customer to authenticate the transaction), `succeeded` (succesful authentication, cannot be reused) or `not_required` (redirect should not be used) or `failed` (failed authentication, cannot be reused). - pub status: SourceRedirectFlowStatus, - - /// The URL provided to you to redirect a customer to as part of a `redirect` authentication flow. - pub url: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeAchCreditTransfer { - #[serde(skip_serializing_if = "Option::is_none")] - pub account_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_routing_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub routing_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub swift_code: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeAchDebit { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub routing_number: Option, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeAlipay { - #[serde(skip_serializing_if = "Option::is_none")] - pub data_string: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub native_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeAuBecsDebit { - #[serde(skip_serializing_if = "Option::is_none")] - pub bsb_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeBancontact { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub iban_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_language: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeCard { - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line1_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_zip_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dynamic_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_month: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_year: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub funding: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub three_d_secure: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tokenization_method: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeCardPresent { - #[serde(skip_serializing_if = "Option::is_none")] - pub application_cryptogram: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub application_preferred_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub authorization_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub authorization_response_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub cvm_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub data_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dedicated_file_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub emv_auth_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub evidence_customer_signature: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub evidence_transaction_certificate: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_month: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_year: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub funding: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pos_device_id: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pos_entry_mode: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub read_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub reader: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub terminal_verification_results: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub transaction_status_information: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeEps { - #[serde(skip_serializing_if = "Option::is_none")] - pub reference: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeGiropay { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeIdeal { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub iban_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeKlarna { - #[serde(skip_serializing_if = "Option::is_none")] - pub background_image_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub client_token: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub locale: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub logo_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub page_title: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_later_asset_urls_descriptive: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_later_asset_urls_standard: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_later_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_later_redirect_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_now_asset_urls_descriptive: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_now_asset_urls_standard: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_now_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_now_redirect_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_over_time_asset_urls_descriptive: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_over_time_asset_urls_standard: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_over_time_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub pay_over_time_redirect_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_method_categories: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub purchase_country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub purchase_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_first_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping_last_name: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeMultibanco { - #[serde(skip_serializing_if = "Option::is_none")] - pub entity: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub reference: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_city: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_line1: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_line2: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_postal_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_address_state: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_account_holder_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_iban: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeP24 { - #[serde(skip_serializing_if = "Option::is_none")] - pub reference: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeSepaDebit { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub branch_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate_reference: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate_url: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeSofort { - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bic: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub iban_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_language: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeThreeDSecure { - #[serde(skip_serializing_if = "Option::is_none")] - pub address_line1_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_zip_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub authenticated: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc_check: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dynamic_last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_month: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub exp_year: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fingerprint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub funding: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub three_d_secure: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tokenization_method: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceTypeWechat { - #[serde(skip_serializing_if = "Option::is_none")] - pub prepay_id: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub qr_code_url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, -} - -/// The parameters for `Source::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateSource<'a> { - /// Amount associated with the source. - /// - /// This is the amount for which the source will be chargeable once ready. - /// Required for `single_use` sources. - /// Not supported for `receiver` type sources, where charge amount may not be specified until funds land. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Three-letter [ISO code for the currency](https://stripe.com/docs/currencies) associated with the source. - /// - /// This is the currency for which the source will be chargeable once ready. - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - /// The `Customer` to whom the original source is attached to. - /// - /// Must be set when the original source is not a `Source` (e.g., `Card`). - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The authentication `flow` of the source to create. - /// - /// `flow` is one of `redirect`, `receiver`, `code_verification`, `none`. - /// It is generally inferred unless a type supports multiple flows. - #[serde(skip_serializing_if = "Option::is_none")] - pub flow: Option, - - /// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The source to share. - #[serde(skip_serializing_if = "Option::is_none")] - pub original_source: Option<&'a str>, - - /// Information about the owner of the payment instrument that may be used or required by particular source types. - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - - /// Optional parameters for the receiver flow. - /// - /// Can be set only if the source is a receiver (`flow` is `receiver`). - #[serde(skip_serializing_if = "Option::is_none")] - pub receiver: Option, - - /// Parameters required for the redirect flow. - /// - /// Required if the source is authenticated by a redirect (`flow` is `redirect`). - #[serde(skip_serializing_if = "Option::is_none")] - pub redirect: Option, - - /// Information about the items and shipping associated with the source. - /// - /// Required for transactional credit (for example Klarna) sources before you can charge it. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_order: Option, - - /// An arbitrary string to be displayed on your customer's statement. - /// - /// As an example, if your website is `RunClub` and the item you're charging for is a race ticket, you may want to specify a `statement_descriptor` of `RunClub 5K race ticket.` While many payment types will display this information, some may not display it at all. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option<&'a str>, - - /// An optional token used to create the source. - /// - /// When passed, token properties will override source parameters. - #[serde(skip_serializing_if = "Option::is_none")] - pub token: Option, - - /// The `type` of the source to create. - /// - /// Required unless `customer` and `original_source` are specified (see the [Cloning card Sources](https://stripe.com/docs/sources/connect#cloning-card-sources) guide). - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option<&'a str>, -} - -impl<'a> CreateSource<'a> { - pub fn new() -> Self { - CreateSource { - amount: Default::default(), - currency: Default::default(), - customer: Default::default(), - expand: Default::default(), - flow: Default::default(), - mandate: Default::default(), - metadata: Default::default(), - original_source: Default::default(), - owner: Default::default(), - receiver: Default::default(), - redirect: Default::default(), - source_order: Default::default(), - statement_descriptor: Default::default(), - token: Default::default(), - type_: Default::default(), - } - } -} - -/// The parameters for `Source::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSource<'a> { - /// Amount associated with the source. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Information about a mandate possibility attached to a source object (generally for bank debits) as well as its acceptance status. - #[serde(skip_serializing_if = "Option::is_none")] - pub mandate: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Information about the owner of the payment instrument that may be used or required by particular source types. - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - - /// Information about the items and shipping associated with the source. - /// - /// Required for transactional credit (for example Klarna) sources before you can charge it. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_order: Option, -} - -impl<'a> UpdateSource<'a> { - pub fn new() -> Self { - UpdateSource { - amount: Default::default(), - expand: Default::default(), - mandate: Default::default(), - metadata: Default::default(), - owner: Default::default(), - source_order: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceReceiver { - #[serde(skip_serializing_if = "Option::is_none")] - pub refund_attributes_method: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceRedirect { - pub return_url: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceSourceOrder { - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceMandateParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub acceptance: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub notification_method: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSourceSourceOrder { - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub shipping: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceSourceOrderItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub parent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceSourceOrderShipping { - pub address: CreateSourceSourceOrderShippingAddress, - - #[serde(skip_serializing_if = "Option::is_none")] - pub carrier: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tracking_number: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceAcceptanceParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ip: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub offline: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub online: Option, - - pub status: SourceAcceptanceParamsStatus, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSourceSourceOrderItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub currency: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub parent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSourceSourceOrderShipping { - pub address: UpdateSourceSourceOrderShippingAddress, - - #[serde(skip_serializing_if = "Option::is_none")] - pub carrier: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tracking_number: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSourceSourceOrderShippingAddress { - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - pub line1: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub line2: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub postal_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceAcceptanceOfflineParams { - pub contact_email: String, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SourceAcceptanceOnlineParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ip: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSourceSourceOrderShippingAddress { - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - pub line1: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub line2: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub postal_code: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, -} - -/// An enum representing the possible values of an `CreateSourceSourceOrderItems`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum CreateSourceSourceOrderItemsType { - Discount, - Shipping, - Sku, - Tax, -} - -impl CreateSourceSourceOrderItemsType { - pub fn as_str(self) -> &'static str { - match self { - CreateSourceSourceOrderItemsType::Discount => "discount", - CreateSourceSourceOrderItemsType::Shipping => "shipping", - CreateSourceSourceOrderItemsType::Sku => "sku", - CreateSourceSourceOrderItemsType::Tax => "tax", - } - } -} - -impl AsRef for CreateSourceSourceOrderItemsType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for CreateSourceSourceOrderItemsType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceAcceptanceParams`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceAcceptanceParamsStatus { - Accepted, - Pending, - Refused, - Revoked, -} - -impl SourceAcceptanceParamsStatus { - pub fn as_str(self) -> &'static str { - match self { - SourceAcceptanceParamsStatus::Accepted => "accepted", - SourceAcceptanceParamsStatus::Pending => "pending", - SourceAcceptanceParamsStatus::Refused => "refused", - SourceAcceptanceParamsStatus::Revoked => "revoked", - } - } -} - -impl AsRef for SourceAcceptanceParamsStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceAcceptanceParamsStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceAcceptanceParams`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceAcceptanceParamsType { - Offline, - Online, -} - -impl SourceAcceptanceParamsType { - pub fn as_str(self) -> &'static str { - match self { - SourceAcceptanceParamsType::Offline => "offline", - SourceAcceptanceParamsType::Online => "online", - } - } -} - -impl AsRef for SourceAcceptanceParamsType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceAcceptanceParamsType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSource`'s `flow` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceFlow { - CodeVerification, - None, - Receiver, - Redirect, -} - -impl SourceFlow { - pub fn as_str(self) -> &'static str { - match self { - SourceFlow::CodeVerification => "code_verification", - SourceFlow::None => "none", - SourceFlow::Receiver => "receiver", - SourceFlow::Redirect => "redirect", - } - } -} - -impl AsRef for SourceFlow { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceFlow { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceMandateParams`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceMandateInterval { - OneTime, - Scheduled, - Variable, -} - -impl SourceMandateInterval { - pub fn as_str(self) -> &'static str { - match self { - SourceMandateInterval::OneTime => "one_time", - SourceMandateInterval::Scheduled => "scheduled", - SourceMandateInterval::Variable => "variable", - } - } -} - -impl AsRef for SourceMandateInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceMandateInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceMandateParams`'s `notification_method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceMandateNotificationMethod { - DeprecatedNone, - Email, - Manual, - None, - StripeEmail, -} - -impl SourceMandateNotificationMethod { - pub fn as_str(self) -> &'static str { - match self { - SourceMandateNotificationMethod::DeprecatedNone => "deprecated_none", - SourceMandateNotificationMethod::Email => "email", - SourceMandateNotificationMethod::Manual => "manual", - SourceMandateNotificationMethod::None => "none", - SourceMandateNotificationMethod::StripeEmail => "stripe_email", - } - } -} - -impl AsRef for SourceMandateNotificationMethod { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceMandateNotificationMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSourceReceiver`'s `refund_attributes_method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceRefundNotificationMethod { - Email, - Manual, - None, -} - -impl SourceRefundNotificationMethod { - pub fn as_str(self) -> &'static str { - match self { - SourceRefundNotificationMethod::Email => "email", - SourceRefundNotificationMethod::Manual => "manual", - SourceRefundNotificationMethod::None => "none", - } - } -} - -impl AsRef for SourceRefundNotificationMethod { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceRefundNotificationMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Source`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceType { - AchCreditTransfer, - AchDebit, - Alipay, - AuBecsDebit, - Bancontact, - Card, - CardPresent, - Eps, - Giropay, - Ideal, - Klarna, - Multibanco, - P24, - SepaDebit, - Sofort, - ThreeDSecure, - Wechat, -} - -impl SourceType { - pub fn as_str(self) -> &'static str { - match self { - SourceType::AchCreditTransfer => "ach_credit_transfer", - SourceType::AchDebit => "ach_debit", - SourceType::Alipay => "alipay", - SourceType::AuBecsDebit => "au_becs_debit", - SourceType::Bancontact => "bancontact", - SourceType::Card => "card", - SourceType::CardPresent => "card_present", - SourceType::Eps => "eps", - SourceType::Giropay => "giropay", - SourceType::Ideal => "ideal", - SourceType::Klarna => "klarna", - SourceType::Multibanco => "multibanco", - SourceType::P24 => "p24", - SourceType::SepaDebit => "sepa_debit", - SourceType::Sofort => "sofort", - SourceType::ThreeDSecure => "three_d_secure", - SourceType::Wechat => "wechat", - } - } -} - -impl AsRef for SourceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `UpdateSourceSourceOrderItems`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum UpdateSourceSourceOrderItemsType { - Discount, - Shipping, - Sku, - Tax, -} - -impl UpdateSourceSourceOrderItemsType { - pub fn as_str(self) -> &'static str { - match self { - UpdateSourceSourceOrderItemsType::Discount => "discount", - UpdateSourceSourceOrderItemsType::Shipping => "shipping", - UpdateSourceSourceOrderItemsType::Sku => "sku", - UpdateSourceSourceOrderItemsType::Tax => "tax", - } - } -} - -impl AsRef for UpdateSourceSourceOrderItemsType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for UpdateSourceSourceOrderItemsType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/source_ext.rs b/ft-stripe/src/resources/source_ext.rs deleted file mode 100644 index d9f4260..0000000 --- a/ft-stripe/src/resources/source_ext.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `Source`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceStatus { - Canceled, - Chargeable, - Consumed, - Failed, - Pending, -} - -impl SourceStatus { - pub fn as_str(self) -> &'static str { - match self { - SourceStatus::Canceled => "canceled", - SourceStatus::Chargeable => "chargeable", - SourceStatus::Consumed => "consumed", - SourceStatus::Failed => "failed", - SourceStatus::Pending => "pending", - } - } -} - -impl AsRef for SourceStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Source`'s `usage` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceUsage { - Reusable, - SingleUse, -} - -impl SourceUsage { - pub fn as_str(self) -> &'static str { - match self { - SourceUsage::Reusable => "reusable", - SourceUsage::SingleUse => "single_use", - } - } -} - -impl AsRef for SourceUsage { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceUsage { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceRedirectFlow`'s `failure_reason` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceRedirectFlowFailureReason { - Declined, - ProcessingError, - UserAbort, -} - -impl SourceRedirectFlowFailureReason { - pub fn as_str(self) -> &'static str { - match self { - SourceRedirectFlowFailureReason::Declined => "declined", - SourceRedirectFlowFailureReason::ProcessingError => "processing_error", - SourceRedirectFlowFailureReason::UserAbort => "user_abort", - } - } -} - -impl AsRef for SourceRedirectFlowFailureReason { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceRedirectFlowFailureReason { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SourceRedirectFlow`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SourceRedirectFlowStatus { - Failed, - NotRequired, - Pending, - Succeeded, -} - -impl SourceRedirectFlowStatus { - pub fn as_str(self) -> &'static str { - match self { - SourceRedirectFlowStatus::Failed => "failed", - SourceRedirectFlowStatus::NotRequired => "not_required", - SourceRedirectFlowStatus::Pending => "pending", - SourceRedirectFlowStatus::Succeeded => "succeeded", - } - } -} - -impl AsRef for SourceRedirectFlowStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SourceRedirectFlowStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/subscription.rs b/ft-stripe/src/resources/subscription.rs deleted file mode 100644 index e172226..0000000 --- a/ft-stripe/src/resources/subscription.rs +++ /dev/null @@ -1,1202 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CouponId, CustomerId, PlanId, PriceId, SubscriptionId}; -use crate::params::{Deleted, Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - CollectionMethod, Currency, Customer, Discount, Invoice, PaymentMethod, PaymentSource, Plan, - Scheduled, SetupIntent, SubscriptionBillingThresholds, SubscriptionItem, - SubscriptionItemBillingThresholds, SubscriptionSchedule, TaxRate, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Subscription". -/// -/// For more details see [https://stripe.com/docs/api/subscriptions/object](https://stripe.com/docs/api/subscriptions/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Subscription { - /// Unique identifier for the object. - pub id: SubscriptionId, - - /// A non-negative decimal between 0 and 100, with at most two decimal places. - /// - /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - /// Determines the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. - pub billing_cycle_anchor: Timestamp, - - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// A date in the future at which the subscription will automatically get canceled. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancel_at: Option, - - /// If the subscription has been canceled with the `at_period_end` flag set to `true`, `cancel_at_period_end` on the subscription will be true. - /// - /// You can use this attribute to determine whether a subscription that has a status of active is scheduled to be canceled at the end of the current period. - pub cancel_at_period_end: bool, - - /// If the subscription has been canceled, the date of that cancellation. - /// - /// If the subscription was canceled with `cancel_at_period_end`, `canceled_at` will still reflect the date of the initial cancellation request, not the end of the subscription period when the subscription is automatically moved to a canceled state. - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled_at: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. - /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// End of the current period that the subscription has been invoiced for. - /// - /// At the end of this period, a new invoice will be created. - pub current_period_end: Timestamp, - - /// Start of the current period that the subscription has been invoiced for. - pub current_period_start: Timestamp, - - /// ID of the customer who owns the subscription. - pub customer: Expandable, - - /// Number of days a customer has to pay invoices generated by this subscription. - /// - /// This value will be `null` for subscriptions where `collection_method=charge_automatically`. - #[serde(skip_serializing_if = "Option::is_none")] - pub days_until_due: Option, - - /// ID of the default payment method for the subscription. - /// - /// It must belong to the customer associated with the subscription. - /// If not set, invoices will use the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option>, - - /// ID of the default payment source for the subscription. - /// - /// It must belong to the customer associated with the subscription and be in a chargeable state. - /// If not set, defaults to the customer's default source. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option>, - - /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. - /// - /// Invoices created will have their `default_tax_rates` populated from the subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - /// Describes the current discount applied to this subscription, if there is one. - /// - /// When billing, a discount applied to a subscription overrides a discount applied on a customer-wide basis. - #[serde(skip_serializing_if = "Option::is_none")] - pub discount: Option, - - /// If the subscription has ended, the date the subscription ended. - #[serde(skip_serializing_if = "Option::is_none")] - pub ended_at: Option, - - /// List of subscription items, each with an attached plan. - pub items: List, - - /// The most recent invoice this subscription has generated. - #[serde(skip_serializing_if = "Option::is_none")] - pub latest_invoice: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at `pending_invoice_item_interval`. - #[serde(skip_serializing_if = "Option::is_none")] - pub next_pending_invoice_item_invoice: Option, - - /// If specified, payment collection for this subscription will be paused. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_collection: Option, - - /// Specifies an interval for how often to bill for any pending invoice items. - /// - /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_invoice_item_interval: Option, - - /// 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. - /// - /// Learn more in the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-2). - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_setup_intent: Option>, - - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_update: Option, - - /// Hash describing the plan the customer is subscribed to. - /// - /// Only set if the subscription contains a single plan. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// The quantity of the plan to which the customer is subscribed. - /// - /// For example, if your plan is $10/user/month, and your customer has 5 users, you could pass 5 as the quantity to have the customer charged $50 (5 x $10) monthly. - /// Only set if the subscription contains a single plan. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The schedule attached to the subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub schedule: Option>, - - /// Date when the subscription was first created. - /// - /// The date might differ from the `created` date due to backdating. - pub start_date: Timestamp, - - /// Possible values are `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `canceled`, or `unpaid`. - /// - /// For `collection_method=charge_automatically` a subscription moves into `incomplete` if the initial payment attempt fails. - /// A subscription in this state can only have metadata and default_source updated. - /// Once the first invoice is paid, the subscription moves into an `active` state. - /// If the first invoice is not paid within 23 hours, the subscription transitions to `incomplete_expired`. - /// This is a terminal state, the open invoice will be voided and no further invoices will be generated. - /// A subscription that is currently in a trial period is `trialing` and moves to `active` when the trial period is over. - /// If subscription `collection_method=charge_automatically` it becomes `past_due` when payment to renew it fails and `canceled` or `unpaid` (depending on your subscriptions settings) when Stripe has exhausted all payment retry attempts. - /// 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. - /// 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). - /// After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices. - pub status: SubscriptionStatus, - - /// If provided, each invoice created by this subscription will apply the tax rate, increasing the amount billed to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - /// If the subscription has a trial, the end of that trial. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, - - /// If the subscription has a trial, the beginning of that trial. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_start: Option, -} - -impl Subscription { - /// By default, returns a list of subscriptions that have not been canceled. - /// - /// In order to list canceled subscriptions, specify `status=canceled`. - pub fn list(client: &Client, params: ListSubscriptions<'_>) -> Response> { - client.get_query("/subscriptions", ¶ms) - } - - /// Creates a new subscription on an existing customer. - /// - /// Each customer can have up to 25 active or scheduled subscriptions. - pub fn create(client: &Client, params: CreateSubscription<'_>) -> Response { - client.post_form("/subscriptions", ¶ms) - } - - /// Retrieves the subscription with the given ID. - pub fn retrieve( - client: &Client, - id: &SubscriptionId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/subscriptions/{}", id), &Expand { expand }) - } - - /// Updates an existing subscription on a customer to match the specified parameters. - /// - /// When changing plans or quantities, we will optionally prorate the price we charge next month to make up for any price changes. - /// To preview how the proration will be calculated, use the [upcoming invoice](https://stripe.com/docs/api#upcoming_invoice) endpoint. - pub fn update( - client: &Client, - id: &SubscriptionId, - params: UpdateSubscription<'_>, - ) -> Response { - client.post_form(&format!("/subscriptions/{}", id), ¶ms) - } - - /// Cancels a customer’s subscription immediately. - /// - /// The customer will not be charged again for the subscription. Note, however, that any pending invoice items that you’ve created will still be charged for at the end of the period, unless manually [deleted](https://stripe.com/docs/api#delete_invoiceitem). - /// If you’ve set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. - /// But if the subscription is set to cancel immediately, pending prorations will be removed. By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. - /// This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. - /// However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. - /// Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all. - pub fn delete(client: &Client, id: &SubscriptionId) -> Response> { - client.delete(&format!("/subscriptions/{}", id)) - } -} - -impl Object for Subscription { - type Id = SubscriptionId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionPendingInvoiceItemInterval { - /// Specifies invoicing frequency. - /// - /// Either `day`, `week`, `month` or `year`. - pub interval: PlanInterval, - - /// The number of intervals between invoices. - /// - /// For example, `interval=month` and `interval_count=3` bills every 3 months. - /// Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). - pub interval_count: u64, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionsResourcePauseCollection { - /// The payment collection behavior for this subscription while paused. - /// - /// One of `keep_as_draft`, `mark_uncollectible`, or `void`. - pub behavior: SubscriptionsResourcePauseCollectionBehavior, - - /// The time after which the subscription will resume collecting payments. - #[serde(skip_serializing_if = "Option::is_none")] - pub resumes_at: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionsResourcePendingUpdate { - /// If the update is applied, determines the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_cycle_anchor: Option, - - /// The point after which the changes reflected by this update will be discarded and no longer applied. - pub expires_at: Timestamp, - - /// List of subscription items, each with an attached plan, that will be set if the update is applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription_items: Option>, - - /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time, if the update is applied. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, - - /// Indicates if a plan's `trial_period_days` should be applied to the subscription. - /// - /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. - /// Setting this flag to `true` together with `trial_end` is not allowed. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_from_plan: Option, -} - -/// The parameters for `Subscription::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateSubscription<'a> { - /// A list of prices and quantities that will generate invoice items appended to the first invoice for this subscription. - /// - /// You may pass up to 10 items. - #[serde(skip_serializing_if = "Option::is_none")] - pub add_invoice_items: Option>, - - /// A non-negative decimal between 0 and 100, with at most two decimal places. - /// - /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. - /// The request must be made by a platform account on a connected account in order to set an application fee percentage. - /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - /// For new subscriptions, a past timestamp to backdate the subscription's start date to. - /// - /// If set, the first invoice will contain a proration for the timespan between the start date and the current time. - /// Can be combined with trials and the billing cycle anchor. - #[serde(skip_serializing_if = "Option::is_none")] - pub backdate_start_date: Option, - - /// A future timestamp to anchor the subscription's [billing cycle](https://stripe.com/docs/subscriptions/billing-cycle). - /// - /// This is used to determine the date of the first full invoice, and, for plans with `month` or `year` intervals, the day of the month for subsequent invoices. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_cycle_anchor: Option, - - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - /// - /// Pass an empty string to remove previously-defined thresholds. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// A timestamp at which the subscription should cancel. - /// - /// If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. - /// If set during a future period, this will always cause a proration for that period. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancel_at: Option, - - /// Boolean indicating whether this subscription should cancel at the end of the current period. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancel_at_period_end: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. - /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. - /// Defaults to `charge_automatically`. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// The code of the coupon to apply to this subscription. - /// - /// A coupon applied to a subscription will only affect invoices created for that particular subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// The identifier of the customer to subscribe. - pub customer: CustomerId, - - /// Number of days a customer has to pay invoices generated by this subscription. - /// - /// Valid only for subscriptions where `collection_method` is set to `send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub days_until_due: Option, - - /// ID of the default payment method for the subscription. - /// - /// It must belong to the customer associated with the subscription. - /// If not set, invoices will use the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option<&'a str>, - - /// ID of the default payment source for the subscription. - /// - /// It must belong to the customer associated with the subscription and be in a chargeable state. - /// If not set, defaults to the customer's default source. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option<&'a str>, - - /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. - /// - /// Invoices created will have their `default_tax_rates` populated from the subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A list of up to 20 subscription items, each with an attached plan. - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Indicates if a customer is on or off-session while an invoice payment is attempted. - #[serde(skip_serializing_if = "Option::is_none")] - pub off_session: Option, - - /// Use `allow_incomplete` to create subscriptions with `status=incomplete` if the first invoice cannot be paid. - /// - /// Creating subscriptions with this status allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. - /// For example, SCA regulation may require 3DS authentication to complete payment. - /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. - /// This is the default behavior. Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. - /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. - /// This was the default behavior for API versions prior to 2019-03-14. - /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. `pending_if_incomplete` is only used with updates and cannot be passed when creating a subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_behavior: Option, - - /// Specifies an interval for how often to bill for any pending invoice items. - /// - /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_invoice_item_interval: Option, - - /// This field has been renamed to `proration_behavior`. - /// - /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub prorate: Option, - - /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) resulting from the `billing_cycle_anchor`. - /// - /// Valid values are `create_prorations` or `none`. Passing `create_prorations` will cause proration invoice items to be created when applicable. - /// Prorations can be disabled by passing `none`. - /// If no value is passed, the default is `create_prorations`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - /// A non-negative decimal (with at most four decimal places) between 0 and 100. - /// - /// This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount in each billing period. - /// For example, a plan which charges $10/month with a `tax_percent` of `20.0` will charge $12 per invoice. - /// To unset a previously-set value, pass an empty string. - /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. - /// - /// This will always overwrite any trials that might apply via a subscribed plan. - /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. - /// The special value `now` can be provided to end the customer's trial immediately. - /// Can be at most two years from `billing_cycle_anchor`. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, - - /// Indicates if a plan's `trial_period_days` should be applied to the subscription. - /// - /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. - /// Setting this flag to `true` together with `trial_end` is not allowed. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_from_plan: Option, - - /// Integer representing the number of trial period days before the customer is charged for the first time. - /// - /// This will always overwrite any trials that might apply via a subscribed plan. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_period_days: Option, -} - -impl<'a> CreateSubscription<'a> { - pub fn new(customer: CustomerId) -> Self { - CreateSubscription { - add_invoice_items: Default::default(), - application_fee_percent: Default::default(), - backdate_start_date: Default::default(), - billing_cycle_anchor: Default::default(), - billing_thresholds: Default::default(), - cancel_at: Default::default(), - cancel_at_period_end: Default::default(), - collection_method: Default::default(), - coupon: Default::default(), - customer, - days_until_due: Default::default(), - default_payment_method: Default::default(), - default_source: Default::default(), - default_tax_rates: Default::default(), - expand: Default::default(), - items: Default::default(), - metadata: Default::default(), - off_session: Default::default(), - payment_behavior: Default::default(), - pending_invoice_item_interval: Default::default(), - prorate: Default::default(), - proration_behavior: Default::default(), - tax_percent: Default::default(), - trial_end: Default::default(), - trial_from_plan: Default::default(), - trial_period_days: Default::default(), - } - } -} - -/// The parameters for `Subscription::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListSubscriptions<'a> { - /// The collection method of the subscriptions to retrieve. - /// - /// Either `charge_automatically` or `send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub current_period_end: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub current_period_start: Option>, - - /// The ID of the customer whose subscriptions will be retrieved. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// The ID of the plan whose subscriptions will be retrieved. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// Filter for subscriptions that contain this recurring price ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// The status of the subscriptions to retrieve. - /// - /// One of: `incomplete`, `incomplete_expired`, `trialing`, `active`, `past_due`, `unpaid`, `canceled`, or `all`. - /// Passing in a value of `canceled` will return all canceled subscriptions, including those belonging to deleted customers. - /// Passing in a value of `all` will return subscriptions of all statuses. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, -} - -impl<'a> ListSubscriptions<'a> { - pub fn new() -> Self { - ListSubscriptions { - collection_method: Default::default(), - created: Default::default(), - current_period_end: Default::default(), - current_period_start: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - plan: Default::default(), - price: Default::default(), - starting_after: Default::default(), - status: Default::default(), - } - } -} - -/// The parameters for `Subscription::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSubscription<'a> { - /// A list of prices and quantities that will generate invoice items appended to the first invoice for this subscription. - /// - /// You may pass up to 10 items. - #[serde(skip_serializing_if = "Option::is_none")] - pub add_invoice_items: Option>, - - /// A non-negative decimal between 0 and 100, with at most two decimal places. - /// - /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account. - /// The request must be made by a platform account on a connected account in order to set an application fee percentage. - /// For more information, see the application fees [documentation](https://stripe.com/docs/connect/subscriptions#collecting-fees-on-subscriptions). - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - /// Either `now` or `unchanged`. - /// - /// Setting the value to `now` resets the subscription's billing cycle anchor to the current time. - /// For more information, see the billing cycle [documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle). - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_cycle_anchor: Option, - - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - /// - /// Pass an empty string to remove previously-defined thresholds. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// A timestamp at which the subscription should cancel. - /// - /// If set to a date before the current period ends, this will cause a proration if prorations have been enabled using `proration_behavior`. - /// If set during a future period, this will always cause a proration for that period. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancel_at: Option, - - /// Boolean indicating whether this subscription should cancel at the end of the current period. - #[serde(skip_serializing_if = "Option::is_none")] - pub cancel_at_period_end: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. - /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. - /// Defaults to `charge_automatically`. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// The code of the coupon to apply to this subscription. - /// - /// A coupon applied to a subscription will only affect invoices created for that particular subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - /// Number of days a customer has to pay invoices generated by this subscription. - /// - /// Valid only for subscriptions where `collection_method` is set to `send_invoice`. - #[serde(skip_serializing_if = "Option::is_none")] - pub days_until_due: Option, - - /// ID of the default payment method for the subscription. - /// - /// It must belong to the customer associated with the subscription. - /// If not set, invoices will use the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option<&'a str>, - - /// ID of the default payment source for the subscription. - /// - /// It must belong to the customer associated with the subscription and be in a chargeable state. - /// If not set, defaults to the customer's default source. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_source: Option<&'a str>, - - /// The tax rates that will apply to any subscription item that does not have `tax_rates` set. - /// - /// Invoices created will have their `default_tax_rates` populated from the subscription. - /// Pass an empty string to remove previously-defined tax rates. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// List of subscription items, each with an attached plan. - #[serde(skip_serializing_if = "Option::is_none")] - pub items: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Indicates if a customer is on or off-session while an invoice payment is attempted. - #[serde(skip_serializing_if = "Option::is_none")] - pub off_session: Option, - - /// If specified, payment collection for this subscription will be paused. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_collection: Option, - - /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. - /// - /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. - /// For example, SCA regulation may require 3DS authentication to complete payment. - /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. - /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). - /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. - /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. - /// This was the default behavior for API versions prior to 2019-03-14. - /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_behavior: Option, - - /// Specifies an interval for how often to bill for any pending invoice items. - /// - /// It is analogous to calling [Create an invoice](https://stripe.com/docs/api#create_invoice) for the given subscription at the specified interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub pending_invoice_item_interval: Option, - - /// This field has been renamed to `proration_behavior`. - /// - /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub prorate: Option, - - /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. - /// - /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. - /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). - /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - /// If set, the proration will be calculated as though the subscription was updated at the given time. - /// - /// This can be used to apply exactly the same proration that was previewed with [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. - /// It can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_date: Option, - - /// A non-negative decimal (with at most four decimal places) between 0 and 100. - /// - /// This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount in each billing period. - /// For example, a plan which charges $10/month with a `tax_percent` of `20.0` will charge $12 per invoice. - /// To unset a previously-set value, pass an empty string. - /// This field has been deprecated and will be removed in a future API version, for further information view the [migration docs](https://stripe.com/docs/billing/migration/taxes) for `tax_rates`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - /// Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. - /// - /// This will always overwrite any trials that might apply via a subscribed plan. - /// If set, trial_end will override the default trial period of the plan the customer is being subscribed to. - /// The special value `now` can be provided to end the customer's trial immediately. - /// Can be at most two years from `billing_cycle_anchor`. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, - - /// Indicates if a plan's `trial_period_days` should be applied to the subscription. - /// - /// Setting `trial_end` per subscription is preferred, and this defaults to `false`. - /// Setting this flag to `true` together with `trial_end` is not allowed. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_from_plan: Option, -} - -impl<'a> UpdateSubscription<'a> { - pub fn new() -> Self { - UpdateSubscription { - add_invoice_items: Default::default(), - application_fee_percent: Default::default(), - billing_cycle_anchor: Default::default(), - billing_thresholds: Default::default(), - cancel_at: Default::default(), - cancel_at_period_end: Default::default(), - collection_method: Default::default(), - coupon: Default::default(), - days_until_due: Default::default(), - default_payment_method: Default::default(), - default_source: Default::default(), - default_tax_rates: Default::default(), - expand: Default::default(), - items: Default::default(), - metadata: Default::default(), - off_session: Default::default(), - pause_collection: Default::default(), - payment_behavior: Default::default(), - pending_invoice_item_interval: Default::default(), - prorate: Default::default(), - proration_behavior: Default::default(), - proration_date: Default::default(), - tax_percent: Default::default(), - trial_end: Default::default(), - trial_from_plan: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AddInvoiceItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSubscriptionItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSubscriptionPendingInvoiceItemInterval { - pub interval: PlanInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSubscriptionItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub clear_usage: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub deleted: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option, - - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSubscriptionPauseCollection { - pub behavior: UpdateSubscriptionPauseCollectionBehavior, - - #[serde(skip_serializing_if = "Option::is_none")] - pub resumes_at: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSubscriptionPendingInvoiceItemInterval { - pub interval: PlanInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSubscriptionItemsBillingThresholds { - pub usage_gte: i64, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItemPriceData { - pub currency: Currency, - - pub product: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceData { - pub currency: Currency, - - pub product: String, - - pub recurring: SubscriptionItemPriceDataRecurring, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceDataRecurring { - pub interval: PlanInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, -} - -/// An enum representing the possible values of an `SubscriptionPendingInvoiceItemInterval`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanInterval { - Day, - Month, - Week, - Year, -} - -impl PlanInterval { - pub fn as_str(self) -> &'static str { - match self { - PlanInterval::Day => "day", - PlanInterval::Month => "month", - PlanInterval::Week => "week", - PlanInterval::Year => "year", - } - } -} - -impl AsRef for PlanInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `UpdateSubscription`'s `billing_cycle_anchor` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionBillingCycleAnchor { - Now, - Unchanged, -} - -impl SubscriptionBillingCycleAnchor { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionBillingCycleAnchor::Now => "now", - SubscriptionBillingCycleAnchor::Unchanged => "unchanged", - } - } -} - -impl AsRef for SubscriptionBillingCycleAnchor { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionBillingCycleAnchor { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSubscription`'s `payment_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionPaymentBehavior { - AllowIncomplete, - ErrorIfIncomplete, - PendingIfIncomplete, -} - -impl SubscriptionPaymentBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionPaymentBehavior::AllowIncomplete => "allow_incomplete", - SubscriptionPaymentBehavior::ErrorIfIncomplete => "error_if_incomplete", - SubscriptionPaymentBehavior::PendingIfIncomplete => "pending_if_incomplete", - } - } -} - -impl AsRef for SubscriptionPaymentBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionPaymentBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSubscription`'s `proration_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionProrationBehavior { - AlwaysInvoice, - CreateProrations, - None, -} - -impl SubscriptionProrationBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", - SubscriptionProrationBehavior::CreateProrations => "create_prorations", - SubscriptionProrationBehavior::None => "none", - } - } -} - -impl AsRef for SubscriptionProrationBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionProrationBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `Subscription`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionStatus { - Active, - Canceled, - Incomplete, - IncompleteExpired, - PastDue, - Trialing, - Unpaid, -} - -impl SubscriptionStatus { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionStatus::Active => "active", - SubscriptionStatus::Canceled => "canceled", - SubscriptionStatus::Incomplete => "incomplete", - SubscriptionStatus::IncompleteExpired => "incomplete_expired", - SubscriptionStatus::PastDue => "past_due", - SubscriptionStatus::Trialing => "trialing", - SubscriptionStatus::Unpaid => "unpaid", - } - } -} - -impl AsRef for SubscriptionStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListSubscriptions`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionStatusFilter { - Active, - All, - Canceled, - Ended, - Incomplete, - IncompleteExpired, - PastDue, - Trialing, - Unpaid, -} - -impl SubscriptionStatusFilter { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionStatusFilter::Active => "active", - SubscriptionStatusFilter::All => "all", - SubscriptionStatusFilter::Canceled => "canceled", - SubscriptionStatusFilter::Ended => "ended", - SubscriptionStatusFilter::Incomplete => "incomplete", - SubscriptionStatusFilter::IncompleteExpired => "incomplete_expired", - SubscriptionStatusFilter::PastDue => "past_due", - SubscriptionStatusFilter::Trialing => "trialing", - SubscriptionStatusFilter::Unpaid => "unpaid", - } - } -} - -impl AsRef for SubscriptionStatusFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionStatusFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SubscriptionsResourcePauseCollection`'s `behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionsResourcePauseCollectionBehavior { - KeepAsDraft, - MarkUncollectible, - Void, -} - -impl SubscriptionsResourcePauseCollectionBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionsResourcePauseCollectionBehavior::KeepAsDraft => "keep_as_draft", - SubscriptionsResourcePauseCollectionBehavior::MarkUncollectible => "mark_uncollectible", - SubscriptionsResourcePauseCollectionBehavior::Void => "void", - } - } -} - -impl AsRef for SubscriptionsResourcePauseCollectionBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionsResourcePauseCollectionBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `UpdateSubscriptionPauseCollection`'s `behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum UpdateSubscriptionPauseCollectionBehavior { - KeepAsDraft, - MarkUncollectible, - Void, -} - -impl UpdateSubscriptionPauseCollectionBehavior { - pub fn as_str(self) -> &'static str { - match self { - UpdateSubscriptionPauseCollectionBehavior::KeepAsDraft => "keep_as_draft", - UpdateSubscriptionPauseCollectionBehavior::MarkUncollectible => "mark_uncollectible", - UpdateSubscriptionPauseCollectionBehavior::Void => "void", - } - } -} - -impl AsRef for UpdateSubscriptionPauseCollectionBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for UpdateSubscriptionPauseCollectionBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/subscription_ext.rs b/ft-stripe/src/resources/subscription_ext.rs deleted file mode 100644 index c0b4eee..0000000 --- a/ft-stripe/src/resources/subscription_ext.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::SubscriptionId; -use crate::resources::{CreateSubscriptionItems, Subscription}; -use serde::Serialize; - -#[derive(Clone, Debug, Default, Serialize)] -pub struct CancelSubscription { - #[serde(skip_serializing_if = "Option::is_none")] - pub at_period_end: Option, -} - -impl CancelSubscription { - pub fn new() -> CancelSubscription { - CancelSubscription { at_period_end: None } - } -} - -impl Subscription { - /// Cancels a subscription. - /// - /// For more details see https://stripe.com/docs/api#cancel_subscription. - pub fn cancel( - client: &Client, - subscription_id: &SubscriptionId, - params: CancelSubscription, - ) -> Response { - client.delete_query(&format!("/subscriptions/{}", subscription_id), params) - } -} - -impl CreateSubscriptionItems { - pub fn new() -> Self { - Self { - billing_thresholds: Default::default(), - metadata: Default::default(), - plan: Default::default(), - price: Default::default(), - price_data: Default::default(), - quantity: Default::default(), - tax_rates: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/subscription_item.rs b/ft-stripe/src/resources/subscription_item.rs deleted file mode 100644 index c17b804..0000000 --- a/ft-stripe/src/resources/subscription_item.rs +++ /dev/null @@ -1,481 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{PlanId, PriceId, SubscriptionId, SubscriptionItemId}; -use crate::params::{Deleted, Expand, List, Metadata, Object, Timestamp}; -use crate::resources::{Currency, Plan, Price, SubscriptionItemBillingThresholds, TaxRate}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "SubscriptionItem". -/// -/// For more details see [https://stripe.com/docs/api/subscription_items/object](https://stripe.com/docs/api/subscription_items/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItem { - /// Unique identifier for the object. - pub id: SubscriptionItemId, - - /// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// The [quantity](https://stripe.com/docs/subscriptions/quantities) of the plan to which the customer should be subscribed. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The `subscription` this `subscription_item` belongs to. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option, - - /// The tax rates which apply to this `subscription_item`. - /// - /// When set, the `default_tax_rates` on the subscription do not apply to this `subscription_item`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -impl SubscriptionItem { - /// Returns a list of your subscription items for a given subscription. - pub fn list( - client: &Client, - params: ListSubscriptionItems<'_>, - ) -> Response> { - client.get_query("/subscription_items", ¶ms) - } - - /// Adds a new item to an existing subscription. - /// - /// No existing items will be changed or replaced. - pub fn create( - client: &Client, - params: CreateSubscriptionItem<'_>, - ) -> Response { - client.post_form("/subscription_items", ¶ms) - } - - /// Retrieves the invoice item with the given ID. - pub fn retrieve( - client: &Client, - id: &SubscriptionItemId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/subscription_items/{}", id), &Expand { expand }) - } - - /// Updates the plan or quantity of an item on a current subscription. - pub fn update( - client: &Client, - id: &SubscriptionItemId, - params: UpdateSubscriptionItem<'_>, - ) -> Response { - client.post_form(&format!("/subscription_items/{}", id), ¶ms) - } - - /// Deletes an item from the subscription. - /// - /// Removing a subscription item from a subscription will not cancel the subscription. - pub fn delete( - client: &Client, - id: &SubscriptionItemId, - ) -> Response> { - client.delete(&format!("/subscription_items/{}", id)) - } -} - -impl Object for SubscriptionItem { - type Id = SubscriptionItemId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription_item" - } -} - -/// The parameters for `SubscriptionItem::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateSubscriptionItem<'a> { - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - /// - /// When updating, pass an empty string to remove previously-defined thresholds. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. - /// - /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. - /// For example, SCA regulation may require 3DS authentication to complete payment. - /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. - /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). - /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. - /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. - /// This was the default behavior for API versions prior to 2019-03-14. - /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_behavior: Option, - - /// The identifier of the plan to add to the subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// The ID of the price object. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Data used to generate a new price object inline. - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - /// This field has been renamed to `proration_behavior`. - /// - /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub prorate: Option, - - /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. - /// - /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. - /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). - /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - /// If set, the proration will be calculated as though the subscription was updated at the given time. - /// - /// This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_date: Option, - - /// The quantity you'd like to apply to the subscription item you're creating. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The identifier of the subscription to modify. - pub subscription: SubscriptionId, - - /// A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. - /// - /// These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. - /// When updating, pass an empty string to remove previously-defined tax rates. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -impl<'a> CreateSubscriptionItem<'a> { - pub fn new(subscription: SubscriptionId) -> Self { - CreateSubscriptionItem { - billing_thresholds: Default::default(), - expand: Default::default(), - metadata: Default::default(), - payment_behavior: Default::default(), - plan: Default::default(), - price: Default::default(), - price_data: Default::default(), - prorate: Default::default(), - proration_behavior: Default::default(), - proration_date: Default::default(), - quantity: Default::default(), - subscription, - tax_rates: Default::default(), - } - } -} - -/// The parameters for `SubscriptionItem::list`. -#[derive(Clone, Debug, Serialize)] -pub struct ListSubscriptionItems<'a> { - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// The ID of the subscription whose items will be retrieved. - pub subscription: SubscriptionId, -} - -impl<'a> ListSubscriptionItems<'a> { - pub fn new(subscription: SubscriptionId) -> Self { - ListSubscriptionItems { - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - subscription, - } - } -} - -/// The parameters for `SubscriptionItem::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSubscriptionItem<'a> { - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - /// - /// When updating, pass an empty string to remove previously-defined thresholds. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// Indicates if a customer is on or off-session while an invoice payment is attempted. - #[serde(skip_serializing_if = "Option::is_none")] - pub off_session: Option, - - /// Use `allow_incomplete` to transition the subscription to `status=past_due` if a payment is required but cannot be paid. - /// - /// This allows you to manage scenarios where additional user actions are needed to pay a subscription's invoice. - /// For example, SCA regulation may require 3DS authentication to complete payment. - /// See the [SCA Migration Guide](https://stripe.com/docs/billing/migration/strong-customer-authentication) for Billing to learn more. - /// This is the default behavior. Use `pending_if_incomplete` to update the subscription using [pending updates](https://stripe.com/docs/billing/subscriptions/pending-updates). - /// When you use `pending_if_incomplete` you can only pass the parameters [supported by pending updates](https://stripe.com/docs/billing/pending-updates-reference#supported-attributes). Use `error_if_incomplete` if you want Stripe to return an HTTP 402 status code if a subscription's first invoice cannot be paid. - /// For example, if a payment method requires 3DS authentication due to SCA regulation and further user action is needed, this parameter does not create a subscription and returns an error instead. - /// This was the default behavior for API versions prior to 2019-03-14. - /// See the [changelog](https://stripe.com/docs/upgrades#2019-03-14) to learn more. - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_behavior: Option, - - /// The identifier of the new plan for this subscription item. - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - /// The ID of the price object. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - /// Data used to generate a new price object inline. - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - /// This field has been renamed to `proration_behavior`. - /// - /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub prorate: Option, - - /// Determines how to handle [prorations](https://stripe.com/docs/subscriptions/billing-cycle#prorations) when the billing cycle changes (e.g., when switching plans, resetting `billing_cycle_anchor=now`, or starting a trial), or if an item's `quantity` changes. - /// - /// Valid values are `create_prorations`, `none`, or `always_invoice`. Passing `create_prorations` will cause proration invoice items to be created when applicable. - /// These proration items will only be invoiced immediately under [certain conditions](https://stripe.com/docs/subscriptions/upgrading-downgrading#immediate-payment). - /// In order to always invoice immediately for prorations, pass `always_invoice`. Prorations can be disabled by passing `none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - /// If set, the proration will be calculated as though the subscription was updated at the given time. - /// - /// This can be used to apply the same proration that was previewed with the [upcoming invoice](https://stripe.com/docs/api#retrieve_customer_invoice) endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_date: Option, - - /// The quantity you'd like to apply to the subscription item you're creating. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// A list of [Tax Rate](https://stripe.com/docs/api/tax_rates) ids. - /// - /// These Tax Rates will override the [`default_tax_rates`](https://stripe.com/docs/api/subscriptions/create#create_subscription-default_tax_rates) on the Subscription. - /// When updating, pass an empty string to remove previously-defined tax rates. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -impl<'a> UpdateSubscriptionItem<'a> { - pub fn new() -> Self { - UpdateSubscriptionItem { - billing_thresholds: Default::default(), - expand: Default::default(), - metadata: Default::default(), - off_session: Default::default(), - payment_behavior: Default::default(), - plan: Default::default(), - price: Default::default(), - price_data: Default::default(), - prorate: Default::default(), - proration_behavior: Default::default(), - proration_date: Default::default(), - quantity: Default::default(), - tax_rates: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceData { - pub currency: Currency, - - pub product: String, - - pub recurring: SubscriptionItemPriceDataRecurring, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceDataRecurring { - pub interval: PlanInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, -} - -/// An enum representing the possible values of an `SubscriptionItemPriceDataRecurring`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanInterval { - Day, - Month, - Week, - Year, -} - -impl PlanInterval { - pub fn as_str(self) -> &'static str { - match self { - PlanInterval::Day => "day", - PlanInterval::Month => "month", - PlanInterval::Week => "week", - PlanInterval::Year => "year", - } - } -} - -impl AsRef for PlanInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSubscriptionItem`'s `payment_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionPaymentBehavior { - AllowIncomplete, - ErrorIfIncomplete, - PendingIfIncomplete, -} - -impl SubscriptionPaymentBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionPaymentBehavior::AllowIncomplete => "allow_incomplete", - SubscriptionPaymentBehavior::ErrorIfIncomplete => "error_if_incomplete", - SubscriptionPaymentBehavior::PendingIfIncomplete => "pending_if_incomplete", - } - } -} - -impl AsRef for SubscriptionPaymentBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionPaymentBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `CreateSubscriptionItem`'s `proration_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionProrationBehavior { - AlwaysInvoice, - CreateProrations, - None, -} - -impl SubscriptionProrationBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", - SubscriptionProrationBehavior::CreateProrations => "create_prorations", - SubscriptionProrationBehavior::None => "none", - } - } -} - -impl AsRef for SubscriptionProrationBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionProrationBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/subscription_item_ext.rs b/ft-stripe/src/resources/subscription_item_ext.rs deleted file mode 100644 index 8e19303..0000000 --- a/ft-stripe/src/resources/subscription_item_ext.rs +++ /dev/null @@ -1,162 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::config::{Client, Response}; -use crate::ids::{InvoiceId, SubscriptionItemId, UsageRecordId, UsageRecordSummaryId}; -use crate::params::{Expand, List, Object, Timestamp}; -use crate::OpenPeriod; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "UsageRecord". -/// -/// For more details see [https://stripe.com/docs/api/usage_records/](https://stripe.com/docs/api/usage_records/). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UsageRecord { - /// Unique identifier for the object. - pub id: UsageRecordId, - - /// The usage quantity for the specified date. - pub quantity: u64, - - /// The ID of the subscription item this usage record contains data for. - pub subscription_item: SubscriptionItemId, - - /// The timestamp when this usage occurred. - pub timestamp: Timestamp, -} - -/// Creates a usage record for a specified subscription item and date, and fills it with a quantity. -/// -/// For more details see [https://stripe.com/docs/api/usage_records/create](https://stripe.com/docs/api/usage_records/create). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateUsageRecord { - /// The usage quantity for the specified date. - pub quantity: u64, - - /// The timestamp when this usage occurred. - pub timestamp: Timestamp, - - /// Valid values are `Increment` (default) or `Set`. - /// When using `Increment` the specified quantity will be added to the usage at the specified timestamp. - /// The `Set` action will overwrite the usage quantity at that timestamp. - /// If the subscription has billing thresholds, `Increment` is the only allowed value. - #[serde(skip_serializing_if = "Option::is_none")] - pub action: Option, -} - -impl CreateUsageRecord { - pub fn new(quantity: u64, timestamp: Timestamp) -> Self { - CreateUsageRecord { quantity, timestamp, action: None } - } -} - -/// An enum specifying possible values for `CreateUsageRecord`'s `action` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum UsageRecordAction { - /// Deafult. The specified quantity will be added to the usage. - Increment, - - /// Overwrites the usage quantity. - Set, -} - -impl UsageRecord { - /// Creates a usage record for a specified subscription item and date, and fills it with a quantity. - /// - /// For more details see [https://stripe.com/docs/api/usage_records/create](https://stripe.com/docs/api/usage_records/create). - pub fn create( - client: &Client, - id: SubscriptionItemId, - params: CreateUsageRecord, - ) -> Response { - client.post_form(&format!("/subscription_items/{}/usage_records", id), ¶ms) - } -} - -/// The resource representing a Stripe "UsageRecordSummary". -/// -/// For more details see [https://stripe.com/docs/api/usage_records/subscription_item_summary_list](https://stripe.com/docs/api/usage_records/subscription_item_summary_list). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UsageRecordSummary { - /// Unique identifier for the object. - pub id: UsageRecordSummaryId, - - /// The invoice in which this usage period has been billed for. - pub invoice: Option, - - // The usage period. - pub period: OpenPeriod, - - /// The ID of the subscription item this summary is describing. - pub subscription_item: SubscriptionItemId, - - /// The total usage within this usage period. - pub total_usage: u64, -} - -impl UsageRecordSummary { - /// For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that’s been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). - /// - /// The list is sorted in reverse-chronological order (newest first). The first list item represents the most current usage period that hasn’t ended yet. Since new usage records can still be added, the returned summary information for the subscription item’s ID should be seen as unstable until the subscription billing period ends. - pub fn list( - client: &Client, - id: &SubscriptionItemId, - params: ListUsageRecordSummaries<'_>, - ) -> Response> { - // This is a bit of a strange API since params.subscription_item needs to go into the URL, - // but the rest of the parameters (except subscription_item) need to be passed via query params. - let url = format!("/subscription_items/{}/usage_record_summaries", &id); - client.get_query(&url, ¶ms) - } -} - -impl Object for UsageRecordSummary { - type Id = UsageRecordSummaryId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "usage_record_summary" - } -} - -/// For the specified subscription item, returns a list of summary objects. Each object in the list provides usage information that’s been summarized from multiple usage records and over a subscription billing period (e.g., 15 usage records in the month of September). -/// -/// The list is sorted in reverse-chronological order (newest first). The first list item represents the most current usage period that hasn’t ended yet. Since new usage records can still be added, the returned summary information for the subscription item’s ID should be seen as unstable until the subscription billing period ends. -/// For more details see [https://stripe.com/docs/api/usage_records/subscription_item_summary_list](https://stripe.com/docs/api/usage_records/subscription_item_summary_list). -#[derive(Clone, Debug, Serialize)] -pub struct ListUsageRecordSummaries<'a> { - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListUsageRecordSummaries<'a> { - pub fn new() -> Self { - ListUsageRecordSummaries { - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/subscription_schedule.rs b/ft-stripe/src/resources/subscription_schedule.rs deleted file mode 100644 index 3ddb45a..0000000 --- a/ft-stripe/src/resources/subscription_schedule.rs +++ /dev/null @@ -1,821 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, SubscriptionScheduleId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{ - CollectionMethod, Coupon, Currency, Customer, PaymentMethod, Plan, Price, Scheduled, - Subscription, SubscriptionBillingThresholds, SubscriptionItemBillingThresholds, TaxRate, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "SubscriptionSchedule". -/// -/// For more details see [https://stripe.com/docs/api/subscription_schedules/object](https://stripe.com/docs/api/subscription_schedules/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionSchedule { - /// Unique identifier for the object. - pub id: SubscriptionScheduleId, - - /// Time at which the subscription schedule was canceled. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled_at: Option, - - /// Time at which the subscription schedule was completed. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Object representing the start and end dates for the current phase of the subscription schedule, if it is `active`. - #[serde(skip_serializing_if = "Option::is_none")] - pub current_phase: Option, - - /// ID of the customer who owns the subscription schedule. - pub customer: Expandable, - - pub default_settings: SubscriptionScheduleDefaultSettings, - - /// Behavior of the subscription schedule and underlying subscription when it ends. - pub end_behavior: SubscriptionScheduleEndBehavior, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// Configuration for the subscription schedule's phases. - pub phases: Vec, - - /// Time at which the subscription schedule was released. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub released_at: Option, - - /// ID of the subscription once managed by the subscription schedule (if it is released). - #[serde(skip_serializing_if = "Option::is_none")] - pub released_subscription: Option, - - /// The present status of the subscription schedule. - /// - /// Possible values are `not_started`, `active`, `completed`, `released`, and `canceled`. - /// You can read more about the different states in our [behavior guide](https://stripe.com/docs/billing/subscriptions/subscription-schedules). - pub status: SubscriptionScheduleStatus, - - /// ID of the subscription managed by the subscription schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub subscription: Option>, -} - -impl SubscriptionSchedule { - /// Retrieves the list of your subscription schedules. - pub fn list( - client: &Client, - params: ListSubscriptionSchedules<'_>, - ) -> Response> { - client.get_query("/subscription_schedules", ¶ms) - } - - /// Creates a new subscription schedule object. - /// - /// Each customer can have up to 25 active or scheduled subscriptions. - pub fn create( - client: &Client, - params: CreateSubscriptionSchedule<'_>, - ) -> Response { - client.post_form("/subscription_schedules", ¶ms) - } - - /// Retrieves the details of an existing subscription schedule. - /// - /// You only need to supply the unique subscription schedule identifier that was returned upon subscription schedule creation. - pub fn retrieve( - client: &Client, - id: &SubscriptionScheduleId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/subscription_schedules/{}", id), &Expand { expand }) - } - - /// Updates an existing subscription schedule. - pub fn update( - client: &Client, - id: &SubscriptionScheduleId, - params: UpdateSubscriptionSchedule<'_>, - ) -> Response { - client.post_form(&format!("/subscription_schedules/{}", id), ¶ms) - } -} - -impl Object for SubscriptionSchedule { - type Id = SubscriptionScheduleId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "subscription_schedule" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleCurrentPhase { - /// The end of this phase of the subscription schedule. - pub end_date: Timestamp, - - /// The start of this phase of the subscription schedule. - pub start_date: Timestamp, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionSchedulePhaseConfiguration { - #[serde(skip_serializing_if = "Option::is_none")] - pub add_invoice_items: Option>, - - /// A non-negative decimal between 0 and 100, with at most two decimal places. - /// - /// This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner's Stripe account during this phase of the schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. - /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// ID of the coupon to use during this phase of the subscription schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option>, - - /// ID of the default payment method for the subscription schedule. - /// - /// It must belong to the customer associated with the subscription schedule. - /// If not set, invoices will use the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option>, - - /// The default tax rates to apply to the subscription during this phase of the subscription schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - /// The end of this phase of the subscription schedule. - pub end_date: Timestamp, - - /// The subscription schedule's default invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - /// Plans to subscribe during this phase of the subscription schedule. - pub plans: Vec, - - /// Controls whether or not the subscription schedule will prorate when transitioning to this phase. - /// - /// Values are `create_prorations` and `none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - /// The start of this phase of the subscription schedule. - pub start_date: Timestamp, - - /// If provided, each invoice created during this phase of the subscription schedule will apply the tax rate, increasing the amount billed to the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - /// When the trial ends within the phase. - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleAddInvoiceItem { - /// ID of the price used to generate the invoice item. - pub price: Expandable, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleConfigurationItem { - /// Define thresholds at which an invoice will be sent, and the related subscription advanced to a new billing period. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// ID of the plan to which the customer should be subscribed. - pub plan: Expandable, - - /// ID of the price to which the customer should be subscribed. - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option>, - - /// Quantity of the plan to which the customer should be subscribed. - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - /// The tax rates which apply to this `phase_item`. - /// - /// When set, the `default_tax_rates` on the phase do not apply to this `phase_item`. - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleDefaultSettings { - /// Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period. - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - /// Either `charge_automatically`, or `send_invoice`. - /// - /// When charging automatically, Stripe will attempt to pay the underlying subscription at the end of each billing cycle using the default source attached to the customer. - /// When sending an invoice, Stripe will email your customer an invoice with payment instructions. - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - /// ID of the default payment method for the subscription schedule. - /// - /// If not set, invoices will use the default payment method in the customer's invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option>, - - /// The subscription schedule's default invoice settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, -} - -/// The parameters for `SubscriptionSchedule::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateSubscriptionSchedule<'a> { - /// The identifier of the customer to create the subscription schedule for. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// Object representing the subscription schedule's default settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_settings: Option, - - /// Configures how the subscription schedule behaves when it ends. - /// - /// Possible values are `release` or `cancel` with the default being `release`. - /// `release` will end the subscription schedule and keep the underlying subscription running.`cancel` will end the subscription schedule and cancel the underlying subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub end_behavior: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Migrate an existing subscription to be managed by a subscription schedule. - /// - /// If this parameter is set, a subscription schedule will be created using the subscription's plan(s), set to auto-renew using the subscription's interval. - /// When using this parameter, other parameters (such as phase values) cannot be set. - /// To create a subscription schedule with other modifications, we recommend making two separate API calls. - #[serde(skip_serializing_if = "Option::is_none")] - pub from_subscription: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// List representing phases of the subscription schedule. - /// - /// Each phase can be customized to have different durations, plans, and coupons. - /// If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. - #[serde(skip_serializing_if = "Option::is_none")] - pub phases: Option>, - - /// When the subscription schedule starts. - /// - /// We recommend using `now` so that it starts the subscription immediately. - /// You can also use a Unix timestamp to backdate the subscription so that it starts on a past date, or set a future date for the subscription to start on. - #[serde(skip_serializing_if = "Option::is_none")] - pub start_date: Option, -} - -impl<'a> CreateSubscriptionSchedule<'a> { - pub fn new() -> Self { - CreateSubscriptionSchedule { - customer: Default::default(), - default_settings: Default::default(), - end_behavior: Default::default(), - expand: Default::default(), - from_subscription: Default::default(), - metadata: Default::default(), - phases: Default::default(), - start_date: Default::default(), - } - } -} - -/// The parameters for `SubscriptionSchedule::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListSubscriptionSchedules<'a> { - /// Only return subscription schedules that were created canceled the given date interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub canceled_at: Option>, - - /// Only return subscription schedules that completed during the given date interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option>, - - /// Only return subscription schedules that were created during the given date interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// Only return subscription schedules for the given customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// Only return subscription schedules that were released during the given date interval. - #[serde(skip_serializing_if = "Option::is_none")] - pub released_at: Option>, - - /// Only return subscription schedules that have not started yet. - #[serde(skip_serializing_if = "Option::is_none")] - pub scheduled: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListSubscriptionSchedules<'a> { - pub fn new() -> Self { - ListSubscriptionSchedules { - canceled_at: Default::default(), - completed_at: Default::default(), - created: Default::default(), - customer: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - released_at: Default::default(), - scheduled: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `SubscriptionSchedule::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateSubscriptionSchedule<'a> { - /// Object representing the subscription schedule's default settings. - #[serde(skip_serializing_if = "Option::is_none")] - pub default_settings: Option, - - /// Configures how the subscription schedule behaves when it ends. - /// - /// Possible values are `release` or `cancel` with the default being `release`. - /// `release` will end the subscription schedule and keep the underlying subscription running.`cancel` will end the subscription schedule and cancel the underlying subscription. - #[serde(skip_serializing_if = "Option::is_none")] - pub end_behavior: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// List representing phases of the subscription schedule. - /// - /// Each phase can be customized to have different durations, plans, and coupons. - /// If there are multiple phases, the `end_date` of one phase will always equal the `start_date` of the next phase. - /// Note that past phases can be omitted. - #[serde(skip_serializing_if = "Option::is_none")] - pub phases: Option>, - - /// This field has been renamed to `proration_behavior`. - /// - /// `prorate=true` can be replaced with `proration_behavior=create_prorations` and `prorate=false` can be replaced with `proration_behavior=none`. - #[serde(skip_serializing_if = "Option::is_none")] - pub prorate: Option, - - /// If the update changes the current phase, indicates if the changes should be prorated. - /// - /// Valid values are `create_prorations` or `none`, and the default value is `create_prorations`. - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, -} - -impl<'a> UpdateSubscriptionSchedule<'a> { - pub fn new() -> Self { - UpdateSubscriptionSchedule { - default_settings: Default::default(), - end_behavior: Default::default(), - expand: Default::default(), - metadata: Default::default(), - phases: Default::default(), - prorate: Default::default(), - proration_behavior: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateSubscriptionSchedulePhases { - #[serde(skip_serializing_if = "Option::is_none")] - pub add_invoice_items: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub end_date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub iterations: Option, - - pub plans: Vec, - - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub trial: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleDefaultSettingsParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct UpdateSubscriptionSchedulePhases { - #[serde(skip_serializing_if = "Option::is_none")] - pub add_invoice_items: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub application_fee_percent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub collection_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub coupon: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_payment_method: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default_tax_rates: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub end_date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub invoice_settings: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub iterations: Option, - - pub plans: Vec, - - #[serde(skip_serializing_if = "Option::is_none")] - pub proration_behavior: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub start_date: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_percent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub trial: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub trial_end: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct AddInvoiceItems { - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleBillingThresholds { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_gte: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub reset_billing_cycle_anchor: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionScheduleInvoiceSettings { - #[serde(skip_serializing_if = "Option::is_none")] - pub days_until_due: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionSchedulePhasesPlansParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_thresholds: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub plan: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub price_data: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub quantity: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tax_rates: Option>, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct InvoiceItemPriceData { - pub currency: Currency, - - pub product: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceData { - pub currency: Currency, - - pub product: String, - - pub recurring: SubscriptionItemPriceDataRecurring, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub unit_amount_decimal: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemPriceDataRecurring { - pub interval: PlanInterval, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_count: Option, -} - -/// An enum representing the possible values of an `SubscriptionItemPriceDataRecurring`'s `interval` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PlanInterval { - Day, - Month, - Week, - Year, -} - -impl PlanInterval { - pub fn as_str(self) -> &'static str { - match self { - PlanInterval::Day => "day", - PlanInterval::Month => "month", - PlanInterval::Week => "week", - PlanInterval::Year => "year", - } - } -} - -impl AsRef for PlanInterval { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for PlanInterval { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SubscriptionSchedulePhaseConfiguration`'s `proration_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionProrationBehavior { - AlwaysInvoice, - CreateProrations, - None, -} - -impl SubscriptionProrationBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionProrationBehavior::AlwaysInvoice => "always_invoice", - SubscriptionProrationBehavior::CreateProrations => "create_prorations", - SubscriptionProrationBehavior::None => "none", - } - } -} - -impl AsRef for SubscriptionProrationBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionProrationBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SubscriptionScheduleDefaultSettings`'s `collection_method` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionScheduleDefaultSettingsCollectionMethod { - ChargeAutomatically, - SendInvoice, -} - -impl SubscriptionScheduleDefaultSettingsCollectionMethod { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionScheduleDefaultSettingsCollectionMethod::ChargeAutomatically => { - "charge_automatically" - } - SubscriptionScheduleDefaultSettingsCollectionMethod::SendInvoice => "send_invoice", - } - } -} - -impl AsRef for SubscriptionScheduleDefaultSettingsCollectionMethod { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionScheduleDefaultSettingsCollectionMethod { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SubscriptionSchedule`'s `end_behavior` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionScheduleEndBehavior { - Cancel, - None, - Release, - Renew, -} - -impl SubscriptionScheduleEndBehavior { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionScheduleEndBehavior::Cancel => "cancel", - SubscriptionScheduleEndBehavior::None => "none", - SubscriptionScheduleEndBehavior::Release => "release", - SubscriptionScheduleEndBehavior::Renew => "renew", - } - } -} - -impl AsRef for SubscriptionScheduleEndBehavior { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionScheduleEndBehavior { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `SubscriptionSchedule`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SubscriptionScheduleStatus { - Active, - Canceled, - Completed, - NotStarted, - Released, -} - -impl SubscriptionScheduleStatus { - pub fn as_str(self) -> &'static str { - match self { - SubscriptionScheduleStatus::Active => "active", - SubscriptionScheduleStatus::Canceled => "canceled", - SubscriptionScheduleStatus::Completed => "completed", - SubscriptionScheduleStatus::NotStarted => "not_started", - SubscriptionScheduleStatus::Released => "released", - } - } -} - -impl AsRef for SubscriptionScheduleStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for SubscriptionScheduleStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/tax_deducted_at_source.rs b/ft-stripe/src/resources/tax_deducted_at_source.rs deleted file mode 100644 index 6a3f7dd..0000000 --- a/ft-stripe/src/resources/tax_deducted_at_source.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::params::{Object, Timestamp}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "TaxDeductedAtSource". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxDeductedAtSource { - /// The end of the invoicing period. - /// - /// This TDS applies to Stripe fees collected during this invoicing period. - pub period_end: Timestamp, - - /// The start of the invoicing period. - /// - /// This TDS applies to Stripe fees collected during this invoicing period. - pub period_start: Timestamp, - - /// The TAN that was supplied to Stripe when TDS was assessed. - pub tax_deduction_account_number: String, -} - -impl Object for TaxDeductedAtSource { - type Id = (); - fn id(&self) -> Self::Id {} - fn object(&self) -> &'static str { - "tax_deducted_at_source" - } -} diff --git a/ft-stripe/src/resources/tax_id.rs b/ft-stripe/src/resources/tax_id.rs deleted file mode 100644 index 4914721..0000000 --- a/ft-stripe/src/resources/tax_id.rs +++ /dev/null @@ -1,186 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::TaxIdId; -use crate::params::{Expandable, Object, Timestamp}; -use crate::resources::Customer; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "tax_id". -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxId { - /// Unique identifier for the object. - pub id: TaxIdId, - - /// Two-letter ISO code representing the country of the tax ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub country: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - /// ID of the customer. - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option>, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Type of the tax ID, one of `au_abn`, `br_cnpj`, `br_cpf`, `ca_bn`, `ca_qst`, `ch_vat`, `es_cif`, `eu_vat`, `hk_br`, `in_gst`, `jp_cn`, `kr_brn`, `li_uid`, `mx_rfc`, `my_itn`, `my_sst`, `no_vat`, `nz_gst`, `ru_inn`, `sg_gst`, `sg_uen`, `th_vat`, `tw_vat`, `us_ein`, or `za_vat`. - /// - /// Note that some legacy tax IDs have type `unknown`. - #[serde(rename = "type")] - #[serde(skip_serializing_if = "Option::is_none")] - pub type_: Option, - - /// Value of the tax ID. - #[serde(skip_serializing_if = "Option::is_none")] - pub value: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -impl Object for TaxId { - type Id = TaxIdId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "tax_id" - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxIdVerification { - /// Verification status, one of `pending`, `verified`, `unverified`, or `unavailable`. - pub status: TaxIdVerificationStatus, - - /// Verified address. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_address: Option, - - /// Verified name. - #[serde(skip_serializing_if = "Option::is_none")] - pub verified_name: Option, -} - -/// An enum representing the possible values of an `TaxId`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TaxIdType { - AuAbn, - BrCnpj, - BrCpf, - CaBn, - CaQst, - ChVat, - EsCif, - EuVat, - HkBr, - InGst, - JpCn, - KrBrn, - LiUid, - MxRfc, - MyItn, - MySst, - NoVat, - NzGst, - RuInn, - SgGst, - SgUen, - ThVat, - TwVat, - Unknown, - UsEin, - ZaVat, -} - -impl TaxIdType { - pub fn as_str(self) -> &'static str { - match self { - TaxIdType::AuAbn => "au_abn", - TaxIdType::BrCnpj => "br_cnpj", - TaxIdType::BrCpf => "br_cpf", - TaxIdType::CaBn => "ca_bn", - TaxIdType::CaQst => "ca_qst", - TaxIdType::ChVat => "ch_vat", - TaxIdType::EsCif => "es_cif", - TaxIdType::EuVat => "eu_vat", - TaxIdType::HkBr => "hk_br", - TaxIdType::InGst => "in_gst", - TaxIdType::JpCn => "jp_cn", - TaxIdType::KrBrn => "kr_brn", - TaxIdType::LiUid => "li_uid", - TaxIdType::MxRfc => "mx_rfc", - TaxIdType::MyItn => "my_itn", - TaxIdType::MySst => "my_sst", - TaxIdType::NoVat => "no_vat", - TaxIdType::NzGst => "nz_gst", - TaxIdType::RuInn => "ru_inn", - TaxIdType::SgGst => "sg_gst", - TaxIdType::SgUen => "sg_uen", - TaxIdType::ThVat => "th_vat", - TaxIdType::TwVat => "tw_vat", - TaxIdType::Unknown => "unknown", - TaxIdType::UsEin => "us_ein", - TaxIdType::ZaVat => "za_vat", - } - } -} - -impl AsRef for TaxIdType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TaxIdType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `TaxIdVerification`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TaxIdVerificationStatus { - Pending, - Unavailable, - Unverified, - Verified, -} - -impl TaxIdVerificationStatus { - pub fn as_str(self) -> &'static str { - match self { - TaxIdVerificationStatus::Pending => "pending", - TaxIdVerificationStatus::Unavailable => "unavailable", - TaxIdVerificationStatus::Unverified => "unverified", - TaxIdVerificationStatus::Verified => "verified", - } - } -} - -impl AsRef for TaxIdVerificationStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TaxIdVerificationStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/tax_rate.rs b/ft-stripe/src/resources/tax_rate.rs deleted file mode 100644 index 6b66031..0000000 --- a/ft-stripe/src/resources/tax_rate.rs +++ /dev/null @@ -1,248 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::TaxRateId; -use crate::params::{Expand, List, Metadata, Object, RangeQuery, Timestamp}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "TaxRate". -/// -/// For more details see [https://stripe.com/docs/api/tax_rates/object](https://stripe.com/docs/api/tax_rates/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TaxRate { - /// Unique identifier for the object. - pub id: TaxRateId, - - /// Defaults to `true`. - /// - /// When set to `false`, this tax rate cannot be applied to objects in the API, but will still be applied to subscriptions and invoices that already have it set. - pub active: bool, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// An arbitrary string attached to the tax rate for your internal use only. - /// - /// It will not be visible to your customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The display name of the tax rates as it will appear to your customer on their receipt email, PDF, and the hosted invoice page. - pub display_name: String, - - /// This specifies if the tax rate is inclusive or exclusive. - pub inclusive: bool, - - /// The jurisdiction for the tax rate. - #[serde(skip_serializing_if = "Option::is_none")] - pub jurisdiction: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// This represents the tax rate percent out of 100. - pub percentage: f64, -} - -impl TaxRate { - /// Returns a list of your tax rates. - /// - /// Tax rates are returned sorted by creation date, with the most recently created tax rates appearing first. - pub fn list(client: &Client, params: ListTaxRates<'_>) -> Response> { - client.get_query("/tax_rates", ¶ms) - } - - /// Creates a new tax rate. - pub fn create(client: &Client, params: CreateTaxRate<'_>) -> Response { - client.post_form("/tax_rates", ¶ms) - } - - /// Retrieves a tax rate with the given ID. - pub fn retrieve(client: &Client, id: &TaxRateId, expand: &[&str]) -> Response { - client.get_query(&format!("/tax_rates/{}", id), &Expand { expand }) - } - - /// Updates an existing tax rate. - pub fn update(client: &Client, id: &TaxRateId, params: UpdateTaxRate<'_>) -> Response { - client.post_form(&format!("/tax_rates/{}", id), ¶ms) - } -} - -impl Object for TaxRate { - type Id = TaxRateId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "tax_rate" - } -} - -/// The parameters for `TaxRate::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateTaxRate<'a> { - /// Flag determining whether the tax rate is active or inactive. - /// - /// Inactive tax rates continue to work where they are currently applied however they cannot be used for new applications. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// An arbitrary string attached to the tax rate for your internal use only. - /// - /// It will not be visible to your customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The display name of the tax rate, which will be shown to users. - pub display_name: &'a str, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// This specifies if the tax rate is inclusive or exclusive. - pub inclusive: bool, - - /// The jurisdiction for the tax rate. - #[serde(skip_serializing_if = "Option::is_none")] - pub jurisdiction: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// This represents the tax rate percent out of 100. - pub percentage: f64, -} - -impl<'a> CreateTaxRate<'a> { - pub fn new(display_name: &'a str, percentage: f64) -> Self { - CreateTaxRate { - active: Default::default(), - description: Default::default(), - display_name, - expand: Default::default(), - inclusive: Default::default(), - jurisdiction: Default::default(), - metadata: Default::default(), - percentage, - } - } -} - -/// The parameters for `TaxRate::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListTaxRates<'a> { - /// Optional flag to filter by tax rates that are either active or not active (archived). - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// Optional range for filtering created date. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Optional flag to filter by tax rates that are inclusive (or those that are not inclusive). - #[serde(skip_serializing_if = "Option::is_none")] - pub inclusive: Option, - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListTaxRates<'a> { - pub fn new() -> Self { - ListTaxRates { - active: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - inclusive: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `TaxRate::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateTaxRate<'a> { - /// Flag determining whether the tax rate is active or inactive. - /// - /// Inactive tax rates continue to work where they are currently applied however they cannot be used for new applications. - #[serde(skip_serializing_if = "Option::is_none")] - pub active: Option, - - /// An arbitrary string attached to the tax rate for your internal use only. - /// - /// It will not be visible to your customers. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The display name of the tax rate, which will be shown to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub display_name: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// The jurisdiction for the tax rate. - #[serde(skip_serializing_if = "Option::is_none")] - pub jurisdiction: Option<&'a str>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdateTaxRate<'a> { - pub fn new() -> Self { - UpdateTaxRate { - active: Default::default(), - description: Default::default(), - display_name: Default::default(), - expand: Default::default(), - jurisdiction: Default::default(), - metadata: Default::default(), - } - } -} diff --git a/ft-stripe/src/resources/token.rs b/ft-stripe/src/resources/token.rs deleted file mode 100644 index 327a846..0000000 --- a/ft-stripe/src/resources/token.rs +++ /dev/null @@ -1,230 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{CustomerId, TokenId}; -use crate::params::{Expand, Metadata, Object, Timestamp}; -use crate::resources::{ - Address, BankAccount, BusinessType, Card, CompanyParams, Dob, PersonParams, TokenType, -}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Token". -/// -/// For more details see [https://stripe.com/docs/api/tokens/object](https://stripe.com/docs/api/tokens/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Token { - /// Unique identifier for the object. - pub id: TokenId, - - #[serde(skip_serializing_if = "Option::is_none")] - pub bank_account: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - - /// IP address of the client that generated the token. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_ip: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Type of the token: `account`, `bank_account`, `card`, or `pii`. - #[serde(rename = "type")] - pub type_: TokenType, - - /// Whether this token has already been used (tokens can be used only once). - pub used: bool, -} - -impl Token { - /// Creates a single-use token that represents a bank account’s details. - /// This token can be used with any API method in place of a bank account dictionary. - /// - /// This token can be used only once, by attaching it to a [Custom account](https://stripe.com/docs/api#accounts). - pub fn create(client: &Client, params: CreateToken<'_>) -> Response { - client.post_form("/tokens", ¶ms) - } - - /// Retrieves the token with the given ID. - pub fn retrieve(client: &Client, id: &TokenId, expand: &[&str]) -> Response { - client.get_query(&format!("/tokens/{}", id), &Expand { expand }) - } -} - -impl Object for Token { - type Id = TokenId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "token" - } -} - -/// The parameters for `Token::create`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct CreateToken<'a> { - /// Information for the account this token will represent. - #[serde(skip_serializing_if = "Option::is_none")] - pub account: Option, - - /// The customer (owned by the application's account) for which to create a token. - /// - /// This can be used only with an [OAuth access token](https://stripe.com/docs/connect/standard-accounts) or [Stripe-Account header](https://stripe.com/docs/connect/authentication). - /// For more details, see [Cloning Saved Payment Methods](https://stripe.com/docs/connect/cloning-saved-payment-methods). - #[serde(skip_serializing_if = "Option::is_none")] - pub customer: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Information for the person this token will represent. - #[serde(skip_serializing_if = "Option::is_none")] - pub person: Option, - - /// The PII this token will represent. - #[serde(skip_serializing_if = "Option::is_none")] - pub pii: Option, -} - -impl<'a> CreateToken<'a> { - pub fn new() -> Self { - CreateToken { - account: Default::default(), - customer: Default::default(), - expand: Default::default(), - person: Default::default(), - pii: Default::default(), - } - } -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateTokenAccount { - #[serde(skip_serializing_if = "Option::is_none")] - pub business_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub company: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub individual: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tos_shown_and_accepted: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateTokenPerson { - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kana: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub address_kanji: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub dob: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub first_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub gender: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub id_number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kana: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub last_name_kanji: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub maiden_name: Option, - - #[serde(default)] - pub metadata: Metadata, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub relationship: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub ssn_last_4: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub verification: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateTokenPii { - #[serde(skip_serializing_if = "Option::is_none")] - pub id_number: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CreateTokenPersonRelationship { - #[serde(skip_serializing_if = "Option::is_none")] - pub director: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub executive: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub percent_ownership: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub representative: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PersonVerificationParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub additional_document: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub document: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct VerificationDocumentParams { - #[serde(skip_serializing_if = "Option::is_none")] - pub back: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub front: Option, -} diff --git a/ft-stripe/src/resources/token_ext.rs b/ft-stripe/src/resources/token_ext.rs deleted file mode 100644 index 54c6b71..0000000 --- a/ft-stripe/src/resources/token_ext.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `Token`'s `type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TokenType { - Account, - BankAccount, - Card, - Pii, -} - -impl TokenType { - pub fn as_str(self) -> &'static str { - match self { - TokenType::Account => "account", - TokenType::BankAccount => "bank_account", - TokenType::Card => "card", - TokenType::Pii => "pii", - } - } -} - -impl AsRef for TokenType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TokenType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/topup.rs b/ft-stripe/src/resources/topup.rs deleted file mode 100644 index 162928a..0000000 --- a/ft-stripe/src/resources/topup.rs +++ /dev/null @@ -1,272 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::TopupId; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{BalanceTransaction, Currency, Source}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Topup". -/// -/// For more details see [https://stripe.com/docs/api/topups/object](https://stripe.com/docs/api/topups/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Topup { - /// Unique identifier for the object. - pub id: TopupId, - - /// Amount transferred. - pub amount: i64, - - /// ID of the balance transaction that describes the impact of this top-up on your account balance. - /// - /// May not be specified depending on status of top-up. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// Date the funds are expected to arrive in your Stripe account for payouts. - /// - /// This factors in delays like weekends or bank holidays. - /// May not be specified depending on status of top-up. - #[serde(skip_serializing_if = "Option::is_none")] - pub expected_availability_date: Option, - - /// Error code explaining reason for top-up failure if available (see [the errors section](https://stripe.com/docs/api#errors) for a list of codes). - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_code: Option, - - /// Message to user further explaining reason for top-up failure if available. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure_message: Option, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - pub source: Source, - - /// Extra information about a top-up. - /// - /// This will appear on your source's bank statement. - /// It must contain at least one letter. - #[serde(skip_serializing_if = "Option::is_none")] - pub statement_descriptor: Option, - - /// The status of the top-up is either `canceled`, `failed`, `pending`, `reversed`, or `succeeded`. - pub status: TopupStatus, - - /// A string that identifies this top-up as part of a group. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option, -} - -impl Topup { - /// Returns a list of top-ups. - pub fn list(client: &Client, params: ListTopups<'_>) -> Response> { - client.get_query("/topups", ¶ms) - } - - /// Retrieves the details of a top-up that has previously been created. - /// - /// Supply the unique top-up ID that was returned from your previous request, and Stripe will return the corresponding top-up information. - pub fn retrieve(client: &Client, id: &TopupId, expand: &[&str]) -> Response { - client.get_query(&format!("/topups/{}", id), &Expand { expand }) - } - - /// Updates the metadata of a top-up. - /// - /// Other top-up details are not editable by design. - pub fn update(client: &Client, id: &TopupId, params: UpdateTopup<'_>) -> Response { - client.post_form(&format!("/topups/{}", id), ¶ms) - } -} - -impl Object for Topup { - type Id = TopupId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "topup" - } -} - -/// The parameters for `Topup::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListTopups<'a> { - /// A positive integer representing how much to transfer. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option>, - - /// A filter on the list, based on the object `created` field. - /// - /// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return top-ups that have the given status. - /// - /// One of `canceled`, `failed`, `pending` or `succeeded`. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, -} - -impl<'a> ListTopups<'a> { - pub fn new() -> Self { - ListTopups { - amount: Default::default(), - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - status: Default::default(), - } - } -} - -/// The parameters for `Topup::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateTopup<'a> { - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdateTopup<'a> { - pub fn new() -> Self { - UpdateTopup { - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - } - } -} - -/// An enum representing the possible values of an `Topup`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TopupStatus { - Canceled, - Failed, - Pending, - Reversed, - Succeeded, -} - -impl TopupStatus { - pub fn as_str(self) -> &'static str { - match self { - TopupStatus::Canceled => "canceled", - TopupStatus::Failed => "failed", - TopupStatus::Pending => "pending", - TopupStatus::Reversed => "reversed", - TopupStatus::Succeeded => "succeeded", - } - } -} - -impl AsRef for TopupStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TopupStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of an `ListTopups`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TopupStatusFilter { - Canceled, - Failed, - Pending, - Succeeded, -} - -impl TopupStatusFilter { - pub fn as_str(self) -> &'static str { - match self { - TopupStatusFilter::Canceled => "canceled", - TopupStatusFilter::Failed => "failed", - TopupStatusFilter::Pending => "pending", - TopupStatusFilter::Succeeded => "succeeded", - } - } -} - -impl AsRef for TopupStatusFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TopupStatusFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/transfer.rs b/ft-stripe/src/resources/transfer.rs deleted file mode 100644 index 9f69a2e..0000000 --- a/ft-stripe/src/resources/transfer.rs +++ /dev/null @@ -1,304 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::{ChargeId, TransferId}; -use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp}; -use crate::resources::{Account, BalanceTransaction, Charge, Currency, TransferReversal}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "Transfer". -/// -/// For more details see [https://stripe.com/docs/api/transfers/object](https://stripe.com/docs/api/transfers/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Transfer { - /// Unique identifier for the object. - pub id: TransferId, - - /// Amount in %s to be transferred. - pub amount: i64, - - /// Amount in %s reversed (can be less than the amount attribute on the transfer if a partial reversal was issued). - pub amount_reversed: i64, - - /// Balance transaction that describes the impact of this transfer on your account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// Time that this record of the transfer was first created. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// ID of the Stripe account the transfer was sent to. - #[serde(skip_serializing_if = "Option::is_none")] - pub destination: Option>, - - /// If the destination is a Stripe account, this will be the ID of the payment that the destination account received for the transfer. - #[serde(skip_serializing_if = "Option::is_none")] - pub destination_payment: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - pub livemode: bool, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// A list of reversals that have been applied to the transfer. - pub reversals: List, - - /// Whether the transfer has been fully reversed. - /// - /// If the transfer is only partially reversed, this attribute will still be false. - pub reversed: bool, - - /// ID of the charge or payment that was used to fund the transfer. - /// - /// If null, the transfer was funded from the available balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_transaction: Option>, - - /// The source balance this transfer came from. - /// - /// One of `card`, `fpx`, or `bank_account`. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_type: Option, - - /// A string that identifies this transaction as part of a group. - /// - /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option, -} - -impl Transfer { - /// Returns a list of existing transfers sent to connected accounts. - /// - /// The transfers are returned in sorted order, with the most recently created transfers appearing first. - pub fn list(client: &Client, params: ListTransfers<'_>) -> Response> { - client.get_query("/transfers", ¶ms) - } - - /// To send funds from your Stripe account to a connected account, you create a new transfer object. - /// - /// Your [Stripe balance](https://stripe.com/docs/api#balance) must be able to cover the transfer amount, or you’ll receive an “Insufficient Funds” error. - pub fn create(client: &Client, params: CreateTransfer<'_>) -> Response { - client.post_form("/transfers", ¶ms) - } - - /// Retrieves the details of an existing transfer. - /// - /// Supply the unique transfer ID from either a transfer creation request or the transfer list, and Stripe will return the corresponding transfer information. - pub fn retrieve(client: &Client, id: &TransferId, expand: &[&str]) -> Response { - client.get_query(&format!("/transfers/{}", id), &Expand { expand }) - } - - /// Updates the specified transfer by setting the values of the parameters passed. - /// - /// Any parameters not provided will be left unchanged. This request accepts only metadata as an argument. - pub fn update( - client: &Client, - id: &TransferId, - params: UpdateTransfer<'_>, - ) -> Response { - client.post_form(&format!("/transfers/{}", id), ¶ms) - } -} - -impl Object for Transfer { - type Id = TransferId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "transfer" - } -} - -/// The parameters for `Transfer::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateTransfer<'a> { - /// A positive integer in %s representing how much to transfer. - #[serde(skip_serializing_if = "Option::is_none")] - pub amount: Option, - - /// 3-letter [ISO code for currency](https://stripe.com/docs/payouts). - pub currency: Currency, - - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// You can use this parameter to transfer funds from a charge before they are added to your available balance. - /// - /// A pending balance will transfer immediately but the funds will not become available until the original charge becomes available. - /// [See the Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-availability) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_transaction: Option, - - /// The source balance to use for this transfer. - /// - /// One of `bank_account`, `card`, or `fpx`. - /// For most users, this will default to `card`. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_type: Option, - - /// A string that identifies this transaction as part of a group. - /// - /// See the [Connect documentation](https://stripe.com/docs/connect/charges-transfers#transfer-options) for details. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> CreateTransfer<'a> { - pub fn new(currency: Currency) -> Self { - CreateTransfer { - amount: Default::default(), - currency, - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - source_transaction: Default::default(), - source_type: Default::default(), - transfer_group: Default::default(), - } - } -} - -/// The parameters for `Transfer::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListTransfers<'a> { - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option>, - - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, - - /// Only return transfers with the specified transfer group. - #[serde(skip_serializing_if = "Option::is_none")] - pub transfer_group: Option<&'a str>, -} - -impl<'a> ListTransfers<'a> { - pub fn new() -> Self { - ListTransfers { - created: Default::default(), - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - transfer_group: Default::default(), - } - } -} - -/// The parameters for `Transfer::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateTransfer<'a> { - /// An arbitrary string attached to the object. - /// - /// Often useful for displaying to users. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, -} - -impl<'a> UpdateTransfer<'a> { - pub fn new() -> Self { - UpdateTransfer { - description: Default::default(), - expand: Default::default(), - metadata: Default::default(), - } - } -} - -/// An enum representing the possible values of an `CreateTransfer`'s `source_type` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum TransferSourceType { - BankAccount, - Card, - Fpx, -} - -impl TransferSourceType { - pub fn as_str(self) -> &'static str { - match self { - TransferSourceType::BankAccount => "bank_account", - TransferSourceType::Card => "card", - TransferSourceType::Fpx => "fpx", - } - } -} - -impl AsRef for TransferSourceType { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for TransferSourceType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/transfer_reversal.rs b/ft-stripe/src/resources/transfer_reversal.rs deleted file mode 100644 index 4d1bd30..0000000 --- a/ft-stripe/src/resources/transfer_reversal.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::ids::TransferReversalId; -use crate::params::{Expandable, Metadata, Object, Timestamp}; -use crate::resources::{BalanceTransaction, Currency, Refund, Transfer}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "TransferReversal". -/// -/// For more details see [https://stripe.com/docs/api/transfer_reversals/object](https://stripe.com/docs/api/transfer_reversals/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct TransferReversal { - /// Unique identifier for the object. - pub id: TransferReversalId, - - /// Amount, in %s. - pub amount: i64, - - /// Balance transaction that describes the impact on your account balance. - #[serde(skip_serializing_if = "Option::is_none")] - pub balance_transaction: Option>, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - pub created: Timestamp, - - /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. - /// - /// Must be a [supported currency](https://stripe.com/docs/currencies). - pub currency: Currency, - - /// Linked payment refund for the transfer reversal. - #[serde(skip_serializing_if = "Option::is_none")] - pub destination_payment_refund: Option>, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - pub metadata: Metadata, - - /// ID of the refund responsible for the transfer reversal. - #[serde(skip_serializing_if = "Option::is_none")] - pub source_refund: Option>, - - /// ID of the transfer that was reversed. - pub transfer: Expandable, -} - -impl Object for TransferReversal { - type Id = TransferReversalId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "transfer_reversal" - } -} diff --git a/ft-stripe/src/resources/types.rs b/ft-stripe/src/resources/types.rs deleted file mode 100644 index 610f8c7..0000000 --- a/ft-stripe/src/resources/types.rs +++ /dev/null @@ -1,726 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use crate::params::Timestamp; -use crate::resources::card::{CardBrand, CardType}; -use serde::{Deserialize, Serialize}; - -/// An enum representing the versions of the Stripe API. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ApiVersion { - #[serde(rename = "2011-01-01")] - V2011_01_01, - #[serde(rename = "2011-06-21")] - V2011_06_21, - #[serde(rename = "2011-06-28")] - V2011_06_28, - #[serde(rename = "2011-08-01")] - V2011_08_01, - #[serde(rename = "2011-09-15")] - V2011_09_15, - #[serde(rename = "2011-11-17")] - V2011_11_17, - #[serde(rename = "2012-02-23")] - V2012_02_23, - #[serde(rename = "2012-03-25")] - V2012_03_25, - #[serde(rename = "2012-06-18")] - V2012_06_18, - #[serde(rename = "2012-06-28")] - V2012_06_28, - #[serde(rename = "2012-07-09")] - V2012_07_09, - #[serde(rename = "2012-09-24")] - V2012_09_24, - #[serde(rename = "2012-10-26")] - V2012_10_26, - #[serde(rename = "2012-11-07")] - V2012_11_07, - #[serde(rename = "2013-02-11")] - V2013_02_11, - #[serde(rename = "2013-02-13")] - V2013_02_13, - #[serde(rename = "2013-07-05")] - V2013_07_05, - #[serde(rename = "2013-08-12")] - V2013_08_12, - #[serde(rename = "2013-08-13")] - V2013_08_13, - #[serde(rename = "2013-10-29")] - V2013_10_29, - #[serde(rename = "2013-12-03")] - V2013_12_03, - #[serde(rename = "2014-01-31")] - V2014_01_31, - #[serde(rename = "2014-03-13")] - V2014_03_13, - #[serde(rename = "2014-03-28")] - V2014_03_28, - #[serde(rename = "2014-05-19")] - V2014_05_19, - #[serde(rename = "2014-06-13")] - V2014_06_13, - #[serde(rename = "2014-06-17")] - V2014_06_17, - #[serde(rename = "2014-07-22")] - V2014_07_22, - #[serde(rename = "2014-07-26")] - V2014_07_26, - #[serde(rename = "2014-08-04")] - V2014_08_04, - #[serde(rename = "2014-08-20")] - V2014_08_20, - #[serde(rename = "2014-09-08")] - V2014_09_08, - #[serde(rename = "2014-10-07")] - V2014_10_07, - #[serde(rename = "2014-11-05")] - V2014_11_05, - #[serde(rename = "2014-11-20")] - V2014_11_20, - #[serde(rename = "2014-12-08")] - V2014_12_08, - #[serde(rename = "2014-12-17")] - V2014_12_17, - #[serde(rename = "2014-12-22")] - V2014_12_22, - #[serde(rename = "2015-01-11")] - V2015_01_11, - #[serde(rename = "2015-01-26")] - V2015_01_26, - #[serde(rename = "2015-02-10")] - V2015_02_10, - #[serde(rename = "2015-02-16")] - V2015_02_16, - #[serde(rename = "2015-02-18")] - V2015_02_18, - #[serde(rename = "2015-03-24")] - V2015_03_24, - #[serde(rename = "2015-04-07")] - V2015_04_07, - #[serde(rename = "2015-06-15")] - V2015_06_15, - #[serde(rename = "2015-07-07")] - V2015_07_07, - #[serde(rename = "2015-07-13")] - V2015_07_13, - #[serde(rename = "2015-07-28")] - V2015_07_28, - #[serde(rename = "2015-08-07")] - V2015_08_07, - #[serde(rename = "2015-08-19")] - V2015_08_19, - #[serde(rename = "2015-09-03")] - V2015_09_03, - #[serde(rename = "2015-09-08")] - V2015_09_08, - #[serde(rename = "2015-09-23")] - V2015_09_23, - #[serde(rename = "2015-10-01")] - V2015_10_01, - #[serde(rename = "2015-10-12")] - V2015_10_12, - #[serde(rename = "2015-10-16")] - V2015_10_16, - #[serde(rename = "2016-02-03")] - V2016_02_03, - #[serde(rename = "2016-02-19")] - V2016_02_19, - #[serde(rename = "2016-02-22")] - V2016_02_22, - #[serde(rename = "2016-02-23")] - V2016_02_23, - #[serde(rename = "2016-02-29")] - V2016_02_29, - #[serde(rename = "2016-03-07")] - V2016_03_07, - #[serde(rename = "2016-06-15")] - V2016_06_15, - #[serde(rename = "2016-07-06")] - V2016_07_06, - #[serde(rename = "2016-10-19")] - V2016_10_19, - #[serde(rename = "2017-01-27")] - V2017_01_27, - #[serde(rename = "2017-02-14")] - V2017_02_14, - #[serde(rename = "2017-04-06")] - V2017_04_06, - #[serde(rename = "2017-05-25")] - V2017_05_25, - #[serde(rename = "2017-06-05")] - V2017_06_05, - #[serde(rename = "2017-08-15")] - V2017_08_15, - #[serde(rename = "2017-12-14")] - V2017_12_14, - #[serde(rename = "2018-01-23")] - V2018_01_23, - #[serde(rename = "2018-02-05")] - V2018_02_05, - #[serde(rename = "2018-02-06")] - V2018_02_06, - #[serde(rename = "2018-02-28")] - V2018_02_28, - #[serde(rename = "2018-05-21")] - V2018_05_21, - #[serde(rename = "2018-07-27")] - V2018_07_27, - #[serde(rename = "2018-08-23")] - V2018_08_23, - #[serde(rename = "2018-09-06")] - V2018_09_06, - #[serde(rename = "2018-09-24")] - V2018_09_24, - #[serde(rename = "2018-10-31")] - V2018_10_31, - #[serde(rename = "2018-11-08")] - V2018_11_08, - #[serde(rename = "2019-02-11")] - V2019_02_11, - #[serde(rename = "2019-02-19")] - V2019_02_19, - #[serde(rename = "2019-03-14")] - V2019_03_14, - #[serde(rename = "2019-05-16")] - V2019_05_16, - #[serde(rename = "2019-08-14")] - V2019_08_14, - #[serde(rename = "2019-09-09")] - V2019_09_09, -} - -impl ApiVersion { - pub fn as_str(self) -> &'static str { - match self { - ApiVersion::V2011_01_01 => "2011-01-01", - ApiVersion::V2011_06_21 => "2011-06-21", - ApiVersion::V2011_06_28 => "2011-06-28", - ApiVersion::V2011_08_01 => "2011-08-01", - ApiVersion::V2011_09_15 => "2011-09-15", - ApiVersion::V2011_11_17 => "2011-11-17", - ApiVersion::V2012_02_23 => "2012-02-23", - ApiVersion::V2012_03_25 => "2012-03-25", - ApiVersion::V2012_06_18 => "2012-06-18", - ApiVersion::V2012_06_28 => "2012-06-28", - ApiVersion::V2012_07_09 => "2012-07-09", - ApiVersion::V2012_09_24 => "2012-09-24", - ApiVersion::V2012_10_26 => "2012-10-26", - ApiVersion::V2012_11_07 => "2012-11-07", - ApiVersion::V2013_02_11 => "2013-02-11", - ApiVersion::V2013_02_13 => "2013-02-13", - ApiVersion::V2013_07_05 => "2013-07-05", - ApiVersion::V2013_08_12 => "2013-08-12", - ApiVersion::V2013_08_13 => "2013-08-13", - ApiVersion::V2013_10_29 => "2013-10-29", - ApiVersion::V2013_12_03 => "2013-12-03", - ApiVersion::V2014_01_31 => "2014-01-31", - ApiVersion::V2014_03_13 => "2014-03-13", - ApiVersion::V2014_03_28 => "2014-03-28", - ApiVersion::V2014_05_19 => "2014-05-19", - ApiVersion::V2014_06_13 => "2014-06-13", - ApiVersion::V2014_06_17 => "2014-06-17", - ApiVersion::V2014_07_22 => "2014-07-22", - ApiVersion::V2014_07_26 => "2014-07-26", - ApiVersion::V2014_08_04 => "2014-08-04", - ApiVersion::V2014_08_20 => "2014-08-20", - ApiVersion::V2014_09_08 => "2014-09-08", - ApiVersion::V2014_10_07 => "2014-10-07", - ApiVersion::V2014_11_05 => "2014-11-05", - ApiVersion::V2014_11_20 => "2014-11-20", - ApiVersion::V2014_12_08 => "2014-12-08", - ApiVersion::V2014_12_17 => "2014-12-17", - ApiVersion::V2014_12_22 => "2014-12-22", - ApiVersion::V2015_01_11 => "2015-01-11", - ApiVersion::V2015_01_26 => "2015-01-26", - ApiVersion::V2015_02_10 => "2015-02-10", - ApiVersion::V2015_02_16 => "2015-02-16", - ApiVersion::V2015_02_18 => "2015-02-18", - ApiVersion::V2015_03_24 => "2015-03-24", - ApiVersion::V2015_04_07 => "2015-04-07", - ApiVersion::V2015_06_15 => "2015-06-15", - ApiVersion::V2015_07_07 => "2015-07-07", - ApiVersion::V2015_07_13 => "2015-07-13", - ApiVersion::V2015_07_28 => "2015-07-28", - ApiVersion::V2015_08_07 => "2015-08-07", - ApiVersion::V2015_08_19 => "2015-08-19", - ApiVersion::V2015_09_03 => "2015-09-03", - ApiVersion::V2015_09_08 => "2015-09-08", - ApiVersion::V2015_09_23 => "2015-09-23", - ApiVersion::V2015_10_01 => "2015-10-01", - ApiVersion::V2015_10_12 => "2015-10-12", - ApiVersion::V2015_10_16 => "2015-10-16", - ApiVersion::V2016_02_03 => "2016-02-03", - ApiVersion::V2016_02_19 => "2016-02-19", - ApiVersion::V2016_02_22 => "2016-02-22", - ApiVersion::V2016_02_23 => "2016-02-23", - ApiVersion::V2016_02_29 => "2016-02-29", - ApiVersion::V2016_03_07 => "2016-03-07", - ApiVersion::V2016_06_15 => "2016-06-15", - ApiVersion::V2016_07_06 => "2016-07-06", - ApiVersion::V2016_10_19 => "2016-10-19", - ApiVersion::V2017_01_27 => "2017-01-27", - ApiVersion::V2017_02_14 => "2017-02-14", - ApiVersion::V2017_04_06 => "2017-04-06", - ApiVersion::V2017_05_25 => "2017-05-25", - ApiVersion::V2017_06_05 => "2017-06-05", - ApiVersion::V2017_08_15 => "2017-08-15", - ApiVersion::V2017_12_14 => "2017-12-14", - ApiVersion::V2018_01_23 => "2018-01-23", - ApiVersion::V2018_02_05 => "2018-02-05", - ApiVersion::V2018_02_06 => "2018-02-06", - ApiVersion::V2018_02_28 => "2018-02-28", - ApiVersion::V2018_05_21 => "2018-05-21", - ApiVersion::V2018_07_27 => "2018-07-27", - ApiVersion::V2018_08_23 => "2018-08-23", - ApiVersion::V2018_09_06 => "2018-09-06", - ApiVersion::V2018_09_24 => "2018-09-24", - ApiVersion::V2018_10_31 => "2018-10-31", - ApiVersion::V2018_11_08 => "2018-11-08", - ApiVersion::V2019_02_11 => "2019-02-11", - ApiVersion::V2019_02_19 => "2019-02-19", - ApiVersion::V2019_03_14 => "2019-03-14", - ApiVersion::V2019_05_16 => "2019-05-16", - ApiVersion::V2019_08_14 => "2019-08-14", - ApiVersion::V2019_09_09 => "2019-09-09", - } - } -} - -impl AsRef for ApiVersion { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for ApiVersion { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} - -/// An enum representing the possible values of a `BankAccount`'s `account_holder_type` field. -/// -/// For more details see [https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_type](https://stripe.com/docs/api/customer_bank_accounts/object#customer_bank_account_object-account_holder_type) -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum AccountHolderType { - Individual, - Company, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Address { - /// Address line 1 or block/building number (e.g. Street address/PO Box/Company name) - pub line1: Option, - /// Address line 2 or building details (e.g. Apartment/Suite/Unit/Building) - pub line2: Option, - /// City (or Ward) - pub city: Option, - /// State (or Prefecture) - pub state: Option, - /// ZIP or postal code - pub postal_code: Option, - /// Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)) - pub country: Option, - /// The town/cho-me (Japan only) - pub town: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct BillingDetails { - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, - - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct CustomField { - pub name: String, - pub value: String, -} - -/// A date of birth. -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Dob { - pub day: i64, - pub month: i64, - pub year: i64, -} - -/// An enum representing the possible values of a `FraudDetails`'s `report` fields. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum FraudDetailsReport { - Fraudulent, - Safe, -} - -#[derive(Clone, Debug, Default, Deserialize, Serialize)] -pub struct PackageDimensions { - pub height: f64, - pub length: f64, - pub weight: f64, - pub width: f64, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodAchDebit { - /// Type of entity that holds the account. This can be either `individual` or `company`. - pub account_holder_type: AccountHolderType, - - /// Name of the bank associated with the bank account. - pub bank_name: String, - - /// Two-letter ISO code representing the country the bank account is located in. - pub country: String, - - /// Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same. - pub fingerprint: String, - - /// Last four digits of the bank account number. - pub last4: String, - - /// Routing transit number of the bank account. - pub routing_number: String, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -pub enum PaymentMethodCardBrand { - #[serde(rename = "amex")] - AmericanExpress, - #[serde(rename = "diners")] - DinersClub, - #[serde(rename = "discover")] - Discover, - #[serde(rename = "jcb")] - JCB, - #[serde(rename = "visa")] - Visa, - #[serde(rename = "mastercard")] - MasterCard, - #[serde(rename = "unionpay")] - UnionPay, - - /// An unknown card brand. - /// - /// May also be a variant not yet supported by the library. - #[serde(other)] - #[serde(rename = "unknown")] - Unknown, -} - -impl From for CardBrand { - fn from(brand: PaymentMethodCardBrand) -> Self { - match brand { - PaymentMethodCardBrand::AmericanExpress => CardBrand::AmericanExpress, - PaymentMethodCardBrand::DinersClub => CardBrand::DinersClub, - PaymentMethodCardBrand::Discover => CardBrand::Discover, - PaymentMethodCardBrand::JCB => CardBrand::JCB, - PaymentMethodCardBrand::Visa => CardBrand::Visa, - PaymentMethodCardBrand::MasterCard => CardBrand::MasterCard, - PaymentMethodCardBrand::UnionPay => CardBrand::UnionPay, - PaymentMethodCardBrand::Unknown => CardBrand::Unknown, - } - } -} - -impl From for PaymentMethodCardBrand { - fn from(brand: CardBrand) -> Self { - match brand { - CardBrand::AmericanExpress => PaymentMethodCardBrand::AmericanExpress, - CardBrand::DinersClub => PaymentMethodCardBrand::DinersClub, - CardBrand::Discover => PaymentMethodCardBrand::Discover, - CardBrand::JCB => PaymentMethodCardBrand::JCB, - CardBrand::Visa => PaymentMethodCardBrand::Visa, - CardBrand::MasterCard => PaymentMethodCardBrand::MasterCard, - CardBrand::UnionPay => PaymentMethodCardBrand::UnionPay, - CardBrand::Unknown => PaymentMethodCardBrand::Unknown, - } - } -} - -#[derive(Clone, Debug, Default, Deserialize, Serialize)] -pub struct PaymentMethodCard { - /// Can be `American Express`, `Diners Club`, `Discover`, `JCB`, `MasterCard`, `UnionPay`, `Visa`, or `Unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option, - - /// Two-letter ISO code representing the country of the card. - /// - /// You could use this attribute to get a sense of the international breakdown of cards you've collected. - pub country: String, - - /// Two-digit number representing the card's expiration month. - pub exp_month: i64, - - /// Four-digit number representing the card's expiration year. - pub exp_year: i64, - - /// Uniquely identifies this particular card number. - /// - /// You can use this attribute to check whether two customers who've signed up with you are using the same card number, for example. - pub fingerprint: String, - - /// Card funding type. - /// - /// Can be `credit`, `debit`, `prepaid`, or `unknown`. - #[serde(skip_serializing_if = "Option::is_none")] - pub funding: Option, - - /// The last four digits of the card. - pub last4: String, -} - -// TODO: Implement -/// This type is a stub that still needs to be implemented. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum PaymentMethodDetailsType { - AchDebit, - Card, - - /// An unknown payment method details type. - /// - /// May also be a variant not yet supported by the library. - #[serde(other)] - Unknown, -} - -// TODO: Implement -/// This type is a stub that still needs to be implemented. -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct PaymentMethodDetails { - #[serde(skip_serializing_if = "Option::is_none")] - pub ach_debit: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option, - pub r#type: PaymentMethodDetailsType, -} - -/// Period is a structure representing a start and end dates. -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Period { - pub start: Timestamp, - pub end: Timestamp, -} - -/// OpenPeriod is a structure representing a possibly open-ended period with optional start and end dates. -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct OpenPeriod { - pub start: Option, - pub end: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Shipping { - pub name: String, - pub address: Address, - #[serde(skip_serializing_if = "Option::is_none")] - pub carrier: Option, // eg. Fedex, UPS, USPS - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub tracking_number: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct ShippingParams { - pub address: Address, - pub name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub phone: Option, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SpendingLimit { - /// Maximum amount allowed to spend per time interval. - pub amount: i64, - - /// Array of strings containing [categories](https://stripe.com/docs/api#issuing_authorization_object-merchant_data-category) on which to apply the spending limit. - /// - /// Leave this blank to limit all charges. - #[serde(skip_serializing_if = "Option::is_none")] - pub categories: Option>, - - /// The time interval with which to apply this spending limit towards. - /// - /// Allowed values are `per_authorization`, `daily`, `weekly`, `monthly`, `yearly`, or `all_time`. - pub interval: SpendingLimitInterval, -} - -/// An enum representing the possible values of an `SpendingLimit`'s `interval` field. -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum SpendingLimitInterval { - AllTime, - Daily, - Monthly, - PerAuthorization, - Weekly, - Yearly, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionBillingThresholds { - #[serde(skip_serializing_if = "Option::is_none")] - pub amount_gte: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub reset_billing_cycle_anchor: Option, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(untagged)] -pub enum DelayDays { - Days(u32), - Other(DelayDaysOther), -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum DelayDaysOther { - Minimum, -} - -impl DelayDays { - pub fn days(n: u32) -> Self { - DelayDays::Days(n) - } - pub fn minimum() -> Self { - DelayDays::Other(DelayDaysOther::Minimum) - } -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(untagged)] -pub enum Scheduled { - Timestamp(Timestamp), - Other(ScheduledOther), -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ScheduledOther { - Now, -} - -impl Scheduled { - pub fn at(ts: Timestamp) -> Self { - Scheduled::Timestamp(ts) - } - pub fn now() -> Self { - Scheduled::Other(ScheduledOther::Now) - } -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(untagged)] -pub enum UpTo { - Max(u64), - Other(UpToOther), -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum UpToOther { - Inf, -} - -impl UpTo { - pub fn max(n: u64) -> Self { - UpTo::Max(n) - } - pub fn now() -> Self { - UpTo::Other(UpToOther::Inf) - } -} - -/// A day of the week. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum Weekday { - Sunday, - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(untagged)] -pub enum PaymentIntentOffSession { - Exists(bool), - Other(OffSessionOther), -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum OffSessionOther { - #[serde(rename = "one_off")] - OneOff, - #[serde(rename = "recurring")] - Recurring, -} - -impl PaymentIntentOffSession { - pub fn exists(n: bool) -> Self { - PaymentIntentOffSession::Exists(n) - } - pub fn frequency(n: OffSessionOther) -> Self { - match n { - OffSessionOther::OneOff => PaymentIntentOffSession::Other(OffSessionOther::OneOff), - OffSessionOther::Recurring => { - PaymentIntentOffSession::Other(OffSessionOther::Recurring) - } - } - } -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum SetupIntentUsage { - #[serde(rename = "on_session")] - OnSession, - #[serde(rename = "off_session")] - OffSession, -} - -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct SubscriptionItemBillingThresholds { - pub usage_gte: i64, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum BusinessType { - Individual, - Company, -} - -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum ApiErrors { - #[serde(rename = "api_connection_error")] - ApiConnectionError, - #[serde(rename = "api_error")] - ApiError, - #[serde(rename = "authentication_error")] - AuthenticationError, - #[serde(rename = "card_error")] - CardError, - #[serde(rename = "idempotency_error")] - IdempotencyError, - #[serde(rename = "invalid_request_error")] - InvalidRequestError, - #[serde(rename = "rate_limit_error")] - RateLimitError, -} diff --git a/ft-stripe/src/resources/webhook_endpoint.rs b/ft-stripe/src/resources/webhook_endpoint.rs deleted file mode 100644 index 6a45050..0000000 --- a/ft-stripe/src/resources/webhook_endpoint.rs +++ /dev/null @@ -1,745 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -// ====================================== -// This file was automatically generated. -// ====================================== - -use crate::config::{Client, Response}; -use crate::ids::WebhookEndpointId; -use crate::params::{Deleted, Expand, List, Metadata, Object, Timestamp}; -use crate::resources::{ApiVersion, WebhookEndpointStatus}; -use serde::{Deserialize, Serialize}; - -/// The resource representing a Stripe "NotificationWebhookEndpoint". -/// -/// For more details see [https://stripe.com/docs/api/webhook_endpoints/object](https://stripe.com/docs/api/webhook_endpoints/object). -#[derive(Clone, Debug, Deserialize, Serialize)] -pub struct WebhookEndpoint { - /// Unique identifier for the object. - pub id: WebhookEndpointId, - - /// The API version events are rendered as for this webhook endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub api_version: Option, - - /// The ID of the associated Connect application. - #[serde(skip_serializing_if = "Option::is_none")] - pub application: Option, - - /// Time at which the object was created. - /// - /// Measured in seconds since the Unix epoch. - #[serde(skip_serializing_if = "Option::is_none")] - pub created: Option, - - // Always true for a deleted object - #[serde(default)] - pub deleted: bool, - - /// An optional description of what the wehbook is used for. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - - /// The list of events to enable for this endpoint. - /// - /// `['*']` indicates that all events are enabled, except those that require explicit selection. - #[serde(skip_serializing_if = "Option::is_none")] - pub enabled_events: Option>, - - /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub livemode: Option, - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - #[serde(default)] - pub metadata: Metadata, - - /// The endpoint's secret, used to generate [webhook signatures](https://stripe.com/docs/webhooks/signatures). - /// - /// Only returned at creation. - #[serde(skip_serializing_if = "Option::is_none")] - pub secret: Option, - - /// The status of the webhook. - /// - /// It can be `enabled` or `disabled`. - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - - /// The URL of the webhook endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, -} - -impl WebhookEndpoint { - /// Returns a list of your webhook endpoints. - pub fn list( - client: &Client, - params: ListWebhookEndpoints<'_>, - ) -> Response> { - client.get_query("/webhook_endpoints", ¶ms) - } - - /// A webhook endpoint must have a `url` and a list of `enabled_events`. - /// - /// You may optionally specify the Boolean `connect` parameter. - /// If set to true, then a Connect webhook endpoint that notifies the specified `url` about events from all connected accounts is created; otherwise an account webhook endpoint that notifies the specified `url` only about events from your account is created. - /// You can also create webhook endpoints in the [webhooks settings](https://dashboard.stripe.com/account/webhooks) section of the Dashboard. - pub fn create(client: &Client, params: CreateWebhookEndpoint<'_>) -> Response { - client.post_form("/webhook_endpoints", ¶ms) - } - - /// Retrieves the webhook endpoint with the given ID. - pub fn retrieve( - client: &Client, - id: &WebhookEndpointId, - expand: &[&str], - ) -> Response { - client.get_query(&format!("/webhook_endpoints/{}", id), &Expand { expand }) - } - - /// Updates the webhook endpoint. - /// - /// You may edit the `url`, the list of `enabled_events`, and the status of your endpoint. - pub fn update( - client: &Client, - id: &WebhookEndpointId, - params: UpdateWebhookEndpoint<'_>, - ) -> Response { - client.post_form(&format!("/webhook_endpoints/{}", id), ¶ms) - } - - /// You can also delete webhook endpoints via the [webhook endpoint management](https://dashboard.stripe.com/account/webhooks) page of the Stripe dashboard. - pub fn delete(client: &Client, id: &WebhookEndpointId) -> Response> { - client.delete(&format!("/webhook_endpoints/{}", id)) - } -} - -impl Object for WebhookEndpoint { - type Id = WebhookEndpointId; - fn id(&self) -> Self::Id { - self.id.clone() - } - fn object(&self) -> &'static str { - "webhook_endpoint" - } -} - -/// The parameters for `WebhookEndpoint::create`. -#[derive(Clone, Debug, Serialize)] -pub struct CreateWebhookEndpoint<'a> { - /// Events sent to this endpoint will be generated with this Stripe Version instead of your account's default Stripe Version. - #[serde(skip_serializing_if = "Option::is_none")] - pub api_version: Option, - - /// Whether this endpoint should receive events from connected accounts (`true`), or from your account (`false`). - /// - /// Defaults to `false`. - #[serde(skip_serializing_if = "Option::is_none")] - pub connect: Option, - - /// An optional description of what the wehbook is used for. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// The list of events to enable for this endpoint. - /// - /// You may specify `['*']` to enable all events, except those that require explicit selection. - pub enabled_events: Vec, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The URL of the webhook endpoint. - pub url: &'a str, -} - -impl<'a> CreateWebhookEndpoint<'a> { - pub fn new(enabled_events: Vec, url: &'a str) -> Self { - CreateWebhookEndpoint { - api_version: Default::default(), - connect: Default::default(), - description: Default::default(), - enabled_events, - expand: Default::default(), - metadata: Default::default(), - url, - } - } -} - -/// The parameters for `WebhookEndpoint::list`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct ListWebhookEndpoints<'a> { - /// A cursor for use in pagination. - /// - /// `ending_before` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub ending_before: Option, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// A limit on the number of objects to be returned. - /// - /// Limit can range between 1 and 100, and the default is 10. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - - /// A cursor for use in pagination. - /// - /// `starting_after` is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list. - #[serde(skip_serializing_if = "Option::is_none")] - pub starting_after: Option, -} - -impl<'a> ListWebhookEndpoints<'a> { - pub fn new() -> Self { - ListWebhookEndpoints { - ending_before: Default::default(), - expand: Default::default(), - limit: Default::default(), - starting_after: Default::default(), - } - } -} - -/// The parameters for `WebhookEndpoint::update`. -#[derive(Clone, Debug, Serialize, Default)] -pub struct UpdateWebhookEndpoint<'a> { - /// An optional description of what the wehbook is used for. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<&'a str>, - - /// Disable the webhook endpoint if set to true. - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled: Option, - - /// The list of events to enable for this endpoint. - /// - /// You may specify `['*']` to enable all events, except those that require explicit selection. - #[serde(skip_serializing_if = "Option::is_none")] - pub enabled_events: Option>, - - /// Specifies which fields in the response should be expanded. - #[serde(skip_serializing_if = "Expand::is_empty")] - pub expand: &'a [&'a str], - - /// Set of key-value pairs that you can attach to an object. - /// - /// This can be useful for storing additional information about the object in a structured format. - /// Individual keys can be unset by posting an empty value to them. - /// All keys can be unset by posting an empty value to `metadata`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - - /// The URL of the webhook endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option<&'a str>, -} - -impl<'a> UpdateWebhookEndpoint<'a> { - pub fn new() -> Self { - UpdateWebhookEndpoint { - description: Default::default(), - disabled: Default::default(), - enabled_events: Default::default(), - expand: Default::default(), - metadata: Default::default(), - url: Default::default(), - } - } -} - -/// An enum representing the possible values of an `CreateWebhookEndpoint`'s `enabled_events` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum EventFilter { - #[serde(rename = "*")] - All, - #[serde(rename = "account.application.authorized")] - AccountApplicationAuthorized, - #[serde(rename = "account.application.deauthorized")] - AccountApplicationDeauthorized, - #[serde(rename = "account.external_account.created")] - AccountExternalAccountCreated, - #[serde(rename = "account.external_account.deleted")] - AccountExternalAccountDeleted, - #[serde(rename = "account.external_account.updated")] - AccountExternalAccountUpdated, - #[serde(rename = "account.updated")] - AccountUpdated, - #[serde(rename = "application_fee.created")] - ApplicationFeeCreated, - #[serde(rename = "application_fee.refund.updated")] - ApplicationFeeRefundUpdated, - #[serde(rename = "application_fee.refunded")] - ApplicationFeeRefunded, - #[serde(rename = "balance.available")] - BalanceAvailable, - #[serde(rename = "capability.updated")] - CapabilityUpdated, - #[serde(rename = "charge.captured")] - ChargeCaptured, - #[serde(rename = "charge.dispute.closed")] - ChargeDisputeClosed, - #[serde(rename = "charge.dispute.created")] - ChargeDisputeCreated, - #[serde(rename = "charge.dispute.funds_reinstated")] - ChargeDisputeFundsReinstated, - #[serde(rename = "charge.dispute.funds_withdrawn")] - ChargeDisputeFundsWithdrawn, - #[serde(rename = "charge.dispute.updated")] - ChargeDisputeUpdated, - #[serde(rename = "charge.expired")] - ChargeExpired, - #[serde(rename = "charge.failed")] - ChargeFailed, - #[serde(rename = "charge.pending")] - ChargePending, - #[serde(rename = "charge.refund.updated")] - ChargeRefundUpdated, - #[serde(rename = "charge.refunded")] - ChargeRefunded, - #[serde(rename = "charge.succeeded")] - ChargeSucceeded, - #[serde(rename = "charge.updated")] - ChargeUpdated, - #[serde(rename = "checkout.session.completed")] - CheckoutSessionCompleted, - #[serde(rename = "coupon.created")] - CouponCreated, - #[serde(rename = "coupon.deleted")] - CouponDeleted, - #[serde(rename = "coupon.updated")] - CouponUpdated, - #[serde(rename = "credit_note.created")] - CreditNoteCreated, - #[serde(rename = "credit_note.updated")] - CreditNoteUpdated, - #[serde(rename = "credit_note.voided")] - CreditNoteVoided, - #[serde(rename = "customer.created")] - CustomerCreated, - #[serde(rename = "customer.deleted")] - CustomerDeleted, - #[serde(rename = "customer.discount.created")] - CustomerDiscountCreated, - #[serde(rename = "customer.discount.deleted")] - CustomerDiscountDeleted, - #[serde(rename = "customer.discount.updated")] - CustomerDiscountUpdated, - #[serde(rename = "customer.source.created")] - CustomerSourceCreated, - #[serde(rename = "customer.source.deleted")] - CustomerSourceDeleted, - #[serde(rename = "customer.source.expiring")] - CustomerSourceExpiring, - #[serde(rename = "customer.source.updated")] - CustomerSourceUpdated, - #[serde(rename = "customer.subscription.created")] - CustomerSubscriptionCreated, - #[serde(rename = "customer.subscription.deleted")] - CustomerSubscriptionDeleted, - #[serde(rename = "customer.subscription.pending_update_applied")] - CustomerSubscriptionPendingUpdateApplied, - #[serde(rename = "customer.subscription.pending_update_expired")] - CustomerSubscriptionPendingUpdateExpired, - #[serde(rename = "customer.subscription.trial_will_end")] - CustomerSubscriptionTrialWillEnd, - #[serde(rename = "customer.subscription.updated")] - CustomerSubscriptionUpdated, - #[serde(rename = "customer.tax_id.created")] - CustomerTaxIdCreated, - #[serde(rename = "customer.tax_id.deleted")] - CustomerTaxIdDeleted, - #[serde(rename = "customer.tax_id.updated")] - CustomerTaxIdUpdated, - #[serde(rename = "customer.updated")] - CustomerUpdated, - #[serde(rename = "file.created")] - FileCreated, - #[serde(rename = "invoice.created")] - InvoiceCreated, - #[serde(rename = "invoice.deleted")] - InvoiceDeleted, - #[serde(rename = "invoice.finalized")] - InvoiceFinalized, - #[serde(rename = "invoice.marked_uncollectible")] - InvoiceMarkedUncollectible, - #[serde(rename = "invoice.payment_action_required")] - InvoicePaymentActionRequired, - #[serde(rename = "invoice.payment_failed")] - InvoicePaymentFailed, - #[serde(rename = "invoice.payment_succeeded")] - InvoicePaymentSucceeded, - #[serde(rename = "invoice.sent")] - InvoiceSent, - #[serde(rename = "invoice.upcoming")] - InvoiceUpcoming, - #[serde(rename = "invoice.updated")] - InvoiceUpdated, - #[serde(rename = "invoice.voided")] - InvoiceVoided, - #[serde(rename = "invoiceitem.created")] - InvoiceitemCreated, - #[serde(rename = "invoiceitem.deleted")] - InvoiceitemDeleted, - #[serde(rename = "invoiceitem.updated")] - InvoiceitemUpdated, - #[serde(rename = "issuing_authorization.created")] - IssuingAuthorizationCreated, - #[serde(rename = "issuing_authorization.request")] - IssuingAuthorizationRequest, - #[serde(rename = "issuing_authorization.updated")] - IssuingAuthorizationUpdated, - #[serde(rename = "issuing_card.created")] - IssuingCardCreated, - #[serde(rename = "issuing_card.updated")] - IssuingCardUpdated, - #[serde(rename = "issuing_cardholder.created")] - IssuingCardholderCreated, - #[serde(rename = "issuing_cardholder.updated")] - IssuingCardholderUpdated, - #[serde(rename = "issuing_transaction.created")] - IssuingTransactionCreated, - #[serde(rename = "issuing_transaction.updated")] - IssuingTransactionUpdated, - #[serde(rename = "mandate.updated")] - MandateUpdated, - #[serde(rename = "order.created")] - OrderCreated, - #[serde(rename = "order.payment_failed")] - OrderPaymentFailed, - #[serde(rename = "order.payment_succeeded")] - OrderPaymentSucceeded, - #[serde(rename = "order.updated")] - OrderUpdated, - #[serde(rename = "order_return.created")] - OrderReturnCreated, - #[serde(rename = "payment_intent.amount_capturable_updated")] - PaymentIntentAmountCapturableUpdated, - #[serde(rename = "payment_intent.canceled")] - PaymentIntentCanceled, - #[serde(rename = "payment_intent.created")] - PaymentIntentCreated, - #[serde(rename = "payment_intent.payment_failed")] - PaymentIntentPaymentFailed, - #[serde(rename = "payment_intent.processing")] - PaymentIntentProcessing, - #[serde(rename = "payment_intent.succeeded")] - PaymentIntentSucceeded, - #[serde(rename = "payment_method.attached")] - PaymentMethodAttached, - #[serde(rename = "payment_method.card_automatically_updated")] - PaymentMethodCardAutomaticallyUpdated, - #[serde(rename = "payment_method.detached")] - PaymentMethodDetached, - #[serde(rename = "payment_method.updated")] - PaymentMethodUpdated, - #[serde(rename = "payout.canceled")] - PayoutCanceled, - #[serde(rename = "payout.created")] - PayoutCreated, - #[serde(rename = "payout.failed")] - PayoutFailed, - #[serde(rename = "payout.paid")] - PayoutPaid, - #[serde(rename = "payout.updated")] - PayoutUpdated, - #[serde(rename = "person.created")] - PersonCreated, - #[serde(rename = "person.deleted")] - PersonDeleted, - #[serde(rename = "person.updated")] - PersonUpdated, - #[serde(rename = "plan.created")] - PlanCreated, - #[serde(rename = "plan.deleted")] - PlanDeleted, - #[serde(rename = "plan.updated")] - PlanUpdated, - #[serde(rename = "product.created")] - ProductCreated, - #[serde(rename = "product.deleted")] - ProductDeleted, - #[serde(rename = "product.updated")] - ProductUpdated, - #[serde(rename = "radar.early_fraud_warning.created")] - RadarEarlyFraudWarningCreated, - #[serde(rename = "radar.early_fraud_warning.updated")] - RadarEarlyFraudWarningUpdated, - #[serde(rename = "recipient.created")] - RecipientCreated, - #[serde(rename = "recipient.deleted")] - RecipientDeleted, - #[serde(rename = "recipient.updated")] - RecipientUpdated, - #[serde(rename = "reporting.report_run.failed")] - ReportingReportRunFailed, - #[serde(rename = "reporting.report_run.succeeded")] - ReportingReportRunSucceeded, - #[serde(rename = "reporting.report_type.updated")] - ReportingReportTypeUpdated, - #[serde(rename = "review.closed")] - ReviewClosed, - #[serde(rename = "review.opened")] - ReviewOpened, - #[serde(rename = "setup_intent.canceled")] - SetupIntentCanceled, - #[serde(rename = "setup_intent.created")] - SetupIntentCreated, - #[serde(rename = "setup_intent.setup_failed")] - SetupIntentSetupFailed, - #[serde(rename = "setup_intent.succeeded")] - SetupIntentSucceeded, - #[serde(rename = "sigma.scheduled_query_run.created")] - SigmaScheduledQueryRunCreated, - #[serde(rename = "sku.created")] - SkuCreated, - #[serde(rename = "sku.deleted")] - SkuDeleted, - #[serde(rename = "sku.updated")] - SkuUpdated, - #[serde(rename = "source.canceled")] - SourceCanceled, - #[serde(rename = "source.chargeable")] - SourceChargeable, - #[serde(rename = "source.failed")] - SourceFailed, - #[serde(rename = "source.mandate_notification")] - SourceMandateNotification, - #[serde(rename = "source.refund_attributes_required")] - SourceRefundAttributesRequired, - #[serde(rename = "source.transaction.created")] - SourceTransactionCreated, - #[serde(rename = "source.transaction.updated")] - SourceTransactionUpdated, - #[serde(rename = "subscription_schedule.aborted")] - SubscriptionScheduleAborted, - #[serde(rename = "subscription_schedule.canceled")] - SubscriptionScheduleCanceled, - #[serde(rename = "subscription_schedule.completed")] - SubscriptionScheduleCompleted, - #[serde(rename = "subscription_schedule.created")] - SubscriptionScheduleCreated, - #[serde(rename = "subscription_schedule.expiring")] - SubscriptionScheduleExpiring, - #[serde(rename = "subscription_schedule.released")] - SubscriptionScheduleReleased, - #[serde(rename = "subscription_schedule.updated")] - SubscriptionScheduleUpdated, - #[serde(rename = "tax_rate.created")] - TaxRateCreated, - #[serde(rename = "tax_rate.updated")] - TaxRateUpdated, - #[serde(rename = "topup.canceled")] - TopupCanceled, - #[serde(rename = "topup.created")] - TopupCreated, - #[serde(rename = "topup.failed")] - TopupFailed, - #[serde(rename = "topup.reversed")] - TopupReversed, - #[serde(rename = "topup.succeeded")] - TopupSucceeded, - #[serde(rename = "transfer.created")] - TransferCreated, - #[serde(rename = "transfer.failed")] - TransferFailed, - #[serde(rename = "transfer.paid")] - TransferPaid, - #[serde(rename = "transfer.reversed")] - TransferReversed, - #[serde(rename = "transfer.updated")] - TransferUpdated, -} - -impl EventFilter { - pub fn as_str(self) -> &'static str { - match self { - EventFilter::All => "*", - EventFilter::AccountApplicationAuthorized => "account.application.authorized", - EventFilter::AccountApplicationDeauthorized => "account.application.deauthorized", - EventFilter::AccountExternalAccountCreated => "account.external_account.created", - EventFilter::AccountExternalAccountDeleted => "account.external_account.deleted", - EventFilter::AccountExternalAccountUpdated => "account.external_account.updated", - EventFilter::AccountUpdated => "account.updated", - EventFilter::ApplicationFeeCreated => "application_fee.created", - EventFilter::ApplicationFeeRefundUpdated => "application_fee.refund.updated", - EventFilter::ApplicationFeeRefunded => "application_fee.refunded", - EventFilter::BalanceAvailable => "balance.available", - EventFilter::CapabilityUpdated => "capability.updated", - EventFilter::ChargeCaptured => "charge.captured", - EventFilter::ChargeDisputeClosed => "charge.dispute.closed", - EventFilter::ChargeDisputeCreated => "charge.dispute.created", - EventFilter::ChargeDisputeFundsReinstated => "charge.dispute.funds_reinstated", - EventFilter::ChargeDisputeFundsWithdrawn => "charge.dispute.funds_withdrawn", - EventFilter::ChargeDisputeUpdated => "charge.dispute.updated", - EventFilter::ChargeExpired => "charge.expired", - EventFilter::ChargeFailed => "charge.failed", - EventFilter::ChargePending => "charge.pending", - EventFilter::ChargeRefundUpdated => "charge.refund.updated", - EventFilter::ChargeRefunded => "charge.refunded", - EventFilter::ChargeSucceeded => "charge.succeeded", - EventFilter::ChargeUpdated => "charge.updated", - EventFilter::CheckoutSessionCompleted => "checkout.session.completed", - EventFilter::CouponCreated => "coupon.created", - EventFilter::CouponDeleted => "coupon.deleted", - EventFilter::CouponUpdated => "coupon.updated", - EventFilter::CreditNoteCreated => "credit_note.created", - EventFilter::CreditNoteUpdated => "credit_note.updated", - EventFilter::CreditNoteVoided => "credit_note.voided", - EventFilter::CustomerCreated => "customer.created", - EventFilter::CustomerDeleted => "customer.deleted", - EventFilter::CustomerDiscountCreated => "customer.discount.created", - EventFilter::CustomerDiscountDeleted => "customer.discount.deleted", - EventFilter::CustomerDiscountUpdated => "customer.discount.updated", - EventFilter::CustomerSourceCreated => "customer.source.created", - EventFilter::CustomerSourceDeleted => "customer.source.deleted", - EventFilter::CustomerSourceExpiring => "customer.source.expiring", - EventFilter::CustomerSourceUpdated => "customer.source.updated", - EventFilter::CustomerSubscriptionCreated => "customer.subscription.created", - EventFilter::CustomerSubscriptionDeleted => "customer.subscription.deleted", - EventFilter::CustomerSubscriptionPendingUpdateApplied => { - "customer.subscription.pending_update_applied" - } - EventFilter::CustomerSubscriptionPendingUpdateExpired => { - "customer.subscription.pending_update_expired" - } - EventFilter::CustomerSubscriptionTrialWillEnd => "customer.subscription.trial_will_end", - EventFilter::CustomerSubscriptionUpdated => "customer.subscription.updated", - EventFilter::CustomerTaxIdCreated => "customer.tax_id.created", - EventFilter::CustomerTaxIdDeleted => "customer.tax_id.deleted", - EventFilter::CustomerTaxIdUpdated => "customer.tax_id.updated", - EventFilter::CustomerUpdated => "customer.updated", - EventFilter::FileCreated => "file.created", - EventFilter::InvoiceCreated => "invoice.created", - EventFilter::InvoiceDeleted => "invoice.deleted", - EventFilter::InvoiceFinalized => "invoice.finalized", - EventFilter::InvoiceMarkedUncollectible => "invoice.marked_uncollectible", - EventFilter::InvoicePaymentActionRequired => "invoice.payment_action_required", - EventFilter::InvoicePaymentFailed => "invoice.payment_failed", - EventFilter::InvoicePaymentSucceeded => "invoice.payment_succeeded", - EventFilter::InvoiceSent => "invoice.sent", - EventFilter::InvoiceUpcoming => "invoice.upcoming", - EventFilter::InvoiceUpdated => "invoice.updated", - EventFilter::InvoiceVoided => "invoice.voided", - EventFilter::InvoiceitemCreated => "invoiceitem.created", - EventFilter::InvoiceitemDeleted => "invoiceitem.deleted", - EventFilter::InvoiceitemUpdated => "invoiceitem.updated", - EventFilter::IssuingAuthorizationCreated => "issuing_authorization.created", - EventFilter::IssuingAuthorizationRequest => "issuing_authorization.request", - EventFilter::IssuingAuthorizationUpdated => "issuing_authorization.updated", - EventFilter::IssuingCardCreated => "issuing_card.created", - EventFilter::IssuingCardUpdated => "issuing_card.updated", - EventFilter::IssuingCardholderCreated => "issuing_cardholder.created", - EventFilter::IssuingCardholderUpdated => "issuing_cardholder.updated", - EventFilter::IssuingTransactionCreated => "issuing_transaction.created", - EventFilter::IssuingTransactionUpdated => "issuing_transaction.updated", - EventFilter::MandateUpdated => "mandate.updated", - EventFilter::OrderCreated => "order.created", - EventFilter::OrderPaymentFailed => "order.payment_failed", - EventFilter::OrderPaymentSucceeded => "order.payment_succeeded", - EventFilter::OrderUpdated => "order.updated", - EventFilter::OrderReturnCreated => "order_return.created", - EventFilter::PaymentIntentAmountCapturableUpdated => { - "payment_intent.amount_capturable_updated" - } - EventFilter::PaymentIntentCanceled => "payment_intent.canceled", - EventFilter::PaymentIntentCreated => "payment_intent.created", - EventFilter::PaymentIntentPaymentFailed => "payment_intent.payment_failed", - EventFilter::PaymentIntentProcessing => "payment_intent.processing", - EventFilter::PaymentIntentSucceeded => "payment_intent.succeeded", - EventFilter::PaymentMethodAttached => "payment_method.attached", - EventFilter::PaymentMethodCardAutomaticallyUpdated => { - "payment_method.card_automatically_updated" - } - EventFilter::PaymentMethodDetached => "payment_method.detached", - EventFilter::PaymentMethodUpdated => "payment_method.updated", - EventFilter::PayoutCanceled => "payout.canceled", - EventFilter::PayoutCreated => "payout.created", - EventFilter::PayoutFailed => "payout.failed", - EventFilter::PayoutPaid => "payout.paid", - EventFilter::PayoutUpdated => "payout.updated", - EventFilter::PersonCreated => "person.created", - EventFilter::PersonDeleted => "person.deleted", - EventFilter::PersonUpdated => "person.updated", - EventFilter::PlanCreated => "plan.created", - EventFilter::PlanDeleted => "plan.deleted", - EventFilter::PlanUpdated => "plan.updated", - EventFilter::ProductCreated => "product.created", - EventFilter::ProductDeleted => "product.deleted", - EventFilter::ProductUpdated => "product.updated", - EventFilter::RadarEarlyFraudWarningCreated => "radar.early_fraud_warning.created", - EventFilter::RadarEarlyFraudWarningUpdated => "radar.early_fraud_warning.updated", - EventFilter::RecipientCreated => "recipient.created", - EventFilter::RecipientDeleted => "recipient.deleted", - EventFilter::RecipientUpdated => "recipient.updated", - EventFilter::ReportingReportRunFailed => "reporting.report_run.failed", - EventFilter::ReportingReportRunSucceeded => "reporting.report_run.succeeded", - EventFilter::ReportingReportTypeUpdated => "reporting.report_type.updated", - EventFilter::ReviewClosed => "review.closed", - EventFilter::ReviewOpened => "review.opened", - EventFilter::SetupIntentCanceled => "setup_intent.canceled", - EventFilter::SetupIntentCreated => "setup_intent.created", - EventFilter::SetupIntentSetupFailed => "setup_intent.setup_failed", - EventFilter::SetupIntentSucceeded => "setup_intent.succeeded", - EventFilter::SigmaScheduledQueryRunCreated => "sigma.scheduled_query_run.created", - EventFilter::SkuCreated => "sku.created", - EventFilter::SkuDeleted => "sku.deleted", - EventFilter::SkuUpdated => "sku.updated", - EventFilter::SourceCanceled => "source.canceled", - EventFilter::SourceChargeable => "source.chargeable", - EventFilter::SourceFailed => "source.failed", - EventFilter::SourceMandateNotification => "source.mandate_notification", - EventFilter::SourceRefundAttributesRequired => "source.refund_attributes_required", - EventFilter::SourceTransactionCreated => "source.transaction.created", - EventFilter::SourceTransactionUpdated => "source.transaction.updated", - EventFilter::SubscriptionScheduleAborted => "subscription_schedule.aborted", - EventFilter::SubscriptionScheduleCanceled => "subscription_schedule.canceled", - EventFilter::SubscriptionScheduleCompleted => "subscription_schedule.completed", - EventFilter::SubscriptionScheduleCreated => "subscription_schedule.created", - EventFilter::SubscriptionScheduleExpiring => "subscription_schedule.expiring", - EventFilter::SubscriptionScheduleReleased => "subscription_schedule.released", - EventFilter::SubscriptionScheduleUpdated => "subscription_schedule.updated", - EventFilter::TaxRateCreated => "tax_rate.created", - EventFilter::TaxRateUpdated => "tax_rate.updated", - EventFilter::TopupCanceled => "topup.canceled", - EventFilter::TopupCreated => "topup.created", - EventFilter::TopupFailed => "topup.failed", - EventFilter::TopupReversed => "topup.reversed", - EventFilter::TopupSucceeded => "topup.succeeded", - EventFilter::TransferCreated => "transfer.created", - EventFilter::TransferFailed => "transfer.failed", - EventFilter::TransferPaid => "transfer.paid", - EventFilter::TransferReversed => "transfer.reversed", - EventFilter::TransferUpdated => "transfer.updated", - } - } -} - -impl AsRef for EventFilter { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for EventFilter { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -} diff --git a/ft-stripe/src/resources/webhook_endpoint_ext.rs b/ft-stripe/src/resources/webhook_endpoint_ext.rs deleted file mode 100644 index 38e9865..0000000 --- a/ft-stripe/src/resources/webhook_endpoint_ext.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Code taken from https://github.com/wyyerd/stripe-rs/tree/c2f03f8dec41e20b66f9bbe902b8384096ac653c -use serde::{Deserialize, Serialize}; - -/// An enum representing the possible values of an `WebhookEndpoint`'s `status` field. -#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] -#[serde(rename_all = "snake_case")] -pub enum WebhookEndpointStatus { - Disabled, - Enabled, -} - -impl WebhookEndpointStatus { - pub fn as_str(self) -> &'static str { - match self { - WebhookEndpointStatus::Disabled => "disabled", - WebhookEndpointStatus::Enabled => "enabled", - } - } -} - -impl AsRef for WebhookEndpointStatus { - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl std::fmt::Display for WebhookEndpointStatus { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - self.as_str().fmt(f) - } -}